ProxyAutoConfig.cpp 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031
  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. #include "ProxyAutoConfig.h"
  7. #include "nsICancelable.h"
  8. #include "nsIDNSListener.h"
  9. #include "nsIDNSRecord.h"
  10. #include "nsIDNSService.h"
  11. #include "nsThreadUtils.h"
  12. #include "nsIConsoleService.h"
  13. #include "nsIURLParser.h"
  14. #include "nsJSUtils.h"
  15. #include "jsfriendapi.h"
  16. #include "prnetdb.h"
  17. #include "nsITimer.h"
  18. #include "mozilla/Mutex.h"
  19. #include "mozilla/net/DNS.h"
  20. #include "nsServiceManagerUtils.h"
  21. #include "nsNetCID.h"
  22. namespace mozilla {
  23. namespace net {
  24. // These are some global helper symbols the PAC format requires that we provide that
  25. // are initialized as part of the global javascript context used for PAC evaluations.
  26. // Additionally dnsResolve(host) and myIpAddress() are supplied in the same context
  27. // but are implemented as c++ helpers. alert(msg) is similarly defined.
  28. static const char *sPacUtils =
  29. "function dnsDomainIs(host, domain) {\n"
  30. " return (host.length >= domain.length &&\n"
  31. " host.substring(host.length - domain.length) == domain);\n"
  32. "}\n"
  33. ""
  34. "function dnsDomainLevels(host) {\n"
  35. " return host.split('.').length - 1;\n"
  36. "}\n"
  37. ""
  38. "function convert_addr(ipchars) {\n"
  39. " var bytes = ipchars.split('.');\n"
  40. " var result = ((bytes[0] & 0xff) << 24) |\n"
  41. " ((bytes[1] & 0xff) << 16) |\n"
  42. " ((bytes[2] & 0xff) << 8) |\n"
  43. " (bytes[3] & 0xff);\n"
  44. " return result;\n"
  45. "}\n"
  46. ""
  47. "function isInNet(ipaddr, pattern, maskstr) {\n"
  48. " var test = /^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$/.exec(ipaddr);\n"
  49. " if (test == null) {\n"
  50. " ipaddr = dnsResolve(ipaddr);\n"
  51. " if (ipaddr == null)\n"
  52. " return false;\n"
  53. " } else if (test[1] > 255 || test[2] > 255 || \n"
  54. " test[3] > 255 || test[4] > 255) {\n"
  55. " return false; // not an IP address\n"
  56. " }\n"
  57. " var host = convert_addr(ipaddr);\n"
  58. " var pat = convert_addr(pattern);\n"
  59. " var mask = convert_addr(maskstr);\n"
  60. " return ((host & mask) == (pat & mask));\n"
  61. " \n"
  62. "}\n"
  63. ""
  64. "function isPlainHostName(host) {\n"
  65. " return (host.search('\\\\.') == -1);\n"
  66. "}\n"
  67. ""
  68. "function isResolvable(host) {\n"
  69. " var ip = dnsResolve(host);\n"
  70. " return (ip != null);\n"
  71. "}\n"
  72. ""
  73. "function localHostOrDomainIs(host, hostdom) {\n"
  74. " return (host == hostdom) ||\n"
  75. " (hostdom.lastIndexOf(host + '.', 0) == 0);\n"
  76. "}\n"
  77. ""
  78. "function shExpMatch(url, pattern) {\n"
  79. " pattern = pattern.replace(/\\./g, '\\\\.');\n"
  80. " pattern = pattern.replace(/\\*/g, '.*');\n"
  81. " pattern = pattern.replace(/\\?/g, '.');\n"
  82. " var newRe = new RegExp('^'+pattern+'$');\n"
  83. " return newRe.test(url);\n"
  84. "}\n"
  85. ""
  86. "var wdays = {SUN: 0, MON: 1, TUE: 2, WED: 3, THU: 4, FRI: 5, SAT: 6};\n"
  87. "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"
  88. ""
  89. "function weekdayRange() {\n"
  90. " function getDay(weekday) {\n"
  91. " if (weekday in wdays) {\n"
  92. " return wdays[weekday];\n"
  93. " }\n"
  94. " return -1;\n"
  95. " }\n"
  96. " var date = new Date();\n"
  97. " var argc = arguments.length;\n"
  98. " var wday;\n"
  99. " if (argc < 1)\n"
  100. " return false;\n"
  101. " if (arguments[argc - 1] == 'GMT') {\n"
  102. " argc--;\n"
  103. " wday = date.getUTCDay();\n"
  104. " } else {\n"
  105. " wday = date.getDay();\n"
  106. " }\n"
  107. " var wd1 = getDay(arguments[0]);\n"
  108. " var wd2 = (argc == 2) ? getDay(arguments[1]) : wd1;\n"
  109. " return (wd1 == -1 || wd2 == -1) ? false\n"
  110. " : (wd1 <= wd2) ? (wd1 <= wday && wday <= wd2)\n"
  111. " : (wd2 >= wday || wday >= wd1);\n"
  112. "}\n"
  113. ""
  114. "function dateRange() {\n"
  115. " function getMonth(name) {\n"
  116. " if (name in months) {\n"
  117. " return months[name];\n"
  118. " }\n"
  119. " return -1;\n"
  120. " }\n"
  121. " var date = new Date();\n"
  122. " var argc = arguments.length;\n"
  123. " if (argc < 1) {\n"
  124. " return false;\n"
  125. " }\n"
  126. " var isGMT = (arguments[argc - 1] == 'GMT');\n"
  127. "\n"
  128. " if (isGMT) {\n"
  129. " argc--;\n"
  130. " }\n"
  131. " // function will work even without explict handling of this case\n"
  132. " if (argc == 1) {\n"
  133. " var tmp = parseInt(arguments[0]);\n"
  134. " if (isNaN(tmp)) {\n"
  135. " return ((isGMT ? date.getUTCMonth() : date.getMonth()) ==\n"
  136. " getMonth(arguments[0]));\n"
  137. " } else if (tmp < 32) {\n"
  138. " return ((isGMT ? date.getUTCDate() : date.getDate()) == tmp);\n"
  139. " } else { \n"
  140. " return ((isGMT ? date.getUTCFullYear() : date.getFullYear()) ==\n"
  141. " tmp);\n"
  142. " }\n"
  143. " }\n"
  144. " var year = date.getFullYear();\n"
  145. " var date1, date2;\n"
  146. " date1 = new Date(year, 0, 1, 0, 0, 0);\n"
  147. " date2 = new Date(year, 11, 31, 23, 59, 59);\n"
  148. " var adjustMonth = false;\n"
  149. " for (var i = 0; i < (argc >> 1); i++) {\n"
  150. " var tmp = parseInt(arguments[i]);\n"
  151. " if (isNaN(tmp)) {\n"
  152. " var mon = getMonth(arguments[i]);\n"
  153. " date1.setMonth(mon);\n"
  154. " } else if (tmp < 32) {\n"
  155. " adjustMonth = (argc <= 2);\n"
  156. " date1.setDate(tmp);\n"
  157. " } else {\n"
  158. " date1.setFullYear(tmp);\n"
  159. " }\n"
  160. " }\n"
  161. " for (var i = (argc >> 1); i < argc; i++) {\n"
  162. " var tmp = parseInt(arguments[i]);\n"
  163. " if (isNaN(tmp)) {\n"
  164. " var mon = getMonth(arguments[i]);\n"
  165. " date2.setMonth(mon);\n"
  166. " } else if (tmp < 32) {\n"
  167. " date2.setDate(tmp);\n"
  168. " } else {\n"
  169. " date2.setFullYear(tmp);\n"
  170. " }\n"
  171. " }\n"
  172. " if (adjustMonth) {\n"
  173. " date1.setMonth(date.getMonth());\n"
  174. " date2.setMonth(date.getMonth());\n"
  175. " }\n"
  176. " if (isGMT) {\n"
  177. " var tmp = date;\n"
  178. " tmp.setFullYear(date.getUTCFullYear());\n"
  179. " tmp.setMonth(date.getUTCMonth());\n"
  180. " tmp.setDate(date.getUTCDate());\n"
  181. " tmp.setHours(date.getUTCHours());\n"
  182. " tmp.setMinutes(date.getUTCMinutes());\n"
  183. " tmp.setSeconds(date.getUTCSeconds());\n"
  184. " date = tmp;\n"
  185. " }\n"
  186. " return (date1 <= date2) ? (date1 <= date) && (date <= date2)\n"
  187. " : (date2 >= date) || (date >= date1);\n"
  188. "}\n"
  189. ""
  190. "function timeRange() {\n"
  191. " var argc = arguments.length;\n"
  192. " var date = new Date();\n"
  193. " var isGMT= false;\n"
  194. ""
  195. " if (argc < 1) {\n"
  196. " return false;\n"
  197. " }\n"
  198. " if (arguments[argc - 1] == 'GMT') {\n"
  199. " isGMT = true;\n"
  200. " argc--;\n"
  201. " }\n"
  202. "\n"
  203. " var hour = isGMT ? date.getUTCHours() : date.getHours();\n"
  204. " var date1, date2;\n"
  205. " date1 = new Date();\n"
  206. " date2 = new Date();\n"
  207. "\n"
  208. " if (argc == 1) {\n"
  209. " return (hour == arguments[0]);\n"
  210. " } else if (argc == 2) {\n"
  211. " return ((arguments[0] <= hour) && (hour <= arguments[1]));\n"
  212. " } else {\n"
  213. " switch (argc) {\n"
  214. " case 6:\n"
  215. " date1.setSeconds(arguments[2]);\n"
  216. " date2.setSeconds(arguments[5]);\n"
  217. " case 4:\n"
  218. " var middle = argc >> 1;\n"
  219. " date1.setHours(arguments[0]);\n"
  220. " date1.setMinutes(arguments[1]);\n"
  221. " date2.setHours(arguments[middle]);\n"
  222. " date2.setMinutes(arguments[middle + 1]);\n"
  223. " if (middle == 2) {\n"
  224. " date2.setSeconds(59);\n"
  225. " }\n"
  226. " break;\n"
  227. " default:\n"
  228. " throw 'timeRange: bad number of arguments'\n"
  229. " }\n"
  230. " }\n"
  231. "\n"
  232. " if (isGMT) {\n"
  233. " date.setFullYear(date.getUTCFullYear());\n"
  234. " date.setMonth(date.getUTCMonth());\n"
  235. " date.setDate(date.getUTCDate());\n"
  236. " date.setHours(date.getUTCHours());\n"
  237. " date.setMinutes(date.getUTCMinutes());\n"
  238. " date.setSeconds(date.getUTCSeconds());\n"
  239. " }\n"
  240. " return (date1 <= date2) ? (date1 <= date) && (date <= date2)\n"
  241. " : (date2 >= date) || (date >= date1);\n"
  242. "\n"
  243. "}\n"
  244. "";
  245. // sRunning is defined for the helper functions only while the
  246. // Javascript engine is running and the PAC object cannot be deleted
  247. // or reset.
  248. static uint32_t sRunningIndex = 0xdeadbeef;
  249. static ProxyAutoConfig *GetRunning()
  250. {
  251. MOZ_ASSERT(sRunningIndex != 0xdeadbeef);
  252. return static_cast<ProxyAutoConfig *>(PR_GetThreadPrivate(sRunningIndex));
  253. }
  254. static void SetRunning(ProxyAutoConfig *arg)
  255. {
  256. MOZ_ASSERT(sRunningIndex != 0xdeadbeef);
  257. PR_SetThreadPrivate(sRunningIndex, arg);
  258. }
  259. // The PACResolver is used for dnsResolve()
  260. class PACResolver final : public nsIDNSListener
  261. , public nsITimerCallback
  262. {
  263. public:
  264. NS_DECL_THREADSAFE_ISUPPORTS
  265. PACResolver()
  266. : mStatus(NS_ERROR_FAILURE)
  267. , mMutex("PACResolver::Mutex")
  268. {
  269. }
  270. // nsIDNSListener
  271. NS_IMETHOD OnLookupComplete(nsICancelable *request,
  272. nsIDNSRecord *record,
  273. nsresult status) override
  274. {
  275. nsCOMPtr<nsITimer> timer;
  276. {
  277. MutexAutoLock lock(mMutex);
  278. timer.swap(mTimer);
  279. mRequest = nullptr;
  280. }
  281. if (timer) {
  282. timer->Cancel();
  283. }
  284. mRequest = nullptr;
  285. mStatus = status;
  286. mResponse = record;
  287. return NS_OK;
  288. }
  289. // nsITimerCallback
  290. NS_IMETHOD Notify(nsITimer *timer) override
  291. {
  292. nsCOMPtr<nsICancelable> request;
  293. {
  294. MutexAutoLock lock(mMutex);
  295. request.swap(mRequest);
  296. mTimer = nullptr;
  297. }
  298. if (request) {
  299. request->Cancel(NS_ERROR_NET_TIMEOUT);
  300. }
  301. return NS_OK;
  302. }
  303. nsresult mStatus;
  304. nsCOMPtr<nsICancelable> mRequest;
  305. nsCOMPtr<nsIDNSRecord> mResponse;
  306. nsCOMPtr<nsITimer> mTimer;
  307. Mutex mMutex;
  308. private:
  309. ~PACResolver() {}
  310. };
  311. NS_IMPL_ISUPPORTS(PACResolver, nsIDNSListener, nsITimerCallback)
  312. static
  313. void PACLogToConsole(nsString &aMessage)
  314. {
  315. nsCOMPtr<nsIConsoleService> consoleService =
  316. do_GetService(NS_CONSOLESERVICE_CONTRACTID);
  317. if (!consoleService)
  318. return;
  319. consoleService->LogStringMessage(aMessage.get());
  320. }
  321. // Javascript errors and warnings are logged to the main error console
  322. static void
  323. PACLogErrorOrWarning(const nsAString& aKind, JSErrorReport* aReport)
  324. {
  325. nsString formattedMessage(NS_LITERAL_STRING("PAC Execution "));
  326. formattedMessage += aKind;
  327. formattedMessage += NS_LITERAL_STRING(": ");
  328. if (aReport->message())
  329. formattedMessage.Append(NS_ConvertUTF8toUTF16(aReport->message().c_str()));
  330. formattedMessage += NS_LITERAL_STRING(" [");
  331. formattedMessage.Append(aReport->linebuf(), aReport->linebufLength());
  332. formattedMessage += NS_LITERAL_STRING("]");
  333. PACLogToConsole(formattedMessage);
  334. }
  335. static void
  336. PACWarningReporter(JSContext* aCx, JSErrorReport* aReport)
  337. {
  338. MOZ_ASSERT(aReport);
  339. MOZ_ASSERT(JSREPORT_IS_WARNING(aReport->flags));
  340. PACLogErrorOrWarning(NS_LITERAL_STRING("Warning"), aReport);
  341. }
  342. class MOZ_STACK_CLASS AutoPACErrorReporter
  343. {
  344. JSContext* mCx;
  345. public:
  346. explicit AutoPACErrorReporter(JSContext* aCx)
  347. : mCx(aCx)
  348. {}
  349. ~AutoPACErrorReporter() {
  350. if (!JS_IsExceptionPending(mCx)) {
  351. return;
  352. }
  353. JS::RootedValue exn(mCx);
  354. if (!JS_GetPendingException(mCx, &exn)) {
  355. return;
  356. }
  357. JS_ClearPendingException(mCx);
  358. js::ErrorReport report(mCx);
  359. if (!report.init(mCx, exn, js::ErrorReport::WithSideEffects)) {
  360. JS_ClearPendingException(mCx);
  361. return;
  362. }
  363. PACLogErrorOrWarning(NS_LITERAL_STRING("Error"), report.report());
  364. }
  365. };
  366. // timeout of 0 means the normal necko timeout strategy, otherwise the dns request
  367. // will be canceled after aTimeout milliseconds
  368. static
  369. bool PACResolve(const nsCString &aHostName, NetAddr *aNetAddr,
  370. unsigned int aTimeout)
  371. {
  372. if (!GetRunning()) {
  373. NS_WARNING("PACResolve without a running ProxyAutoConfig object");
  374. return false;
  375. }
  376. return GetRunning()->ResolveAddress(aHostName, aNetAddr, aTimeout);
  377. }
  378. ProxyAutoConfig::ProxyAutoConfig()
  379. : mJSContext(nullptr)
  380. , mJSNeedsSetup(false)
  381. , mShutdown(false)
  382. , mIncludePath(false)
  383. {
  384. MOZ_COUNT_CTOR(ProxyAutoConfig);
  385. }
  386. bool
  387. ProxyAutoConfig::ResolveAddress(const nsCString &aHostName,
  388. NetAddr *aNetAddr,
  389. unsigned int aTimeout)
  390. {
  391. nsCOMPtr<nsIDNSService> dns = do_GetService(NS_DNSSERVICE_CONTRACTID);
  392. if (!dns)
  393. return false;
  394. RefPtr<PACResolver> helper = new PACResolver();
  395. if (NS_FAILED(dns->AsyncResolve(aHostName,
  396. nsIDNSService::RESOLVE_PRIORITY_MEDIUM,
  397. helper,
  398. NS_GetCurrentThread(),
  399. getter_AddRefs(helper->mRequest))))
  400. return false;
  401. if (aTimeout && helper->mRequest) {
  402. if (!mTimer)
  403. mTimer = do_CreateInstance(NS_TIMER_CONTRACTID);
  404. if (mTimer) {
  405. mTimer->InitWithCallback(helper, aTimeout, nsITimer::TYPE_ONE_SHOT);
  406. helper->mTimer = mTimer;
  407. }
  408. }
  409. // Spin the event loop of the pac thread until lookup is complete.
  410. // nsPACman is responsible for keeping a queue and only allowing
  411. // one PAC execution at a time even when it is called re-entrantly.
  412. while (helper->mRequest)
  413. NS_ProcessNextEvent(NS_GetCurrentThread());
  414. if (NS_FAILED(helper->mStatus) ||
  415. NS_FAILED(helper->mResponse->GetNextAddr(0, aNetAddr)))
  416. return false;
  417. return true;
  418. }
  419. static
  420. bool PACResolveToString(const nsCString &aHostName,
  421. nsCString &aDottedDecimal,
  422. unsigned int aTimeout)
  423. {
  424. NetAddr netAddr;
  425. if (!PACResolve(aHostName, &netAddr, aTimeout))
  426. return false;
  427. char dottedDecimal[128];
  428. if (!NetAddrToString(&netAddr, dottedDecimal, sizeof(dottedDecimal)))
  429. return false;
  430. aDottedDecimal.Assign(dottedDecimal);
  431. return true;
  432. }
  433. // dnsResolve(host) javascript implementation
  434. static
  435. bool PACDnsResolve(JSContext *cx, unsigned int argc, JS::Value *vp)
  436. {
  437. JS::CallArgs args = CallArgsFromVp(argc, vp);
  438. if (NS_IsMainThread()) {
  439. NS_WARNING("DNS Resolution From PAC on Main Thread. How did that happen?");
  440. return false;
  441. }
  442. if (!args.requireAtLeast(cx, "dnsResolve", 1))
  443. return false;
  444. JS::Rooted<JSString*> arg1(cx, JS::ToString(cx, args[0]));
  445. if (!arg1)
  446. return false;
  447. nsAutoJSString hostName;
  448. nsAutoCString dottedDecimal;
  449. if (!hostName.init(cx, arg1))
  450. return false;
  451. if (PACResolveToString(NS_ConvertUTF16toUTF8(hostName), dottedDecimal, 0)) {
  452. JSString *dottedDecimalString = JS_NewStringCopyZ(cx, dottedDecimal.get());
  453. if (!dottedDecimalString) {
  454. return false;
  455. }
  456. args.rval().setString(dottedDecimalString);
  457. }
  458. else {
  459. args.rval().setNull();
  460. }
  461. return true;
  462. }
  463. // myIpAddress() javascript implementation
  464. static
  465. bool PACMyIpAddress(JSContext *cx, unsigned int argc, JS::Value *vp)
  466. {
  467. JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
  468. if (NS_IsMainThread()) {
  469. NS_WARNING("DNS Resolution From PAC on Main Thread. How did that happen?");
  470. return false;
  471. }
  472. if (!GetRunning()) {
  473. NS_WARNING("PAC myIPAddress without a running ProxyAutoConfig object");
  474. return false;
  475. }
  476. return GetRunning()->MyIPAddress(args);
  477. }
  478. // proxyAlert(msg) javascript implementation
  479. static
  480. bool PACProxyAlert(JSContext *cx, unsigned int argc, JS::Value *vp)
  481. {
  482. JS::CallArgs args = CallArgsFromVp(argc, vp);
  483. if (!args.requireAtLeast(cx, "alert", 1))
  484. return false;
  485. JS::Rooted<JSString*> arg1(cx, JS::ToString(cx, args[0]));
  486. if (!arg1)
  487. return false;
  488. nsAutoJSString message;
  489. if (!message.init(cx, arg1))
  490. return false;
  491. nsAutoString alertMessage;
  492. alertMessage.SetCapacity(32 + message.Length());
  493. alertMessage += NS_LITERAL_STRING("PAC-alert: ");
  494. alertMessage += message;
  495. PACLogToConsole(alertMessage);
  496. args.rval().setUndefined(); /* return undefined */
  497. return true;
  498. }
  499. static const JSFunctionSpec PACGlobalFunctions[] = {
  500. JS_FS("dnsResolve", PACDnsResolve, 1, 0),
  501. // a global "var pacUseMultihomedDNS = true;" will change behavior
  502. // of myIpAddress to actively use DNS
  503. JS_FS("myIpAddress", PACMyIpAddress, 0, 0),
  504. JS_FS("alert", PACProxyAlert, 1, 0),
  505. JS_FS_END
  506. };
  507. // JSContextWrapper is a c++ object that manages the context for the JS engine
  508. // used on the PAC thread. It is initialized and destroyed on the PAC thread.
  509. class JSContextWrapper
  510. {
  511. public:
  512. static JSContextWrapper *Create()
  513. {
  514. JSContext* cx = JS_NewContext(sContextHeapSize);
  515. if (NS_WARN_IF(!cx))
  516. return nullptr;
  517. JSContextWrapper *entry = new JSContextWrapper(cx);
  518. if (NS_FAILED(entry->Init())) {
  519. delete entry;
  520. return nullptr;
  521. }
  522. return entry;
  523. }
  524. JSContext *Context() const
  525. {
  526. return mContext;
  527. }
  528. JSObject *Global() const
  529. {
  530. return mGlobal;
  531. }
  532. ~JSContextWrapper()
  533. {
  534. mGlobal = nullptr;
  535. MOZ_COUNT_DTOR(JSContextWrapper);
  536. if (mContext) {
  537. JS_DestroyContext(mContext);
  538. }
  539. }
  540. void SetOK()
  541. {
  542. mOK = true;
  543. }
  544. bool IsOK()
  545. {
  546. return mOK;
  547. }
  548. private:
  549. static const unsigned sContextHeapSize = 4 << 20; // 4 MB
  550. JSContext *mContext;
  551. JS::PersistentRooted<JSObject*> mGlobal;
  552. bool mOK;
  553. static const JSClass sGlobalClass;
  554. explicit JSContextWrapper(JSContext* cx)
  555. : mContext(cx), mGlobal(cx, nullptr), mOK(false)
  556. {
  557. MOZ_COUNT_CTOR(JSContextWrapper);
  558. }
  559. nsresult Init()
  560. {
  561. /*
  562. * Not setting this will cause JS_CHECK_RECURSION to report false
  563. * positives
  564. */
  565. JS_SetNativeStackQuota(mContext, 128 * sizeof(size_t) * 1024);
  566. JS::SetWarningReporter(mContext, PACWarningReporter);
  567. if (!JS::InitSelfHostedCode(mContext)) {
  568. return NS_ERROR_OUT_OF_MEMORY;
  569. }
  570. JSAutoRequest ar(mContext);
  571. JS::CompartmentOptions options;
  572. options.creationOptions().setZone(JS::SystemZone);
  573. options.behaviors().setVersion(JSVERSION_LATEST);
  574. mGlobal = JS_NewGlobalObject(mContext, &sGlobalClass, nullptr,
  575. JS::DontFireOnNewGlobalHook, options);
  576. if (!mGlobal) {
  577. JS_ClearPendingException(mContext);
  578. return NS_ERROR_OUT_OF_MEMORY;
  579. }
  580. JS::Rooted<JSObject*> global(mContext, mGlobal);
  581. JSAutoCompartment ac(mContext, global);
  582. AutoPACErrorReporter aper(mContext);
  583. if (!JS_InitStandardClasses(mContext, global)) {
  584. return NS_ERROR_FAILURE;
  585. }
  586. if (!JS_DefineFunctions(mContext, global, PACGlobalFunctions)) {
  587. return NS_ERROR_FAILURE;
  588. }
  589. JS_FireOnNewGlobalObject(mContext, global);
  590. return NS_OK;
  591. }
  592. };
  593. static const JSClassOps sJSContextWrapperGlobalClassOps = {
  594. nullptr, nullptr, nullptr, nullptr,
  595. nullptr, nullptr, nullptr, nullptr,
  596. nullptr, nullptr, nullptr,
  597. JS_GlobalObjectTraceHook
  598. };
  599. const JSClass JSContextWrapper::sGlobalClass = {
  600. "PACResolutionThreadGlobal",
  601. JSCLASS_GLOBAL_FLAGS,
  602. &sJSContextWrapperGlobalClassOps
  603. };
  604. void
  605. ProxyAutoConfig::SetThreadLocalIndex(uint32_t index)
  606. {
  607. sRunningIndex = index;
  608. }
  609. nsresult
  610. ProxyAutoConfig::Init(const nsCString &aPACURI,
  611. const nsCString &aPACScript,
  612. bool aIncludePath)
  613. {
  614. mPACURI = aPACURI;
  615. mPACScript = sPacUtils;
  616. mPACScript.Append(aPACScript);
  617. mIncludePath = aIncludePath;
  618. if (!GetRunning())
  619. return SetupJS();
  620. mJSNeedsSetup = true;
  621. return NS_OK;
  622. }
  623. nsresult
  624. ProxyAutoConfig::SetupJS()
  625. {
  626. mJSNeedsSetup = false;
  627. MOZ_ASSERT(!GetRunning(), "JIT is running");
  628. delete mJSContext;
  629. mJSContext = nullptr;
  630. if (mPACScript.IsEmpty())
  631. return NS_ERROR_FAILURE;
  632. NS_GetCurrentThread()->SetCanInvokeJS(true);
  633. mJSContext = JSContextWrapper::Create();
  634. if (!mJSContext)
  635. return NS_ERROR_FAILURE;
  636. JSContext* cx = mJSContext->Context();
  637. JSAutoRequest ar(cx);
  638. JSAutoCompartment ac(cx, mJSContext->Global());
  639. AutoPACErrorReporter aper(cx);
  640. // check if this is a data: uri so that we don't spam the js console with
  641. // huge meaningless strings. this is not on the main thread, so it can't
  642. // use nsIURI scheme methods
  643. bool isDataURI = nsDependentCSubstring(mPACURI, 0, 5).LowerCaseEqualsASCII("data:", 5);
  644. SetRunning(this);
  645. JS::Rooted<JSObject*> global(cx, mJSContext->Global());
  646. JS::CompileOptions options(cx);
  647. options.setFileAndLine(mPACURI.get(), 1);
  648. JS::Rooted<JSScript*> script(cx);
  649. if (!JS_CompileScript(cx, mPACScript.get(), mPACScript.Length(), options,
  650. &script) ||
  651. !JS_ExecuteScript(cx, script))
  652. {
  653. nsString alertMessage(NS_LITERAL_STRING("PAC file failed to install from "));
  654. if (isDataURI) {
  655. alertMessage += NS_LITERAL_STRING("data: URI");
  656. }
  657. else {
  658. alertMessage += NS_ConvertUTF8toUTF16(mPACURI);
  659. }
  660. PACLogToConsole(alertMessage);
  661. SetRunning(nullptr);
  662. return NS_ERROR_FAILURE;
  663. }
  664. SetRunning(nullptr);
  665. mJSContext->SetOK();
  666. nsString alertMessage(NS_LITERAL_STRING("PAC file installed from "));
  667. if (isDataURI) {
  668. alertMessage += NS_LITERAL_STRING("data: URI");
  669. }
  670. else {
  671. alertMessage += NS_ConvertUTF8toUTF16(mPACURI);
  672. }
  673. PACLogToConsole(alertMessage);
  674. // we don't need these now
  675. mPACScript.Truncate();
  676. mPACURI.Truncate();
  677. return NS_OK;
  678. }
  679. nsresult
  680. ProxyAutoConfig::GetProxyForURI(const nsCString &aTestURI,
  681. const nsCString &aTestHost,
  682. nsACString &result)
  683. {
  684. if (mJSNeedsSetup)
  685. SetupJS();
  686. if (!mJSContext || !mJSContext->IsOK())
  687. return NS_ERROR_NOT_AVAILABLE;
  688. JSContext *cx = mJSContext->Context();
  689. JSAutoRequest ar(cx);
  690. JSAutoCompartment ac(cx, mJSContext->Global());
  691. AutoPACErrorReporter aper(cx);
  692. // the sRunning flag keeps a new PAC file from being installed
  693. // while the event loop is spinning on a DNS function. Don't early return.
  694. SetRunning(this);
  695. mRunningHost = aTestHost;
  696. nsresult rv = NS_ERROR_FAILURE;
  697. nsCString clensedURI = aTestURI;
  698. if (!mIncludePath) {
  699. nsCOMPtr<nsIURLParser> urlParser =
  700. do_GetService(NS_STDURLPARSER_CONTRACTID);
  701. int32_t pathLen = 0;
  702. if (urlParser) {
  703. uint32_t schemePos;
  704. int32_t schemeLen;
  705. uint32_t authorityPos;
  706. int32_t authorityLen;
  707. uint32_t pathPos;
  708. rv = urlParser->ParseURL(aTestURI.get(), aTestURI.Length(),
  709. &schemePos, &schemeLen,
  710. &authorityPos, &authorityLen,
  711. &pathPos, &pathLen);
  712. }
  713. if (NS_SUCCEEDED(rv)) {
  714. if (pathLen) {
  715. // cut off the path but leave the initial slash
  716. pathLen--;
  717. }
  718. aTestURI.Left(clensedURI, aTestURI.Length() - pathLen);
  719. }
  720. }
  721. JS::RootedString uriString(cx, JS_NewStringCopyZ(cx, clensedURI.get()));
  722. JS::RootedString hostString(cx, JS_NewStringCopyZ(cx, aTestHost.get()));
  723. if (uriString && hostString) {
  724. JS::AutoValueArray<2> args(cx);
  725. args[0].setString(uriString);
  726. args[1].setString(hostString);
  727. JS::Rooted<JS::Value> rval(cx);
  728. JS::Rooted<JSObject*> global(cx, mJSContext->Global());
  729. bool ok = JS_CallFunctionName(cx, global, "FindProxyForURL", args, &rval);
  730. if (ok && rval.isString()) {
  731. nsAutoJSString pacString;
  732. if (pacString.init(cx, rval.toString())) {
  733. CopyUTF16toUTF8(pacString, result);
  734. rv = NS_OK;
  735. }
  736. }
  737. }
  738. mRunningHost.Truncate();
  739. SetRunning(nullptr);
  740. return rv;
  741. }
  742. void
  743. ProxyAutoConfig::GC()
  744. {
  745. if (!mJSContext || !mJSContext->IsOK())
  746. return;
  747. JSAutoCompartment ac(mJSContext->Context(), mJSContext->Global());
  748. JS_MaybeGC(mJSContext->Context());
  749. }
  750. ProxyAutoConfig::~ProxyAutoConfig()
  751. {
  752. MOZ_COUNT_DTOR(ProxyAutoConfig);
  753. NS_ASSERTION(!mJSContext,
  754. "~ProxyAutoConfig leaking JS context that "
  755. "should have been deleted on pac thread");
  756. }
  757. void
  758. ProxyAutoConfig::Shutdown()
  759. {
  760. MOZ_ASSERT(!NS_IsMainThread(), "wrong thread for shutdown");
  761. if (GetRunning() || mShutdown)
  762. return;
  763. mShutdown = true;
  764. delete mJSContext;
  765. mJSContext = nullptr;
  766. }
  767. bool
  768. ProxyAutoConfig::SrcAddress(const NetAddr *remoteAddress, nsCString &localAddress)
  769. {
  770. PRFileDesc *fd;
  771. fd = PR_OpenUDPSocket(remoteAddress->raw.family);
  772. if (!fd)
  773. return false;
  774. PRNetAddr prRemoteAddress;
  775. NetAddrToPRNetAddr(remoteAddress, &prRemoteAddress);
  776. if (PR_Connect(fd, &prRemoteAddress, 0) != PR_SUCCESS) {
  777. PR_Close(fd);
  778. return false;
  779. }
  780. PRNetAddr localName;
  781. if (PR_GetSockName(fd, &localName) != PR_SUCCESS) {
  782. PR_Close(fd);
  783. return false;
  784. }
  785. PR_Close(fd);
  786. char dottedDecimal[128];
  787. if (PR_NetAddrToString(&localName, dottedDecimal, sizeof(dottedDecimal)) != PR_SUCCESS)
  788. return false;
  789. localAddress.Assign(dottedDecimal);
  790. return true;
  791. }
  792. // hostName is run through a dns lookup and then a udp socket is connected
  793. // to the result. If that all works, the local IP address of the socket is
  794. // returned to the javascript caller and |*aResult| is set to true. Otherwise
  795. // |*aResult| is set to false.
  796. bool
  797. ProxyAutoConfig::MyIPAddressTryHost(const nsCString &hostName,
  798. unsigned int timeout,
  799. const JS::CallArgs &aArgs,
  800. bool* aResult)
  801. {
  802. *aResult = false;
  803. NetAddr remoteAddress;
  804. nsAutoCString localDottedDecimal;
  805. JSContext *cx = mJSContext->Context();
  806. if (PACResolve(hostName, &remoteAddress, timeout) &&
  807. SrcAddress(&remoteAddress, localDottedDecimal)) {
  808. JSString *dottedDecimalString =
  809. JS_NewStringCopyZ(cx, localDottedDecimal.get());
  810. if (!dottedDecimalString) {
  811. return false;
  812. }
  813. *aResult = true;
  814. aArgs.rval().setString(dottedDecimalString);
  815. }
  816. return true;
  817. }
  818. bool
  819. ProxyAutoConfig::MyIPAddress(const JS::CallArgs &aArgs)
  820. {
  821. nsAutoCString remoteDottedDecimal;
  822. nsAutoCString localDottedDecimal;
  823. JSContext *cx = mJSContext->Context();
  824. JS::RootedValue v(cx);
  825. JS::Rooted<JSObject*> global(cx, mJSContext->Global());
  826. bool useMultihomedDNS =
  827. JS_GetProperty(cx, global, "pacUseMultihomedDNS", &v) &&
  828. !v.isUndefined() && ToBoolean(v);
  829. // first, lookup the local address of a socket connected
  830. // to the host of uri being resolved by the pac file. This is
  831. // v6 safe.. but is the last step like that
  832. bool rvalAssigned = false;
  833. if (useMultihomedDNS) {
  834. if (!MyIPAddressTryHost(mRunningHost, kTimeout, aArgs, &rvalAssigned) ||
  835. rvalAssigned) {
  836. return rvalAssigned;
  837. }
  838. } else {
  839. // we can still do the fancy multi homing thing if the host is a literal
  840. PRNetAddr tempAddr;
  841. memset(&tempAddr, 0, sizeof(PRNetAddr));
  842. if ((PR_StringToNetAddr(mRunningHost.get(), &tempAddr) == PR_SUCCESS) &&
  843. (!MyIPAddressTryHost(mRunningHost, kTimeout, aArgs, &rvalAssigned) ||
  844. rvalAssigned)) {
  845. return rvalAssigned;
  846. }
  847. }
  848. // next, look for a route to a public internet address that doesn't need DNS.
  849. // This is the google anycast dns address, but it doesn't matter if it
  850. // remains operable (as we don't contact it) as long as the address stays
  851. // in commonly routed IP address space.
  852. remoteDottedDecimal.AssignLiteral("8.8.8.8");
  853. if (!MyIPAddressTryHost(remoteDottedDecimal, 0, aArgs, &rvalAssigned) ||
  854. rvalAssigned) {
  855. return rvalAssigned;
  856. }
  857. // finally, use the old algorithm based on the local hostname
  858. nsAutoCString hostName;
  859. nsCOMPtr<nsIDNSService> dns = do_GetService(NS_DNSSERVICE_CONTRACTID);
  860. // without multihomedDNS use such a short timeout that we are basically
  861. // just looking at the cache for raw dotted decimals
  862. uint32_t timeout = useMultihomedDNS ? kTimeout : 1;
  863. if (dns && NS_SUCCEEDED(dns->GetMyHostName(hostName)) &&
  864. PACResolveToString(hostName, localDottedDecimal, timeout)) {
  865. JSString *dottedDecimalString =
  866. JS_NewStringCopyZ(cx, localDottedDecimal.get());
  867. if (!dottedDecimalString) {
  868. return false;
  869. }
  870. aArgs.rval().setString(dottedDecimalString);
  871. return true;
  872. }
  873. // next try a couple RFC 1918 variants.. maybe there is a
  874. // local route
  875. remoteDottedDecimal.AssignLiteral("192.168.0.1");
  876. if (!MyIPAddressTryHost(remoteDottedDecimal, 0, aArgs, &rvalAssigned) ||
  877. rvalAssigned) {
  878. return rvalAssigned;
  879. }
  880. // more RFC 1918
  881. remoteDottedDecimal.AssignLiteral("10.0.0.1");
  882. if (!MyIPAddressTryHost(remoteDottedDecimal, 0, aArgs, &rvalAssigned) ||
  883. rvalAssigned) {
  884. return rvalAssigned;
  885. }
  886. // who knows? let's fallback to localhost
  887. localDottedDecimal.AssignLiteral("127.0.0.1");
  888. JSString *dottedDecimalString =
  889. JS_NewStringCopyZ(cx, localDottedDecimal.get());
  890. if (!dottedDecimalString) {
  891. return false;
  892. }
  893. aArgs.rval().setString(dottedDecimalString);
  894. return true;
  895. }
  896. } // namespace net
  897. } // namespace mozilla