Source code

Revision control

Other Tools

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