Bug 1845017 - Disable the TestPHCExhaustion test r=glandium
[gecko.git] / uriloader / base / nsURILoader.cpp
blobdf286e5a73919837e9d0160b785111a849cbebce
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode:nil; c-basic-offset: 2 -*- */
2 /* vim:set ts=2 sts=2 sw=2 et cin: */
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/. */
7 #include "nsURILoader.h"
8 #include "nsComponentManagerUtils.h"
9 #include "nsIURIContentListener.h"
10 #include "nsIContentHandler.h"
11 #include "nsILoadGroup.h"
12 #include "nsIDocumentLoader.h"
13 #include "nsIStreamListener.h"
14 #include "nsIURL.h"
15 #include "nsIChannel.h"
16 #include "nsIInterfaceRequestor.h"
17 #include "nsIInterfaceRequestorUtils.h"
18 #include "nsIInputStream.h"
19 #include "nsIStreamConverterService.h"
20 #include "nsIWeakReferenceUtils.h"
21 #include "nsIHttpChannel.h"
22 #include "netCore.h"
23 #include "nsCRT.h"
24 #include "nsIDocShell.h"
25 #include "nsIThreadRetargetableStreamListener.h"
26 #include "nsIChildChannel.h"
27 #include "nsExternalHelperAppService.h"
29 #include "nsString.h"
30 #include "nsThreadUtils.h"
31 #include "nsReadableUtils.h"
32 #include "nsError.h"
34 #include "nsICategoryManager.h"
35 #include "nsCExternalHandlerService.h"
37 #include "nsNetCID.h"
39 #include "nsMimeTypes.h"
41 #include "nsDocLoader.h"
42 #include "mozilla/Attributes.h"
43 #include "mozilla/IntegerPrintfMacros.h"
44 #include "mozilla/Preferences.h"
45 #include "mozilla/Unused.h"
46 #include "mozilla/StaticPrefs_browser.h"
47 #include "mozilla/StaticPrefs_dom.h"
48 #include "mozilla/StaticPrefs_general.h"
49 #include "nsContentUtils.h"
51 mozilla::LazyLogModule nsURILoader::mLog("URILoader");
53 #define LOG(args) MOZ_LOG(nsURILoader::mLog, mozilla::LogLevel::Debug, args)
54 #define LOG_ERROR(args) \
55 MOZ_LOG(nsURILoader::mLog, mozilla::LogLevel::Error, args)
56 #define LOG_ENABLED() MOZ_LOG_TEST(nsURILoader::mLog, mozilla::LogLevel::Debug)
58 NS_IMPL_ADDREF(nsDocumentOpenInfo)
59 NS_IMPL_RELEASE(nsDocumentOpenInfo)
61 NS_INTERFACE_MAP_BEGIN(nsDocumentOpenInfo)
62 NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIRequestObserver)
63 NS_INTERFACE_MAP_ENTRY(nsIRequestObserver)
64 NS_INTERFACE_MAP_ENTRY(nsIStreamListener)
65 NS_INTERFACE_MAP_ENTRY(nsIThreadRetargetableStreamListener)
66 NS_INTERFACE_MAP_END
68 nsDocumentOpenInfo::nsDocumentOpenInfo(nsIInterfaceRequestor* aWindowContext,
69 uint32_t aFlags, nsURILoader* aURILoader)
70 : m_originalContext(aWindowContext),
71 mFlags(aFlags),
72 mURILoader(aURILoader),
73 mDataConversionDepthLimit(
74 mozilla::StaticPrefs::
75 general_document_open_conversion_depth_limit()) {}
77 nsDocumentOpenInfo::nsDocumentOpenInfo(uint32_t aFlags,
78 bool aAllowListenerConversions)
79 : m_originalContext(nullptr),
80 mFlags(aFlags),
81 mURILoader(nullptr),
82 mDataConversionDepthLimit(
83 mozilla::StaticPrefs::general_document_open_conversion_depth_limit()),
84 mAllowListenerConversions(aAllowListenerConversions) {}
86 nsDocumentOpenInfo::~nsDocumentOpenInfo() {}
88 nsresult nsDocumentOpenInfo::Prepare() {
89 LOG(("[0x%p] nsDocumentOpenInfo::Prepare", this));
91 nsresult rv;
93 // ask our window context if it has a uri content listener...
94 m_contentListener = do_GetInterface(m_originalContext, &rv);
95 return rv;
98 NS_IMETHODIMP nsDocumentOpenInfo::OnStartRequest(nsIRequest* request) {
99 LOG(("[0x%p] nsDocumentOpenInfo::OnStartRequest", this));
100 MOZ_ASSERT(request);
101 if (!request) {
102 return NS_ERROR_UNEXPECTED;
105 nsresult rv = NS_OK;
108 // Deal with "special" HTTP responses:
110 // - In the case of a 204 (No Content) or 205 (Reset Content) response, do
111 // not try to find a content handler. Return NS_BINDING_ABORTED to cancel
112 // the request. This has the effect of ensuring that the DocLoader does
113 // not try to interpret this as a real request.
115 nsCOMPtr<nsIHttpChannel> httpChannel(do_QueryInterface(request, &rv));
117 if (NS_SUCCEEDED(rv)) {
118 uint32_t responseCode = 0;
120 rv = httpChannel->GetResponseStatus(&responseCode);
122 if (NS_FAILED(rv)) {
123 LOG_ERROR((" Failed to get HTTP response status"));
125 // behave as in the canceled case
126 return NS_OK;
129 LOG((" HTTP response status: %d", responseCode));
131 if (204 == responseCode || 205 == responseCode) {
132 return NS_BINDING_ABORTED;
137 // Make sure that the transaction has succeeded, so far...
139 nsresult status;
141 rv = request->GetStatus(&status);
143 NS_ASSERTION(NS_SUCCEEDED(rv), "Unable to get request status!");
144 if (NS_FAILED(rv)) return rv;
146 if (NS_FAILED(status)) {
147 LOG_ERROR((" Request failed, status: 0x%08" PRIX32,
148 static_cast<uint32_t>(status)));
151 // The transaction has already reported an error - so it will be torn
152 // down. Therefore, it is not necessary to return an error code...
154 return NS_OK;
157 rv = DispatchContent(request);
159 LOG((" After dispatch, m_targetStreamListener: 0x%p, rv: 0x%08" PRIX32,
160 m_targetStreamListener.get(), static_cast<uint32_t>(rv)));
162 NS_ASSERTION(
163 NS_SUCCEEDED(rv) || !m_targetStreamListener,
164 "Must not have an m_targetStreamListener with a failure return!");
166 NS_ENSURE_SUCCESS(rv, rv);
168 if (m_targetStreamListener)
169 rv = m_targetStreamListener->OnStartRequest(request);
171 LOG((" OnStartRequest returning: 0x%08" PRIX32, static_cast<uint32_t>(rv)));
173 return rv;
176 NS_IMETHODIMP
177 nsDocumentOpenInfo::CheckListenerChain() {
178 NS_ASSERTION(NS_IsMainThread(), "Should be on the main thread!");
179 nsresult rv = NS_OK;
180 nsCOMPtr<nsIThreadRetargetableStreamListener> retargetableListener =
181 do_QueryInterface(m_targetStreamListener, &rv);
182 if (retargetableListener) {
183 rv = retargetableListener->CheckListenerChain();
185 LOG(
186 ("[0x%p] nsDocumentOpenInfo::CheckListenerChain %s listener %p rv "
187 "%" PRIx32,
188 this, (NS_SUCCEEDED(rv) ? "success" : "failure"),
189 (nsIStreamListener*)m_targetStreamListener, static_cast<uint32_t>(rv)));
190 return rv;
193 NS_IMETHODIMP
194 nsDocumentOpenInfo::OnDataAvailable(nsIRequest* request, nsIInputStream* inStr,
195 uint64_t sourceOffset, uint32_t count) {
196 // if we have retarged to the end stream listener, then forward the call....
197 // otherwise, don't do anything
199 nsresult rv = NS_OK;
201 if (m_targetStreamListener)
202 rv = m_targetStreamListener->OnDataAvailable(request, inStr, sourceOffset,
203 count);
204 return rv;
207 NS_IMETHODIMP nsDocumentOpenInfo::OnStopRequest(nsIRequest* request,
208 nsresult aStatus) {
209 LOG(("[0x%p] nsDocumentOpenInfo::OnStopRequest", this));
211 if (m_targetStreamListener) {
212 nsCOMPtr<nsIStreamListener> listener(m_targetStreamListener);
214 // If this is a multipart stream, we could get another
215 // OnStartRequest after this... reset state.
216 m_targetStreamListener = nullptr;
217 mContentType.Truncate();
218 listener->OnStopRequest(request, aStatus);
220 mUsedContentHandler = false;
222 // Remember...
223 // In the case of multiplexed streams (such as multipart/x-mixed-replace)
224 // these stream listener methods could be called again :-)
226 return NS_OK;
229 nsresult nsDocumentOpenInfo::DispatchContent(nsIRequest* request) {
230 LOG(("[0x%p] nsDocumentOpenInfo::DispatchContent for type '%s'", this,
231 mContentType.get()));
233 MOZ_ASSERT(!m_targetStreamListener,
234 "Why do we already have a target stream listener?");
236 nsresult rv;
237 nsCOMPtr<nsIChannel> aChannel = do_QueryInterface(request);
238 if (!aChannel) {
239 LOG_ERROR((" Request is not a channel. Bailing."));
240 return NS_ERROR_FAILURE;
243 constexpr auto anyType = "*/*"_ns;
244 if (mContentType.IsEmpty() || mContentType == anyType) {
245 rv = aChannel->GetContentType(mContentType);
246 if (NS_FAILED(rv)) return rv;
247 LOG((" Got type from channel: '%s'", mContentType.get()));
250 bool isGuessFromExt =
251 mContentType.LowerCaseEqualsASCII(APPLICATION_GUESS_FROM_EXT);
252 if (isGuessFromExt) {
253 // Reset to application/octet-stream for now; no one other than the
254 // external helper app service should see APPLICATION_GUESS_FROM_EXT.
255 mContentType = APPLICATION_OCTET_STREAM;
256 aChannel->SetContentType(nsLiteralCString(APPLICATION_OCTET_STREAM));
259 // Check whether the data should be forced to be handled externally. This
260 // could happen because the Content-Disposition header is set so, or, in the
261 // future, because the user has specified external handling for the MIME
262 // type.
263 bool forceExternalHandling = false;
264 uint32_t disposition;
265 rv = aChannel->GetContentDisposition(&disposition);
267 if (NS_SUCCEEDED(rv) && disposition == nsIChannel::DISPOSITION_ATTACHMENT) {
268 forceExternalHandling = true;
271 LOG((" forceExternalHandling: %s", forceExternalHandling ? "yes" : "no"));
273 if (forceExternalHandling &&
274 mozilla::StaticPrefs::browser_download_open_pdf_attachments_inline()) {
275 // Check if this is a PDF which should be opened internally. We also handle
276 // octet-streams that look like they might be PDFs based on their extension.
277 bool isPDF = mContentType.LowerCaseEqualsASCII(APPLICATION_PDF);
278 if (!isPDF &&
279 (mContentType.LowerCaseEqualsASCII(APPLICATION_OCTET_STREAM) ||
280 mContentType.IsEmpty())) {
281 nsAutoString flname;
282 aChannel->GetContentDispositionFilename(flname);
283 isPDF = StringEndsWith(flname, u".pdf"_ns);
284 if (!isPDF) {
285 nsCOMPtr<nsIURI> uri;
286 aChannel->GetURI(getter_AddRefs(uri));
287 nsCOMPtr<nsIURL> url(do_QueryInterface(uri));
288 if (url) {
289 nsAutoCString ext;
290 url->GetFileExtension(ext);
291 isPDF = ext.EqualsLiteral("pdf");
296 // For a PDF, check if the preference is set that forces attachments to be
297 // opened inline. If so, treat it as a non-attachment by clearing
298 // 'forceExternalHandling' again. This allows it open a PDF directly
299 // instead of downloading it first. It may still end up being handled by
300 // a helper app depending anyway on the later checks.
301 if (isPDF) {
302 nsCOMPtr<nsILoadInfo> loadInfo;
303 aChannel->GetLoadInfo(getter_AddRefs(loadInfo));
305 nsCOMPtr<nsIMIMEInfo> mimeInfo;
307 nsCOMPtr<nsIMIMEService> mimeSvc(
308 do_GetService(NS_MIMESERVICE_CONTRACTID));
309 NS_ENSURE_TRUE(mimeSvc, NS_ERROR_FAILURE);
310 mimeSvc->GetFromTypeAndExtension(nsLiteralCString(APPLICATION_PDF), ""_ns,
311 getter_AddRefs(mimeInfo));
313 if (mimeInfo) {
314 int32_t action = nsIMIMEInfo::saveToDisk;
315 mimeInfo->GetPreferredAction(&action);
317 bool alwaysAsk = true;
318 mimeInfo->GetAlwaysAskBeforeHandling(&alwaysAsk);
319 forceExternalHandling =
320 alwaysAsk || action != nsIMIMEInfo::handleInternally;
325 if (!forceExternalHandling) {
327 // First step: See whether m_contentListener wants to handle this
328 // content type.
330 if (TryDefaultContentListener(aChannel)) {
331 LOG((" Success! Our default listener likes this type"));
332 // All done here
333 return NS_OK;
336 // If we aren't allowed to try other listeners, just skip through to
337 // trying to convert the data.
338 if (!(mFlags & nsIURILoader::DONT_RETARGET)) {
340 // Second step: See whether some other registered listener wants
341 // to handle this content type.
343 int32_t count = mURILoader ? mURILoader->m_listeners.Count() : 0;
344 nsCOMPtr<nsIURIContentListener> listener;
345 for (int32_t i = 0; i < count; i++) {
346 listener = do_QueryReferent(mURILoader->m_listeners[i]);
347 if (listener) {
348 if (TryContentListener(listener, aChannel)) {
349 LOG((" Found listener registered on the URILoader"));
350 return NS_OK;
352 } else {
353 // remove from the listener list, reset i and update count
354 mURILoader->m_listeners.RemoveObjectAt(i--);
355 --count;
360 // Third step: Try to find an nsIContentHandler for our type.
362 nsAutoCString handlerContractID(NS_CONTENT_HANDLER_CONTRACTID_PREFIX);
363 handlerContractID += mContentType;
365 nsCOMPtr<nsIContentHandler> contentHandler =
366 do_CreateInstance(handlerContractID.get());
367 if (contentHandler) {
368 LOG((" Content handler found"));
369 // Note that m_originalContext can be nullptr when running this in
370 // the parent process on behalf on a docshell in the content process,
371 // and in that case we only support content handlers that don't need
372 // the context.
373 rv = contentHandler->HandleContent(mContentType.get(),
374 m_originalContext, request);
375 // XXXbz returning an error code to represent handling the
376 // content is just bizarre!
377 if (rv != NS_ERROR_WONT_HANDLE_CONTENT) {
378 if (NS_FAILED(rv)) {
379 // The content handler has unexpectedly failed. Cancel the request
380 // just in case the handler didn't...
381 LOG((" Content handler failed. Aborting load"));
382 request->Cancel(rv);
383 } else {
384 LOG((" Content handler taking over load"));
385 mUsedContentHandler = true;
388 return rv;
391 } else {
392 LOG(
393 (" DONT_RETARGET flag set, so skipped over random other content "
394 "listeners and content handlers"));
398 // Fourth step: If no listener prefers this type, see if any stream
399 // converters exist to transform this content type into
400 // some other.
402 // Don't do this if the server sent us a MIME type of "*/*" because they saw
403 // it in our Accept header and got confused.
404 // XXXbz have to be careful here; may end up in some sort of bizarre
405 // infinite decoding loop.
406 if (mContentType != anyType) {
407 rv = TryStreamConversion(aChannel);
408 if (NS_SUCCEEDED(rv)) {
409 return NS_OK;
414 NS_ASSERTION(!m_targetStreamListener,
415 "If we found a listener, why are we not using it?");
417 if (mFlags & nsIURILoader::DONT_RETARGET) {
418 LOG(
419 (" External handling forced or (listener not interested and no "
420 "stream converter exists), and retargeting disallowed -> aborting"));
421 return NS_ERROR_WONT_HANDLE_CONTENT;
424 // Before dispatching to the external helper app service, check for an HTTP
425 // error page. If we got one, we don't want to handle it with a helper app,
426 // really.
427 // The WPT a-download-click-404.html requires us to silently handle this
428 // without displaying an error page, so we just return early here.
429 // See bug 1604308 for discussion around what the ideal behaviour is.
430 nsCOMPtr<nsIHttpChannel> httpChannel(do_QueryInterface(request));
431 if (httpChannel) {
432 bool requestSucceeded;
433 rv = httpChannel->GetRequestSucceeded(&requestSucceeded);
434 if (NS_FAILED(rv) || !requestSucceeded) {
435 return NS_OK;
439 // Fifth step:
441 // All attempts to dispatch this content have failed. Just pass it off to
442 // the helper app service.
445 nsCOMPtr<nsIExternalHelperAppService> helperAppService =
446 do_GetService(NS_EXTERNALHELPERAPPSERVICE_CONTRACTID, &rv);
447 if (helperAppService) {
448 LOG((" Passing load off to helper app service"));
450 // Set these flags to indicate that the channel has been targeted and that
451 // we are not using the original consumer.
452 nsLoadFlags loadFlags = 0;
453 request->GetLoadFlags(&loadFlags);
454 request->SetLoadFlags(loadFlags | nsIChannel::LOAD_RETARGETED_DOCUMENT_URI |
455 nsIChannel::LOAD_TARGETED);
457 if (isGuessFromExt || mContentType.IsEmpty()) {
458 mContentType = APPLICATION_GUESS_FROM_EXT;
459 aChannel->SetContentType(nsLiteralCString(APPLICATION_GUESS_FROM_EXT));
462 rv = TryExternalHelperApp(helperAppService, aChannel);
463 if (NS_FAILED(rv)) {
464 request->SetLoadFlags(loadFlags);
465 m_targetStreamListener = nullptr;
469 NS_ASSERTION(m_targetStreamListener || NS_FAILED(rv),
470 "There is no way we should be successful at this point without "
471 "a m_targetStreamListener");
472 return rv;
475 nsresult nsDocumentOpenInfo::TryExternalHelperApp(
476 nsIExternalHelperAppService* aHelperAppService, nsIChannel* aChannel) {
477 return aHelperAppService->DoContent(mContentType, aChannel, m_originalContext,
478 false, nullptr,
479 getter_AddRefs(m_targetStreamListener));
482 nsresult nsDocumentOpenInfo::ConvertData(nsIRequest* request,
483 nsIURIContentListener* aListener,
484 const nsACString& aSrcContentType,
485 const nsACString& aOutContentType) {
486 LOG(("[0x%p] nsDocumentOpenInfo::ConvertData from '%s' to '%s'", this,
487 PromiseFlatCString(aSrcContentType).get(),
488 PromiseFlatCString(aOutContentType).get()));
490 if (mDataConversionDepthLimit == 0) {
491 LOG(
492 ("[0x%p] nsDocumentOpenInfo::ConvertData - reached the recursion "
493 "limit!",
494 this));
495 // This will fall back to external helper app handling.
496 return NS_ERROR_ABORT;
499 MOZ_ASSERT(aSrcContentType != aOutContentType,
500 "ConvertData called when the two types are the same!");
502 nsresult rv = NS_OK;
504 nsCOMPtr<nsIStreamConverterService> StreamConvService =
505 do_GetService(NS_STREAMCONVERTERSERVICE_CONTRACTID, &rv);
506 if (NS_FAILED(rv)) return rv;
508 LOG((" Got converter service"));
510 // When applying stream decoders, it is necessary to "insert" an
511 // intermediate nsDocumentOpenInfo instance to handle the targeting of
512 // the "final" stream or streams.
514 // For certain content types (ie. multi-part/x-mixed-replace) the input
515 // stream is split up into multiple destination streams. This
516 // intermediate instance is used to target these "decoded" streams...
518 RefPtr<nsDocumentOpenInfo> nextLink = Clone();
520 LOG((" Downstream DocumentOpenInfo would be: 0x%p", nextLink.get()));
522 // Decrease the conversion recursion limit by one to prevent infinite loops.
523 nextLink->mDataConversionDepthLimit = mDataConversionDepthLimit - 1;
525 // Make sure nextLink starts with the contentListener that said it wanted
526 // the results of this decode.
527 nextLink->m_contentListener = aListener;
528 // Also make sure it has to look for a stream listener to pump data into.
529 nextLink->m_targetStreamListener = nullptr;
531 // Make sure that nextLink treats the data as aOutContentType when
532 // dispatching; that way even if the stream converters don't change the type
533 // on the channel we will still do the right thing. If aOutContentType is
534 // */*, that's OK -- that will just indicate to nextLink that it should get
535 // the type off the channel.
536 nextLink->mContentType = aOutContentType;
538 // The following call sets m_targetStreamListener to the input end of the
539 // stream converter and sets the output end of the stream converter to
540 // nextLink. As we pump data into m_targetStreamListener the stream
541 // converter will convert it and pass the converted data to nextLink.
542 return StreamConvService->AsyncConvertData(
543 PromiseFlatCString(aSrcContentType).get(),
544 PromiseFlatCString(aOutContentType).get(), nextLink, request,
545 getter_AddRefs(m_targetStreamListener));
548 nsresult nsDocumentOpenInfo::TryStreamConversion(nsIChannel* aChannel) {
549 constexpr auto anyType = "*/*"_ns;
551 // A empty content type should be treated like the unknown content type.
552 nsCString srcContentType(mContentType);
553 if (srcContentType.IsEmpty()) {
554 srcContentType.AssignLiteral(UNKNOWN_CONTENT_TYPE);
557 nsresult rv =
558 ConvertData(aChannel, m_contentListener, srcContentType, anyType);
559 if (NS_FAILED(rv)) {
560 m_targetStreamListener = nullptr;
561 } else if (m_targetStreamListener) {
562 // We found a converter for this MIME type. We'll just pump data into
563 // it and let the downstream nsDocumentOpenInfo handle things.
564 LOG((" Converter taking over now"));
566 return rv;
569 bool nsDocumentOpenInfo::TryContentListener(nsIURIContentListener* aListener,
570 nsIChannel* aChannel) {
571 LOG(("[0x%p] nsDocumentOpenInfo::TryContentListener; mFlags = 0x%x", this,
572 mFlags));
574 MOZ_ASSERT(aListener, "Must have a non-null listener");
575 MOZ_ASSERT(aChannel, "Must have a channel");
577 bool listenerWantsContent = false;
578 nsCString typeToUse;
580 if (mFlags & nsIURILoader::IS_CONTENT_PREFERRED) {
581 aListener->IsPreferred(mContentType.get(), getter_Copies(typeToUse),
582 &listenerWantsContent);
583 } else {
584 aListener->CanHandleContent(mContentType.get(), false,
585 getter_Copies(typeToUse),
586 &listenerWantsContent);
588 if (!listenerWantsContent) {
589 LOG((" Listener is not interested"));
590 return false;
593 if (!typeToUse.IsEmpty() && typeToUse != mContentType) {
594 // Need to do a conversion here.
596 nsresult rv = NS_ERROR_NOT_AVAILABLE;
597 if (mAllowListenerConversions) {
598 rv = ConvertData(aChannel, aListener, mContentType, typeToUse);
601 if (NS_FAILED(rv)) {
602 // No conversion path -- we don't want this listener, if we got one
603 m_targetStreamListener = nullptr;
606 LOG((" Found conversion: %s", m_targetStreamListener ? "yes" : "no"));
608 // m_targetStreamListener is now the input end of the converter, and we can
609 // just pump the data in there, if it exists. If it does not, we need to
610 // try other nsIURIContentListeners.
611 return m_targetStreamListener != nullptr;
614 // At this point, aListener wants data of type mContentType. Let 'em have
615 // it. But first, if we are retargeting, set an appropriate flag on the
616 // channel
617 nsLoadFlags loadFlags = 0;
618 aChannel->GetLoadFlags(&loadFlags);
620 // Set this flag to indicate that the channel has been targeted at a final
621 // consumer. This load flag is tested in nsDocLoader::OnProgress.
622 nsLoadFlags newLoadFlags = nsIChannel::LOAD_TARGETED;
624 nsCOMPtr<nsIURIContentListener> originalListener =
625 do_GetInterface(m_originalContext);
626 if (originalListener != aListener) {
627 newLoadFlags |= nsIChannel::LOAD_RETARGETED_DOCUMENT_URI;
629 aChannel->SetLoadFlags(loadFlags | newLoadFlags);
631 bool abort = false;
632 bool isPreferred = (mFlags & nsIURILoader::IS_CONTENT_PREFERRED) != 0;
633 nsresult rv =
634 aListener->DoContent(mContentType, isPreferred, aChannel,
635 getter_AddRefs(m_targetStreamListener), &abort);
637 if (NS_FAILED(rv)) {
638 LOG_ERROR((" DoContent failed"));
640 // Unset the RETARGETED_DOCUMENT_URI flag if we set it...
641 aChannel->SetLoadFlags(loadFlags);
642 m_targetStreamListener = nullptr;
643 return false;
646 if (abort) {
647 // Nothing else to do here -- aListener is handling it all. Make
648 // sure m_targetStreamListener is null so we don't do anything
649 // after this point.
650 LOG((" Listener has aborted the load"));
651 m_targetStreamListener = nullptr;
654 NS_ASSERTION(abort || m_targetStreamListener,
655 "DoContent returned no listener?");
657 // aListener is handling the load from this point on.
658 return true;
661 bool nsDocumentOpenInfo::TryDefaultContentListener(nsIChannel* aChannel) {
662 if (m_contentListener) {
663 return TryContentListener(m_contentListener, aChannel);
665 return false;
668 ///////////////////////////////////////////////////////////////////////////////////////////////
669 // Implementation of nsURILoader
670 ///////////////////////////////////////////////////////////////////////////////////////////////
672 nsURILoader::nsURILoader() {}
674 nsURILoader::~nsURILoader() {}
676 NS_IMPL_ADDREF(nsURILoader)
677 NS_IMPL_RELEASE(nsURILoader)
679 NS_INTERFACE_MAP_BEGIN(nsURILoader)
680 NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIURILoader)
681 NS_INTERFACE_MAP_ENTRY(nsIURILoader)
682 NS_INTERFACE_MAP_END
684 NS_IMETHODIMP nsURILoader::RegisterContentListener(
685 nsIURIContentListener* aContentListener) {
686 nsresult rv = NS_OK;
688 nsWeakPtr weakListener = do_GetWeakReference(aContentListener);
689 NS_ASSERTION(weakListener,
690 "your URIContentListener must support weak refs!\n");
692 if (weakListener) m_listeners.AppendObject(weakListener);
694 return rv;
697 NS_IMETHODIMP nsURILoader::UnRegisterContentListener(
698 nsIURIContentListener* aContentListener) {
699 nsWeakPtr weakListener = do_GetWeakReference(aContentListener);
700 if (weakListener) m_listeners.RemoveObject(weakListener);
702 return NS_OK;
705 NS_IMETHODIMP nsURILoader::OpenURI(nsIChannel* channel, uint32_t aFlags,
706 nsIInterfaceRequestor* aWindowContext) {
707 NS_ENSURE_ARG_POINTER(channel);
709 if (LOG_ENABLED()) {
710 nsCOMPtr<nsIURI> uri;
711 channel->GetURI(getter_AddRefs(uri));
712 nsAutoCString spec;
713 uri->GetAsciiSpec(spec);
714 LOG(("nsURILoader::OpenURI for %s", spec.get()));
717 nsCOMPtr<nsIStreamListener> loader;
718 nsresult rv = OpenChannel(channel, aFlags, aWindowContext, false,
719 getter_AddRefs(loader));
720 if (NS_FAILED(rv)) {
721 if (rv == NS_ERROR_WONT_HANDLE_CONTENT) {
722 // Not really an error, from this method's point of view
723 return NS_OK;
727 // This method is not complete. Eventually, we should first go
728 // to the content listener and ask them for a protocol handler...
729 // if they don't give us one, we need to go to the registry and get
730 // the preferred protocol handler.
732 // But for now, I'm going to let necko do the work for us....
733 rv = channel->AsyncOpen(loader);
735 // no content from this load - that's OK.
736 if (rv == NS_ERROR_NO_CONTENT) {
737 LOG((" rv is NS_ERROR_NO_CONTENT -- doing nothing"));
738 return NS_OK;
740 return rv;
743 nsresult nsURILoader::OpenChannel(nsIChannel* channel, uint32_t aFlags,
744 nsIInterfaceRequestor* aWindowContext,
745 bool aChannelIsOpen,
746 nsIStreamListener** aListener) {
747 NS_ASSERTION(channel, "Trying to open a null channel!");
748 NS_ASSERTION(aWindowContext, "Window context must not be null");
750 if (LOG_ENABLED()) {
751 nsCOMPtr<nsIURI> uri;
752 channel->GetURI(getter_AddRefs(uri));
753 nsAutoCString spec;
754 uri->GetAsciiSpec(spec);
755 LOG(("nsURILoader::OpenChannel for %s", spec.get()));
758 // we need to create a DocumentOpenInfo object which will go ahead and open
759 // the url and discover the content type....
760 RefPtr<nsDocumentOpenInfo> loader =
761 new nsDocumentOpenInfo(aWindowContext, aFlags, this);
763 // Set the correct loadgroup on the channel
764 nsCOMPtr<nsILoadGroup> loadGroup(do_GetInterface(aWindowContext));
766 if (!loadGroup) {
767 // XXXbz This context is violating what we'd like to be the new uriloader
768 // api.... Set up a nsDocLoader to handle the loadgroup for this context.
769 // This really needs to go away!
770 nsCOMPtr<nsIURIContentListener> listener(do_GetInterface(aWindowContext));
771 if (listener) {
772 nsCOMPtr<nsISupports> cookie;
773 listener->GetLoadCookie(getter_AddRefs(cookie));
774 if (!cookie) {
775 RefPtr<nsDocLoader> newDocLoader = new nsDocLoader();
776 nsresult rv = newDocLoader->Init();
777 if (NS_FAILED(rv)) return rv;
778 rv = nsDocLoader::AddDocLoaderAsChildOfRoot(newDocLoader);
779 if (NS_FAILED(rv)) return rv;
780 cookie = nsDocLoader::GetAsSupports(newDocLoader);
781 listener->SetLoadCookie(cookie);
783 loadGroup = do_GetInterface(cookie);
787 // If the channel is pending, then we need to remove it from its current
788 // loadgroup
789 nsCOMPtr<nsILoadGroup> oldGroup;
790 channel->GetLoadGroup(getter_AddRefs(oldGroup));
791 if (aChannelIsOpen && !SameCOMIdentity(oldGroup, loadGroup)) {
792 // It is important to add the channel to the new group before
793 // removing it from the old one, so that the load isn't considered
794 // done as soon as the request is removed.
795 loadGroup->AddRequest(channel, nullptr);
797 if (oldGroup) {
798 oldGroup->RemoveRequest(channel, nullptr, NS_BINDING_RETARGETED);
802 channel->SetLoadGroup(loadGroup);
804 // prepare the loader for receiving data
805 nsresult rv = loader->Prepare();
806 if (NS_SUCCEEDED(rv)) NS_ADDREF(*aListener = loader);
807 return rv;
810 NS_IMETHODIMP nsURILoader::OpenChannel(nsIChannel* channel, uint32_t aFlags,
811 nsIInterfaceRequestor* aWindowContext,
812 nsIStreamListener** aListener) {
813 bool pending;
814 if (NS_FAILED(channel->IsPending(&pending))) {
815 pending = false;
818 return OpenChannel(channel, aFlags, aWindowContext, pending, aListener);
821 NS_IMETHODIMP nsURILoader::Stop(nsISupports* aLoadCookie) {
822 nsresult rv;
823 nsCOMPtr<nsIDocumentLoader> docLoader;
825 NS_ENSURE_ARG_POINTER(aLoadCookie);
827 docLoader = do_GetInterface(aLoadCookie, &rv);
828 if (docLoader) {
829 rv = docLoader->Stop();
831 return rv;