1
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
3
* The contents of this file are subject to the Mozilla Public
4
* License Version 1.1 (the "License"); you may not use this file
5
* except in compliance with the License. You may obtain a copy of
6
* the License at http://www.mozilla.org/MPL/
8
* Software distributed under the License is distributed on an "AS
9
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
10
* implied. See the License for the specific language governing
11
* rights and limitations under the License.
13
* The Original Code is mozilla.org code.
15
* The Initial Developer of the Original Code is Netscape
16
* Communications Corporation. Portions created by Netscape are
17
* Copyright (C) 2001 Netscape Communications Corporation.
18
* All Rights Reserved.
21
* Stuart Parmenter <pavlov@netscape.com>
24
#include "imgLoader.h"
28
#include "nsNetUtil.h"
29
#include "nsIHttpChannel.h"
30
#include "nsICachingChannel.h"
31
#include "nsIProxyObjectManager.h"
32
#include "nsIServiceManager.h"
33
#include "nsXPIDLString.h"
39
#include "imgRequest.h"
40
#include "imgRequestProxy.h"
42
#include "ImageErrors.h"
43
#include "ImageLogging.h"
45
#include "nsIComponentRegistrar.h"
47
// we want to explore making the document own the load group
48
// so we can associate the document URI with the load group.
49
// until this point, we have an evil hack:
50
#include "nsIHttpChannelInternal.h"
52
#if defined(DEBUG_pavlov) || defined(DEBUG_timeless)
53
#include "nsISimpleEnumerator.h"
55
#include "nsISupportsPrimitives.h"
56
#include "nsXPIDLString.h"
57
#include "nsComponentManagerUtils.h"
59
static void PrintImageDecoders()
61
nsCOMPtr<nsIComponentRegistrar> compMgr;
62
if (NS_FAILED(NS_GetComponentRegistrar(getter_AddRefs(compMgr))) || !compMgr)
64
nsCOMPtr<nsISimpleEnumerator> enumer;
65
if (NS_FAILED(compMgr->EnumerateContractIDs(getter_AddRefs(enumer))) || !enumer)
69
nsCOMPtr<nsISupports> s;
70
PRBool more = PR_FALSE;
71
while (NS_SUCCEEDED(enumer->HasMoreElements(&more)) && more) {
72
enumer->GetNext(getter_AddRefs(s));
74
nsCOMPtr<nsISupportsCString> ss(do_QueryInterface(s));
79
NS_NAMED_LITERAL_CSTRING(decoderContract, "@mozilla.org/image/decoder;2?type=");
81
if (StringBeginsWith(xcs, decoderContract)) {
82
printf("Have decoder for mime type: %s\n", xcs.get()+decoderContract.Length());
89
NS_IMPL_ISUPPORTS2(imgLoader, imgILoader, nsIContentSniffer)
91
imgLoader::imgLoader()
93
/* member initializers and constructor code */
99
imgLoader::~imgLoader()
101
/* destructor code */
104
#define LOAD_FLAGS_CACHE_MASK (nsIRequest::LOAD_BYPASS_CACHE | \
105
nsIRequest::LOAD_FROM_CACHE)
107
#define LOAD_FLAGS_VALIDATE_MASK (nsIRequest::VALIDATE_ALWAYS | \
108
nsIRequest::VALIDATE_NEVER | \
109
nsIRequest::VALIDATE_ONCE_PER_SESSION)
112
static PRBool RevalidateEntry(nsICacheEntryDescriptor *aEntry,
116
PRBool bValidateEntry = PR_FALSE;
118
NS_ASSERTION(!(aFlags & nsIRequest::LOAD_BYPASS_CACHE),
119
"MUST not revalidate when BYPASS_CACHE is specified.");
121
if (aFlags & nsIRequest::VALIDATE_ALWAYS) {
122
bValidateEntry = PR_TRUE;
125
// The cache entry has expired... Determine whether the stale cache
126
// entry can be used without validation...
128
else if (aHasExpired) {
130
// VALIDATE_NEVER and VALIDATE_ONCE_PER_SESSION allow stale cache
131
// entries to be used unless they have been explicitly marked to
132
// indicate that revalidation is necessary.
134
if (aFlags & (nsIRequest::VALIDATE_NEVER |
135
nsIRequest::VALIDATE_ONCE_PER_SESSION))
137
nsXPIDLCString value;
139
aEntry->GetMetaDataElement("MustValidateIfExpired",
140
getter_Copies(value));
141
if (PL_strcmp(value, "true")) {
142
bValidateEntry = PR_TRUE;
146
// LOAD_FROM_CACHE allows a stale cache entry to be used... Otherwise,
147
// the entry must be revalidated.
149
else if (!(aFlags & nsIRequest::LOAD_FROM_CACHE)) {
150
bValidateEntry = PR_TRUE;
154
return bValidateEntry;
158
static nsresult NewImageChannel(nsIChannel **aResult,
160
nsIURI *aInitialDocumentURI,
161
nsIURI *aReferringURI,
162
nsILoadGroup *aLoadGroup, nsLoadFlags aLoadFlags)
165
nsCOMPtr<nsIChannel> newChannel;
166
nsCOMPtr<nsIHttpChannel> newHttpChannel;
168
nsCOMPtr<nsIInterfaceRequestor> callbacks;
171
// Get the notification callbacks from the load group for the new channel.
173
// XXX: This is not exactly correct, because the network request could be
174
// referenced by multiple windows... However, the new channel needs
175
// something. So, using the 'first' notification callbacks is better
178
aLoadGroup->GetNotificationCallbacks(getter_AddRefs(callbacks));
181
// Pass in a NULL loadgroup because this is the underlying network request.
182
// This request may be referenced by several proxy image requests (psossibly
183
// in different documents).
184
// If all of the proxy requests are canceled then this request should be
187
rv = NS_NewChannel(aResult,
189
nsnull, // Cached IOService
191
callbacks, // Notification Callbacks
196
// Initialize HTTP-specific attributes
197
newHttpChannel = do_QueryInterface(*aResult);
198
if (newHttpChannel) {
199
newHttpChannel->SetRequestHeader(NS_LITERAL_CSTRING("Accept"),
200
NS_LITERAL_CSTRING("image/png,*/*;q=0.5"),
203
nsCOMPtr<nsIHttpChannelInternal> httpChannelInternal = do_QueryInterface(newHttpChannel);
204
NS_ENSURE_TRUE(httpChannelInternal, NS_ERROR_UNEXPECTED);
205
httpChannelInternal->SetDocumentURI(aInitialDocumentURI);
206
newHttpChannel->SetReferrer(aReferringURI);
212
/* imgIRequest loadImage (in nsIURI aURI, in nsIURI initialDocumentURI, in nsILoadGroup aLoadGroup, in imgIDecoderObserver aObserver, in nsISupports aCX, in nsLoadFlags aLoadFlags, in nsISupports cacheKey, in imgIRequest aRequest); */
214
NS_IMETHODIMP imgLoader::LoadImage(nsIURI *aURI,
215
nsIURI *aInitialDocumentURI,
216
nsIURI *aReferrerURI,
217
nsILoadGroup *aLoadGroup,
218
imgIDecoderObserver *aObserver,
220
nsLoadFlags aLoadFlags,
221
nsISupports *cacheKey,
222
imgIRequest *aRequest,
223
imgIRequest **_retval)
225
NS_ASSERTION(aURI, "imgLoader::LoadImage -- NULL URI pointer");
227
// CreateNewProxyForRequest treats _retval as inout - null out
228
// to make sure the passed value doesn't affect the behavior of
233
return NS_ERROR_NULL_POINTER;
235
#if defined(PR_LOGGING)
237
aURI->GetAsciiSpec(spec);
238
LOG_SCOPE_WITH_PARAM(gImgLog, "imgLoader::LoadImage", "aURI", spec.get());
241
// This is an owning reference that must be released.
242
imgRequest *request = nsnull;
245
nsLoadFlags requestFlags = nsIRequest::LOAD_NORMAL;
247
// Get the default load flags from the loadgroup (if possible)...
249
aLoadGroup->GetLoadFlags(&requestFlags);
252
// Merge the default load flags with those passed in via aLoadFlags.
253
// Currently, *only* the caching, validation and background load flags
256
// The flags in aLoadFlags take precidence over the default flags!
258
if (aLoadFlags & LOAD_FLAGS_CACHE_MASK) {
259
// Override the default caching flags...
260
requestFlags = (requestFlags & ~LOAD_FLAGS_CACHE_MASK) |
261
(aLoadFlags & LOAD_FLAGS_CACHE_MASK);
263
if (aLoadFlags & LOAD_FLAGS_VALIDATE_MASK) {
264
// Override the default validation flags...
265
requestFlags = (requestFlags & ~LOAD_FLAGS_VALIDATE_MASK) |
266
(aLoadFlags & LOAD_FLAGS_VALIDATE_MASK);
268
if (aLoadFlags & nsIRequest::LOAD_BACKGROUND) {
269
// Propagate background loading...
270
requestFlags |= nsIRequest::LOAD_BACKGROUND;
273
nsCOMPtr<nsICacheEntryDescriptor> entry;
274
PRBool bCanCacheRequest = PR_TRUE;
275
PRBool bHasExpired = PR_FALSE;
276
PRBool bValidateRequest = PR_FALSE;
278
PRBool addToLoadGroup = PR_TRUE;
280
// XXX For now ignore the cache key. We will need it in the future
281
// for correctly dealing with image load requests that are a result
283
imgCache::Get(aURI, &bHasExpired,
284
&request, getter_AddRefs(entry)); // addrefs request
286
if (request && entry) {
288
// request's null out their mCacheEntry when all proxy's are removed.
289
// If we are about to add a new one back, go ahead and re-set the cache
290
// entry so it can be used.
291
if (!request->mCacheEntry) {
292
request->mCacheEntry = entry;
295
// If the request's loadId is the same as the aCX, then it is ok to use
296
// this one because it has already been validated for this context.
298
// XXX: nsnull seems to be a 'special' key value that indicates that NO
299
// validation is required.
301
void *key = (void*)aCX;
302
if (request->mLoadId != key) {
304
// LOAD_BYPASS_CACHE - Always re-fetch
305
if (requestFlags & nsIRequest::LOAD_BYPASS_CACHE) {
306
// doom cache entry; be sure to break the reference cycle between the
307
// request and cache entry. NOTE: the request might not own the cache
308
// entry at this point, so we explicitly Doom |entry| just in case.
311
request->RemoveFromCache();
314
// Determine whether the cache entry must be revalidated...
315
bValidateRequest = RevalidateEntry(entry, requestFlags, bHasExpired);
317
PR_LOG(gImgLog, PR_LOG_DEBUG,
318
("imgLoader::LoadImage validating cache entry. "
319
"bValidateRequest = %d", bValidateRequest));
323
#if defined(PR_LOGGING)
325
PR_LOG(gImgLog, PR_LOG_DEBUG,
326
("imgLoader::LoadImage BYPASSING cache validation for %s "
327
"because of NULL LoadID", spec.get()));
333
// Get the current EventQueue... This is used as a cacheId to prevent
334
// sharing requests which are being loaded across multiple event queues...
336
nsCOMPtr<nsIEventQueueService> eventQService;
337
nsCOMPtr<nsIEventQueue> activeQ;
339
eventQService = do_GetService(NS_EVENTQUEUESERVICE_CONTRACTID, &rv);
341
NS_IF_RELEASE(request);
345
rv = eventQService->ResolveEventQueue(NS_CURRENT_EVENTQ,
346
getter_AddRefs(activeQ));
348
NS_IF_RELEASE(request);
352
void *cacheId = activeQ.get();
353
if (request && !request->IsReusable(cacheId)) {
355
// The current request is still being loaded and lives on a different
358
// Since its event queue is NOT active, do not reuse this imgRequest !!
359
// Instead, force a new request to be created but DO NOT allow it to be
362
PR_LOG(gImgLog, PR_LOG_DEBUG,
363
("[this=%p] imgLoader::LoadImage -- DANGER!! Unable to use cached "
364
"imgRequest [request=%p]\n", this, request));
369
bCanCacheRequest = PR_FALSE;
373
// Time to load the request... There are 3 possible cases:
374
// =======================================================
375
// 1. There is no cached request (ie. nothing was found in the cache).
377
// 2. There is a cached request that must be validated.
379
// 3. There is a valid cached request.
381
if (request && bValidateRequest) {
382
/* Case #2: the cache request cache must be revalidated. */
383
LOG_SCOPE(gImgLog, "imgLoader::LoadImage |cache hit| must validate");
385
// now we need to insert a new channel request object inbetween the real
386
// request and the proxy that basically delays loading the image until it
387
// gets a 304 or figures out that this needs to be a new request
389
if (request->mValidator) {
390
rv = CreateNewProxyForRequest(request, aLoadGroup, aObserver,
391
requestFlags, aRequest, _retval);
394
request->mValidator->AddProxy(NS_STATIC_CAST(imgRequestProxy*, *_retval));
400
nsCOMPtr<nsIChannel> newChannel;
401
rv = NewImageChannel(getter_AddRefs(newChannel),
409
return NS_ERROR_FAILURE;
412
nsCOMPtr<nsICachingChannel> cacheChan(do_QueryInterface(newChannel));
415
// since this channel supports nsICachingChannel, we can ask it
416
// to only stream us data if the data comes off the net.
418
if (NS_SUCCEEDED(newChannel->GetLoadFlags(&loadFlags)))
419
newChannel->SetLoadFlags(loadFlags | nsICachingChannel::LOAD_ONLY_IF_MODIFIED);
422
nsCOMPtr<imgIRequest> req;
423
rv = CreateNewProxyForRequest(request, aLoadGroup, aObserver,
424
requestFlags, aRequest, getter_AddRefs(req));
430
imgCacheValidator *hvc = new imgCacheValidator(request, aCX);
433
return NS_ERROR_OUT_OF_MEMORY;
437
request->mValidator = hvc;
439
hvc->AddProxy(NS_STATIC_CAST(imgRequestProxy*,
440
NS_STATIC_CAST(imgIRequest*, req.get())));
442
rv = newChannel->AsyncOpen(NS_STATIC_CAST(nsIStreamListener *, hvc), nsnull);
443
if (NS_SUCCEEDED(rv))
444
NS_ADDREF(*_retval = req.get());
452
} else if (!request) {
453
/* Case #1: no request from the cache. do a new load */
454
LOG_SCOPE(gImgLog, "imgLoader::LoadImage |cache miss|");
456
nsCOMPtr<nsIChannel> newChannel;
457
rv = NewImageChannel(getter_AddRefs(newChannel),
464
return NS_ERROR_FAILURE;
466
NS_NEWXPCOM(request, imgRequest);
467
if (!request) return NS_ERROR_OUT_OF_MEMORY;
471
PR_LOG(gImgLog, PR_LOG_DEBUG,
472
("[this=%p] imgLoader::LoadImage -- Created new imgRequest [request=%p]\n", this, request));
474
// Add the new request into the imgCache if its cachable...
475
if (bCanCacheRequest) {
476
imgCache::Put(aURI, request, getter_AddRefs(entry));
479
request->Init(newChannel, entry, cacheId, aCX);
481
// create the proxy listener
482
ProxyListener *pl = new ProxyListener(NS_STATIC_CAST(nsIStreamListener *, request));
485
return NS_ERROR_OUT_OF_MEMORY;
490
PR_LOG(gImgLog, PR_LOG_DEBUG,
491
("[this=%p] imgLoader::LoadImage -- Calling channel->AsyncOpen()\n", this));
494
openRes = newChannel->AsyncOpen(NS_STATIC_CAST(nsIStreamListener *, pl), nsnull);
498
if (NS_FAILED(openRes)) {
504
/* Case #3: request found in cache. use it */
505
// XXX: Should this be executed if an expired cache entry does not have a caching channel??
506
LOG_MSG_WITH_PARAM(gImgLog,
507
"imgLoader::LoadImage |cache hit|", "request", request);
509
// Update the request's LoadId
510
request->SetLoadId(aCX);
512
// request is already loaded, no need to add anything to the
514
addToLoadGroup = PR_FALSE;
517
LOG_MSG(gImgLog, "imgLoader::LoadImage", "creating proxy request.");
519
rv = CreateNewProxyForRequest(request, aLoadGroup, aObserver,
520
requestFlags, aRequest, _retval);
522
imgRequestProxy *proxy = (imgRequestProxy *)*_retval;
524
if (addToLoadGroup) {
525
proxy->AddToLoadGroup();
528
// if we have to validate the request, then we will send the
529
// notifications later.
530
if (!bValidateRequest) {
531
request->NotifyProxyListener(proxy);
539
/* imgIRequest loadImageWithChannel(in nsIChannel channel, in imgIDecoderObserver aObserver, in nsISupports cx, out nsIStreamListener); */
540
NS_IMETHODIMP imgLoader::LoadImageWithChannel(nsIChannel *channel, imgIDecoderObserver *aObserver, nsISupports *aCX, nsIStreamListener **listener, imgIRequest **_retval)
542
NS_ASSERTION(channel, "imgLoader::LoadImageWithChannel -- NULL channel pointer");
544
// CreateNewProxyForRequest treats _retval as inout - null out
545
// to make sure the passed value doesn't affect the behavior of
550
imgRequest *request = nsnull;
552
nsCOMPtr<nsIURI> uri;
553
channel->GetURI(getter_AddRefs(uri));
555
nsCOMPtr<nsICacheEntryDescriptor> entry;
558
imgCache::Get(uri, &bHasExpired, &request, getter_AddRefs(entry)); // addrefs request
560
nsLoadFlags requestFlags = nsIRequest::LOAD_NORMAL;
562
channel->GetLoadFlags(&requestFlags);
565
PRBool bUseCacheCopy = PR_TRUE;
567
// LOAD_BYPASS_CACHE - Always re-fetch
568
if (requestFlags & nsIRequest::LOAD_BYPASS_CACHE) {
569
bUseCacheCopy = PR_FALSE;
571
else if (RevalidateEntry(entry, requestFlags, bHasExpired)) {
572
nsCOMPtr<nsICachingChannel> cacheChan(do_QueryInterface(channel));
574
cacheChan->IsFromCache(&bUseCacheCopy);
576
bUseCacheCopy = PR_FALSE;
580
if (!bUseCacheCopy) {
581
// doom cache entry; be sure to break the reference cycle between the
582
// request and cache entry. NOTE: the request might not own the cache
583
// entry at this point, so we explicitly Doom |entry| just in case.
586
request->RemoveFromCache();
591
nsCOMPtr<nsILoadGroup> loadGroup;
592
channel->GetLoadGroup(getter_AddRefs(loadGroup));
595
// we have this in our cache already.. cancel the current (document) load
597
/* XXX If |*listener| is null when we return here, the caller should
598
probably cancel the channel instead of us doing it here.
600
channel->Cancel(NS_IMAGELIB_ERROR_LOAD_ABORTED); // this should fire an OnStopRequest
602
*listener = nsnull; // give them back a null nsIStreamListener
605
// Get the current EventQueue... This is used as a cacheId to prevent
606
// sharing requests which are being loaded across multiple event queues...
608
nsCOMPtr<nsIEventQueueService> eventQService;
609
nsCOMPtr<nsIEventQueue> activeQ;
611
eventQService = do_GetService(NS_EVENTQUEUESERVICE_CONTRACTID, &rv);
615
rv = eventQService->ResolveEventQueue(NS_CURRENT_EVENTQ, getter_AddRefs(activeQ));
619
NS_NEWXPCOM(request, imgRequest);
620
if (!request) return NS_ERROR_OUT_OF_MEMORY;
624
imgCache::Put(uri, request, getter_AddRefs(entry));
626
request->Init(channel, entry, activeQ.get(), aCX);
628
ProxyListener *pl = new ProxyListener(NS_STATIC_CAST(nsIStreamListener *, request));
631
return NS_ERROR_OUT_OF_MEMORY;
636
*listener = NS_STATIC_CAST(nsIStreamListener*, pl);
637
NS_ADDREF(*listener);
642
// XXX: It looks like the wrong load flags are being passed in...
643
requestFlags &= 0xFFFF;
645
rv = CreateNewProxyForRequest(request, loadGroup, aObserver,
646
requestFlags, nsnull, _retval);
647
request->NotifyProxyListener(NS_STATIC_CAST(imgRequestProxy*, *_retval));
656
imgLoader::CreateNewProxyForRequest(imgRequest *aRequest, nsILoadGroup *aLoadGroup,
657
imgIDecoderObserver *aObserver,
658
nsLoadFlags aLoadFlags, imgIRequest *aProxyRequest,
659
imgIRequest **_retval)
661
LOG_SCOPE_WITH_PARAM(gImgLog, "imgLoader::CreateNewProxyForRequest", "imgRequest", aRequest);
663
/* XXX If we move decoding onto separate threads, we should save off the
664
calling thread here and pass it off to |proxyRequest| so that it call
665
proxy calls to |aObserver|.
668
imgRequestProxy *proxyRequest;
670
proxyRequest = NS_STATIC_CAST(imgRequestProxy *, aProxyRequest);
672
NS_NEWXPCOM(proxyRequest, imgRequestProxy);
673
if (!proxyRequest) return NS_ERROR_OUT_OF_MEMORY;
675
NS_ADDREF(proxyRequest);
677
/* It is important to call |SetLoadFlags()| before calling |Init()| because
678
|Init()| adds the request to the loadgroup.
680
proxyRequest->SetLoadFlags(aLoadFlags);
682
// init adds itself to imgRequest's list of observers
683
nsresult rv = proxyRequest->Init(aRequest, aLoadGroup, aObserver);
685
NS_RELEASE(proxyRequest);
690
(*_retval)->Cancel(NS_IMAGELIB_ERROR_LOAD_ABORTED);
691
NS_RELEASE(*_retval);
693
*_retval = NS_STATIC_CAST(imgIRequest*, proxyRequest);
696
NS_RELEASE(proxyRequest);
701
NS_IMETHODIMP imgLoader::SupportImageWithMimeType(const char* aMimeType, PRBool *_retval)
704
nsCOMPtr<nsIComponentRegistrar> reg;
705
nsresult rv = NS_GetComponentRegistrar(getter_AddRefs(reg));
708
nsCAutoString mimeType(aMimeType);
709
ToLowerCase(mimeType);
710
nsCAutoString decoderId(NS_LITERAL_CSTRING("@mozilla.org/image/decoder;2?type=") + mimeType);
711
return reg->IsContractIDRegistered(decoderId.get(), _retval);
714
NS_IMETHODIMP imgLoader::GetMIMETypeFromContent(const PRUint8* aContents, PRUint32 aLength, nsACString& aContentType)
716
return GetMimeTypeFromContent((const char*)aContents, aLength, aContentType);
720
nsresult imgLoader::GetMimeTypeFromContent(const char* aContents, PRUint32 aLength, nsACString& aContentType)
723
if (aLength >= 4 && !nsCRT::strncmp(aContents, "GIF8", 4)) {
724
aContentType.Assign(NS_LITERAL_CSTRING("image/gif"));
728
else if (aLength >= 4 && ((unsigned char)aContents[0]==0x89 &&
729
(unsigned char)aContents[1]==0x50 &&
730
(unsigned char)aContents[2]==0x4E &&
731
(unsigned char)aContents[3]==0x47))
733
aContentType.Assign(NS_LITERAL_CSTRING("image/png"));
736
/* maybe a JPEG (JFIF)? */
737
/* JFIF files start with SOI APP0 but older files can start with SOI DQT
738
* so we test for SOI followed by any marker, i.e. FF D8 FF
739
* this will also work for SPIFF JPEG files if they appear in the future.
741
* (JFIF is 0XFF 0XD8 0XFF 0XE0 <skip 2> 0X4A 0X46 0X49 0X46 0X00)
743
else if (aLength >= 3 &&
744
((unsigned char)aContents[0])==0xFF &&
745
((unsigned char)aContents[1])==0xD8 &&
746
((unsigned char)aContents[2])==0xFF)
748
aContentType.Assign(NS_LITERAL_CSTRING("image/jpeg"));
751
/* or how about ART? */
752
/* ART begins with JG (4A 47). Major version offset 2.
753
* Minor version offset 3. Offset 4 must be NULL.
755
else if (aLength >= 5 &&
756
((unsigned char) aContents[0])==0x4a &&
757
((unsigned char) aContents[1])==0x47 &&
758
((unsigned char) aContents[4])==0x00 )
760
aContentType.Assign(NS_LITERAL_CSTRING("image/x-jg"));
763
else if (aLength >= 2 && !nsCRT::strncmp(aContents, "BM", 2)) {
764
aContentType.Assign(NS_LITERAL_CSTRING("image/bmp"));
767
// ICOs always begin with a 2-byte 0 followed by a 2-byte 1.
768
else if (aLength >= 4 && !memcmp(aContents, "\000\000\001\000", 4)) {
769
aContentType.Assign(NS_LITERAL_CSTRING("image/x-icon"));
772
else if (aLength >= 8 && !nsCRT::strncmp(aContents, "#define ", 8)) {
773
aContentType.Assign(NS_LITERAL_CSTRING("image/x-xbitmap"));
776
/* none of the above? I give up */
777
return NS_ERROR_NOT_AVAILABLE;
784
* proxy stream listener class used to handle multipart/x-mixed-replace
787
#include "nsIRequest.h"
788
#include "nsIStreamConverterService.h"
789
#include "nsXPIDLString.h"
791
NS_IMPL_ISUPPORTS2(ProxyListener, nsIStreamListener, nsIRequestObserver)
793
ProxyListener::ProxyListener(nsIStreamListener *dest) :
796
/* member initializers and constructor code */
799
ProxyListener::~ProxyListener()
801
/* destructor code */
805
/** nsIRequestObserver methods **/
807
/* void onStartRequest (in nsIRequest request, in nsISupports ctxt); */
808
NS_IMETHODIMP ProxyListener::OnStartRequest(nsIRequest *aRequest, nsISupports *ctxt)
811
return NS_ERROR_FAILURE;
813
nsCOMPtr<nsIChannel> channel(do_QueryInterface(aRequest));
815
nsCAutoString contentType;
816
nsresult rv = channel->GetContentType(contentType);
818
if (!contentType.IsEmpty()) {
819
/* If multipart/x-mixed-replace content, we'll insert a MIME decoder
820
in the pipeline to handle the content and pass it along to our
823
if (NS_LITERAL_CSTRING("multipart/x-mixed-replace").Equals(contentType)) {
825
nsCOMPtr<nsIStreamConverterService> convServ(do_GetService("@mozilla.org/streamConverters;1", &rv));
826
if (NS_SUCCEEDED(rv)) {
827
nsCOMPtr<nsIStreamListener> toListener(mDestListener);
828
nsCOMPtr<nsIStreamListener> fromListener;
830
rv = convServ->AsyncConvertData(NS_LITERAL_STRING("multipart/x-mixed-replace").get(),
831
NS_LITERAL_STRING("*/*").get(),
834
getter_AddRefs(fromListener));
835
if (NS_SUCCEEDED(rv))
836
mDestListener = fromListener;
842
return mDestListener->OnStartRequest(aRequest, ctxt);
845
/* void onStopRequest (in nsIRequest request, in nsISupports ctxt, in nsresult status); */
846
NS_IMETHODIMP ProxyListener::OnStopRequest(nsIRequest *aRequest, nsISupports *ctxt, nsresult status)
849
return NS_ERROR_FAILURE;
851
return mDestListener->OnStopRequest(aRequest, ctxt, status);
854
/** nsIStreamListener methods **/
856
/* void onDataAvailable (in nsIRequest request, in nsISupports ctxt, in nsIInputStream inStr, in unsigned long sourceOffset, in unsigned long count); */
857
NS_IMETHODIMP ProxyListener::OnDataAvailable(nsIRequest *aRequest, nsISupports *ctxt, nsIInputStream *inStr, PRUint32 sourceOffset, PRUint32 count)
860
return NS_ERROR_FAILURE;
862
return mDestListener->OnDataAvailable(aRequest, ctxt, inStr, sourceOffset, count);
870
* http validate class. check a channel for a 304
873
NS_IMPL_ISUPPORTS2(imgCacheValidator, nsIStreamListener, nsIRequestObserver)
875
imgCacheValidator::imgCacheValidator(imgRequest *request, void *aContext) :
878
/* member initializers and constructor code */
884
imgCacheValidator::~imgCacheValidator()
886
/* destructor code */
888
mRequest->mValidator = nsnull;
889
NS_RELEASE(mRequest);
893
void imgCacheValidator::AddProxy(imgRequestProxy *aProxy)
895
// aProxy needs to be in the loadgroup since we're validating from
897
aProxy->AddToLoadGroup();
899
mProxies.AppendElement(aProxy);
902
/** nsIRequestObserver methods **/
904
/* void onStartRequest (in nsIRequest request, in nsISupports ctxt); */
905
NS_IMETHODIMP imgCacheValidator::OnStartRequest(nsIRequest *aRequest, nsISupports *ctxt)
907
nsCOMPtr<nsICachingChannel> cacheChan(do_QueryInterface(aRequest));
910
if (NS_SUCCEEDED(cacheChan->IsFromCache(&isFromCache)) && isFromCache) {
913
mProxies.Count(&count);
914
for (PRInt32 i = count-1; i>=0; i--) {
915
imgRequestProxy *proxy;
916
mProxies.GetElementAt(i, (nsISupports**)&proxy);
917
mRequest->NotifyProxyListener(proxy);
921
mRequest->SetLoadId(mContext);
922
mRequest->mValidator = nsnull;
924
NS_RELEASE(mRequest); // assigns null
930
nsCOMPtr<nsIChannel> channel(do_QueryInterface(aRequest));
931
nsCOMPtr<nsICacheEntryDescriptor> entry;
932
nsCOMPtr<nsIURI> uri;
934
// Doom the old request's cache entry
935
mRequest->RemoveFromCache();
937
mRequest->GetURI(getter_AddRefs(uri));
939
mRequest->mValidator = nsnull;
940
NS_RELEASE(mRequest); // assigns null
943
nsCOMPtr<nsIEventQueueService> eventQService = do_GetService(NS_EVENTQUEUESERVICE_CONTRACTID, &rv);
944
if (NS_FAILED(rv)) return rv;
946
nsCOMPtr<nsIEventQueue> activeQ;
947
rv = eventQService->ResolveEventQueue(NS_CURRENT_EVENTQ, getter_AddRefs(activeQ));
948
if (NS_FAILED(rv)) return rv;
951
NS_NEWXPCOM(request, imgRequest);
952
if (!request) return NS_ERROR_OUT_OF_MEMORY;
955
imgCache::Put(uri, request, getter_AddRefs(entry));
957
request->Init(channel, entry, activeQ.get(), mContext);
959
ProxyListener *pl = new ProxyListener(NS_STATIC_CAST(nsIStreamListener *, request));
962
return NS_ERROR_OUT_OF_MEMORY;
965
mDestListener = NS_STATIC_CAST(nsIStreamListener*, pl);
968
mProxies.Count(&count);
969
for (PRInt32 i = count-1; i>=0; i--) {
970
imgRequestProxy *proxy;
971
mProxies.GetElementAt(i, (nsISupports**)&proxy);
972
proxy->ChangeOwner(request);
973
request->NotifyProxyListener(proxy);
982
return mDestListener->OnStartRequest(aRequest, ctxt);
985
/* void onStopRequest (in nsIRequest request, in nsISupports ctxt, in nsresult status); */
986
NS_IMETHODIMP imgCacheValidator::OnStopRequest(nsIRequest *aRequest, nsISupports *ctxt, nsresult status)
991
return mDestListener->OnStopRequest(aRequest, ctxt, status);
994
/** nsIStreamListener methods **/
997
// XXX see bug 113959
998
static NS_METHOD dispose_of_data(nsIInputStream* in, void* closure,
999
const char* fromRawSegment, PRUint32 toOffset,
1000
PRUint32 count, PRUint32 *writeCount)
1002
*writeCount = count;
1006
/* void onDataAvailable (in nsIRequest request, in nsISupports ctxt, in nsIInputStream inStr, in unsigned long sourceOffset, in unsigned long count); */
1007
NS_IMETHODIMP imgCacheValidator::OnDataAvailable(nsIRequest *aRequest, nsISupports *ctxt, nsIInputStream *inStr, PRUint32 sourceOffset, PRUint32 count)
1010
nsCOMPtr<nsICachingChannel> cacheChan(do_QueryInterface(aRequest));
1013
if (NS_SUCCEEDED(cacheChan->IsFromCache(&isFromCache)) && isFromCache)
1014
NS_ERROR("OnDataAvailable not suppressed by LOAD_ONLY_IF_MODIFIED load flag");
1018
if (!mDestListener) {
1019
// XXX see bug 113959
1021
inStr->ReadSegments(dispose_of_data, nsnull, count, &_retval);
1025
return mDestListener->OnDataAvailable(aRequest, ctxt, inStr, sourceOffset, count);