1 : /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2 : * vim: set ts=4 sw=4 et tw=80:
3 : *
4 : * ***** BEGIN LICENSE BLOCK *****
5 : * Version: MPL 1.1/GPL 2.0/LGPL 2.1
6 : *
7 : * The contents of this file are subject to the Mozilla Public License Version
8 : * 1.1 (the "License"); you may not use this file except in compliance with
9 : * the License. You may obtain a copy of the License at
10 : * http://www.mozilla.org/MPL/
11 : *
12 : * Software distributed under the License is distributed on an "AS IS" basis,
13 : * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
14 : * for the specific language governing rights and limitations under the
15 : * License.
16 : *
17 : * The Original Code is Mozilla Communicator client code, released
18 : * March 31, 1998.
19 : *
20 : * The Initial Developer of the Original Code is
21 : * Netscape Communications Corporation.
22 : * Portions created by the Initial Developer are Copyright (C) 1998
23 : * the Initial Developer. All Rights Reserved.
24 : *
25 : * Contributor(s):
26 : * Robert Ginda <rginda@netscape.com>
27 : * Kris Maglione <maglione.k@gmail.com>
28 : *
29 : * Alternatively, the contents of this file may be used under the terms of
30 : * either of the GNU General Public License Version 2 or later (the "GPL"),
31 : * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
32 : * in which case the provisions of the GPL or the LGPL are applicable instead
33 : * of those above. If you wish to allow use of your version of this file only
34 : * under the terms of either the GPL or the LGPL, and not to allow others to
35 : * use your version of this file under the terms of the MPL, indicate your
36 : * decision by deleting the provisions above and replace them with the notice
37 : * and other provisions required by the GPL or the LGPL. If you do not delete
38 : * the provisions above, a recipient may use your version of this file under
39 : * the terms of any one of the MPL, the GPL or the LGPL.
40 : *
41 : * ***** END LICENSE BLOCK ***** */
42 :
43 : #include "mozJSSubScriptLoader.h"
44 : #include "mozJSLoaderUtils.h"
45 :
46 : #include "nsIServiceManager.h"
47 : #include "nsIXPConnect.h"
48 :
49 : #include "nsIURI.h"
50 : #include "nsIIOService.h"
51 : #include "nsIChannel.h"
52 : #include "nsIInputStream.h"
53 : #include "nsNetCID.h"
54 : #include "nsDependentString.h"
55 : #include "nsAutoPtr.h"
56 : #include "nsNetUtil.h"
57 : #include "nsIProtocolHandler.h"
58 : #include "nsIFileURL.h"
59 : #include "nsScriptLoader.h"
60 :
61 : #include "jsapi.h"
62 : #include "jsdbgapi.h"
63 : #include "jsfriendapi.h"
64 : #include "nsJSPrincipals.h"
65 :
66 : #include "mozilla/FunctionTimer.h"
67 : #include "mozilla/scache/StartupCache.h"
68 : #include "mozilla/scache/StartupCacheUtils.h"
69 :
70 : using namespace mozilla::scache;
71 :
72 : /* load() error msgs, XXX localize? */
73 : #define LOAD_ERROR_NOSERVICE "Error creating IO Service."
74 : #define LOAD_ERROR_NOURI "Error creating URI (invalid URL scheme?)"
75 : #define LOAD_ERROR_NOSCHEME "Failed to get URI scheme. This is bad."
76 : #define LOAD_ERROR_URI_NOT_LOCAL "Trying to load a non-local URI."
77 : #define LOAD_ERROR_NOSTREAM "Error opening input stream (invalid filename?)"
78 : #define LOAD_ERROR_NOCONTENT "ContentLength not available (not a local URL?)"
79 : #define LOAD_ERROR_BADCHARSET "Error converting to specified charset"
80 : #define LOAD_ERROR_BADREAD "File Read Error."
81 : #define LOAD_ERROR_READUNDERFLOW "File Read Error (underflow.)"
82 : #define LOAD_ERROR_NOPRINCIPALS "Failed to get principals."
83 : #define LOAD_ERROR_NOSPEC "Failed to get URI spec. This is bad."
84 :
85 : // We just use the same reporter as the component loader
86 : extern void
87 : mozJSLoaderErrorReporter(JSContext *cx, const char *message, JSErrorReport *rep);
88 :
89 755 : mozJSSubScriptLoader::mozJSSubScriptLoader() : mSystemPrincipal(nsnull)
90 : {
91 755 : }
92 :
93 1510 : mozJSSubScriptLoader::~mozJSSubScriptLoader()
94 : {
95 : /* empty */
96 3020 : }
97 :
98 15898 : NS_IMPL_THREADSAFE_ISUPPORTS1(mozJSSubScriptLoader, mozIJSSubScriptLoader)
99 :
100 : static nsresult
101 83 : ReportError(JSContext *cx, const char *msg)
102 : {
103 83 : JS_SetPendingException(cx, STRING_TO_JSVAL(JS_NewStringCopyZ(cx, msg)));
104 83 : return NS_OK;
105 : }
106 :
107 : nsresult
108 608 : mozJSSubScriptLoader::ReadScript(nsIURI *uri, JSContext *cx, JSObject *target_obj,
109 : const nsAString& charset, const char *uriStr,
110 : nsIIOService *serv, nsIPrincipal *principal,
111 : JSScript **scriptp)
112 : {
113 1216 : nsCOMPtr<nsIChannel> chan;
114 1216 : nsCOMPtr<nsIInputStream> instream;
115 : JSErrorReporter er;
116 :
117 : nsresult rv;
118 : // Instead of calling NS_OpenURI, we create the channel ourselves and call
119 : // SetContentType, to avoid expensive MIME type lookups (bug 632490).
120 608 : rv = NS_NewChannel(getter_AddRefs(chan), uri, serv,
121 608 : nsnull, nsnull, nsIRequest::LOAD_NORMAL);
122 608 : if (NS_SUCCEEDED(rv)) {
123 604 : chan->SetContentType(NS_LITERAL_CSTRING("application/javascript"));
124 604 : rv = chan->Open(getter_AddRefs(instream));
125 : }
126 :
127 608 : if (NS_FAILED(rv)) {
128 83 : return ReportError(cx, LOAD_ERROR_NOSTREAM);
129 : }
130 :
131 525 : PRInt32 len = -1;
132 :
133 525 : rv = chan->GetContentLength(&len);
134 525 : if (NS_FAILED(rv) || len == -1) {
135 0 : return ReportError(cx, LOAD_ERROR_NOCONTENT);
136 : }
137 :
138 1050 : nsCString buf;
139 525 : rv = NS_ReadInputStreamToString(instream, buf, len);
140 525 : if (NS_FAILED(rv))
141 0 : return rv;
142 :
143 : /* set our own error reporter so we can report any bad things as catchable
144 : * exceptions, including the source/line number */
145 525 : er = JS_SetErrorReporter(cx, mozJSLoaderErrorReporter);
146 :
147 525 : if (!charset.IsVoid()) {
148 0 : nsString script;
149 0 : rv = nsScriptLoader::ConvertToUTF16(nsnull, reinterpret_cast<const PRUint8*>(buf.get()), len,
150 0 : charset, nsnull, script);
151 :
152 0 : if (NS_FAILED(rv)) {
153 0 : return ReportError(cx, LOAD_ERROR_BADCHARSET);
154 : }
155 :
156 : *scriptp =
157 0 : JS_CompileUCScriptForPrincipals(cx, target_obj, nsJSPrincipals::get(principal),
158 0 : reinterpret_cast<const jschar*>(script.get()),
159 0 : script.Length(), uriStr, 1);
160 : } else {
161 525 : *scriptp = JS_CompileScriptForPrincipals(cx, target_obj, nsJSPrincipals::get(principal),
162 1050 : buf.get(), len, uriStr, 1);
163 : }
164 :
165 : /* repent for our evil deeds */
166 525 : JS_SetErrorReporter(cx, er);
167 :
168 525 : return NS_OK;
169 : }
170 :
171 : NS_IMETHODIMP
172 709 : mozJSSubScriptLoader::LoadSubScript(const nsAString& url,
173 : const JS::Value& target,
174 : const nsAString& charset,
175 : JSContext* cx,
176 : JS::Value* retval)
177 : {
178 : /*
179 : * Loads a local url and evals it into the current cx
180 : * Synchronous (an async version would be cool too.)
181 : * url: The url to load. Must be local so that it can be loaded
182 : * synchronously.
183 : * target_obj: Optional object to eval the script onto (defaults to context
184 : * global)
185 : * returns: Whatever jsval the script pointed to by the url returns.
186 : * Should ONLY (O N L Y !) be called from JavaScript code.
187 : */
188 :
189 709 : nsresult rv = NS_OK;
190 :
191 : #ifdef NS_FUNCTION_TIMER
192 : NS_TIME_FUNCTION_FMT("%s (line %d) (url: %s)", MOZ_FUNCTION_NAME,
193 : __LINE__, NS_LossyConvertUTF16toASCII(url).get());
194 : #endif
195 :
196 : /* set the system principal if it's not here already */
197 709 : if (!mSystemPrincipal) {
198 : nsCOMPtr<nsIScriptSecurityManager> secman =
199 1024 : do_GetService(NS_SCRIPTSECURITYMANAGER_CONTRACTID);
200 512 : if (!secman)
201 0 : return NS_OK;
202 :
203 512 : rv = secman->GetSystemPrincipal(getter_AddRefs(mSystemPrincipal));
204 512 : if (NS_FAILED(rv) || !mSystemPrincipal)
205 0 : return rv;
206 : }
207 :
208 1418 : JSAutoRequest ar(cx);
209 :
210 : JSObject* targetObj;
211 709 : if (!JS_ValueToObject(cx, target, &targetObj))
212 0 : return NS_ERROR_ILLEGAL_VALUE;
213 :
214 :
215 709 : if (!targetObj) {
216 : // If the user didn't provide an object to eval onto, find the global
217 : // object by walking the parent chain of the calling object.
218 588 : nsCOMPtr<nsIXPConnect> xpc = do_GetService(nsIXPConnect::GetCID());
219 294 : NS_ENSURE_TRUE(xpc, NS_ERROR_FAILURE);
220 :
221 294 : nsAXPCNativeCallContext *cc = nsnull;
222 294 : rv = xpc->GetCurrentNativeCallContext(&cc);
223 294 : NS_ENSURE_SUCCESS(rv, NS_ERROR_FAILURE);
224 :
225 588 : nsCOMPtr<nsIXPConnectWrappedNative> wn;
226 294 : rv = cc->GetCalleeWrapper(getter_AddRefs(wn));
227 294 : NS_ENSURE_SUCCESS(rv, NS_ERROR_FAILURE);
228 :
229 294 : rv = wn->GetJSObject(&targetObj);
230 294 : NS_ENSURE_SUCCESS(rv, NS_ERROR_FAILURE);
231 :
232 588 : targetObj = JS_GetGlobalForObject(cx, targetObj);
233 : }
234 :
235 : // Remember an object out of the calling compartment so that we
236 : // can properly wrap the result later.
237 1418 : nsCOMPtr<nsIPrincipal> principal = mSystemPrincipal;
238 709 : JSObject *result_obj = targetObj;
239 709 : targetObj = JS_FindCompilationScope(cx, targetObj);
240 709 : if (!targetObj)
241 0 : return NS_ERROR_FAILURE;
242 :
243 709 : if (targetObj != result_obj) {
244 : nsCOMPtr<nsIScriptSecurityManager> secman =
245 0 : do_GetService(NS_SCRIPTSECURITYMANAGER_CONTRACTID);
246 0 : if (!secman)
247 0 : return NS_ERROR_FAILURE;
248 :
249 0 : rv = secman->GetObjectPrincipal(cx, targetObj, getter_AddRefs(principal));
250 0 : NS_ENSURE_SUCCESS(rv, rv);
251 : }
252 :
253 1418 : JSAutoEnterCompartment ac;
254 709 : if (!ac.enter(cx, targetObj))
255 0 : return NS_ERROR_UNEXPECTED;
256 :
257 : /* load up the url. From here on, failures are reflected as ``custom''
258 : * js exceptions */
259 1418 : nsCOMPtr<nsIURI> uri;
260 1418 : nsCAutoString uriStr;
261 1418 : nsCAutoString scheme;
262 :
263 709 : JSStackFrame* frame = nsnull;
264 709 : JSScript* script = nsnull;
265 :
266 : // Figure out who's calling us
267 1418 : do
268 : {
269 709 : frame = JS_FrameIterator(cx, &frame);
270 :
271 709 : if (frame)
272 709 : script = JS_GetFrameScript(cx, frame);
273 709 : } while (frame && !script);
274 :
275 709 : if (!script) {
276 : // No script means we don't know who's calling, bail.
277 :
278 0 : return NS_ERROR_FAILURE;
279 : }
280 :
281 : // Suppress caching if we're compiling as content.
282 709 : StartupCache* cache = (principal == mSystemPrincipal)
283 : ? StartupCache::GetSingleton()
284 709 : : nsnull;
285 1418 : nsCOMPtr<nsIIOService> serv = do_GetService(NS_IOSERVICE_CONTRACTID);
286 709 : if (!serv) {
287 0 : return ReportError(cx, LOAD_ERROR_NOSERVICE);
288 : }
289 :
290 : // Make sure to explicitly create the URI, since we'll need the
291 : // canonicalized spec.
292 709 : rv = NS_NewURI(getter_AddRefs(uri), NS_LossyConvertUTF16toASCII(url).get(), nsnull, serv);
293 709 : if (NS_FAILED(rv)) {
294 0 : return ReportError(cx, LOAD_ERROR_NOURI);
295 : }
296 :
297 709 : rv = uri->GetSpec(uriStr);
298 709 : if (NS_FAILED(rv)) {
299 0 : return ReportError(cx, LOAD_ERROR_NOSPEC);
300 : }
301 :
302 709 : rv = uri->GetScheme(scheme);
303 709 : if (NS_FAILED(rv)) {
304 0 : return ReportError(cx, LOAD_ERROR_NOSCHEME);
305 : }
306 :
307 709 : if (!scheme.EqualsLiteral("chrome")) {
308 : // This might be a URI to a local file, though!
309 1004 : nsCOMPtr<nsIURI> innerURI = NS_GetInnermostURI(uri);
310 1004 : nsCOMPtr<nsIFileURL> fileURL = do_QueryInterface(innerURI);
311 502 : if (!fileURL) {
312 0 : return ReportError(cx, LOAD_ERROR_URI_NOT_LOCAL);
313 : }
314 :
315 : // For file URIs prepend the filename with the filename of the
316 : // calling script, and " -> ". See bug 418356.
317 1506 : nsCAutoString tmp(JS_GetScriptFilename(cx, script));
318 502 : tmp.AppendLiteral(" -> ");
319 502 : tmp.Append(uriStr);
320 :
321 502 : uriStr = tmp;
322 : }
323 :
324 709 : bool writeScript = false;
325 709 : JSVersion version = JS_GetVersion(cx);
326 1418 : nsCAutoString cachePath;
327 709 : cachePath.AppendPrintf("jssubloader/%d", version);
328 709 : PathifyURI(uri, cachePath);
329 :
330 709 : script = nsnull;
331 709 : if (cache)
332 315 : rv = ReadCachedScript(cache, cachePath, cx, &script);
333 709 : if (!script) {
334 : rv = ReadScript(uri, cx, targetObj, charset,
335 : static_cast<const char*>(uriStr.get()), serv,
336 608 : principal, &script);
337 608 : writeScript = true;
338 : }
339 :
340 709 : if (NS_FAILED(rv) || !script)
341 84 : return rv;
342 :
343 625 : bool ok = JS_ExecuteScriptVersion(cx, targetObj, script, retval, version);
344 :
345 625 : if (ok) {
346 1250 : JSAutoEnterCompartment rac;
347 625 : if (!rac.enter(cx, result_obj) || !JS_WrapValue(cx, retval))
348 0 : return NS_ERROR_UNEXPECTED;
349 : }
350 :
351 625 : if (cache && ok && writeScript) {
352 131 : WriteCachedScript(cache, cachePath, cx, script);
353 : }
354 :
355 625 : return NS_OK;
356 : }
|