1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2  *
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 "mozilla/ArrayUtils.h"
8 #include "mozilla/BasePrincipal.h"
9 #include "mozilla/Monitor.h"
10 #include "mozilla/WindowsProcessMitigations.h"
11 
12 #include "nsComponentManagerUtils.h"
13 #include "nsIconChannel.h"
14 #include "nsIIconURI.h"
15 #include "nsIInterfaceRequestor.h"
16 #include "nsIInterfaceRequestorUtils.h"
17 #include "nsString.h"
18 #include "nsReadableUtils.h"
19 #include "nsMimeTypes.h"
20 #include "nsMemory.h"
21 #include "nsIURL.h"
22 #include "nsIPipe.h"
23 #include "nsNetCID.h"
24 #include "nsIFile.h"
25 #include "nsIFileURL.h"
26 #include "nsIInputStream.h"
27 #include "nsIMIMEService.h"
28 #include "nsCExternalHandlerService.h"
29 #include "nsDirectoryServiceDefs.h"
30 #include "nsProxyRelease.h"
31 #include "nsContentSecurityManager.h"
32 #include "nsContentUtils.h"
33 #include "nsNetUtil.h"
34 #include "nsThreadUtils.h"
35 
36 #include "Decoder.h"
37 #include "DecodePool.h"
38 
39 // we need windows.h to read out registry information...
40 #include <windows.h>
41 #include <shellapi.h>
42 #include <shlobj.h>
43 #include <objbase.h>
44 #include <wchar.h>
45 
46 using namespace mozilla;
47 using namespace mozilla::image;
48 
49 struct ICONFILEHEADER {
50   uint16_t ifhReserved;
51   uint16_t ifhType;
52   uint16_t ifhCount;
53 };
54 
55 struct ICONENTRY {
56   int8_t ieWidth;
57   int8_t ieHeight;
58   uint8_t ieColors;
59   uint8_t ieReserved;
60   uint16_t iePlanes;
61   uint16_t ieBitCount;
62   uint32_t ieSizeImage;
63   uint32_t ieFileOffset;
64 };
65 
66 // Match stock icons with names
GetStockIconIDForName(const nsACString & aStockName)67 static SHSTOCKICONID GetStockIconIDForName(const nsACString& aStockName) {
68   return aStockName.EqualsLiteral("uac-shield") ? SIID_SHIELD : SIID_INVALID;
69 }
70 
71 class nsIconChannel::IconAsyncOpenTask final : public Runnable {
72  public:
IconAsyncOpenTask(nsIconChannel * aChannel,nsIEventTarget * aTarget,nsCOMPtr<nsIFile> && aLocalFile,nsAutoString & aPath,UINT aInfoFlags)73   IconAsyncOpenTask(nsIconChannel* aChannel, nsIEventTarget* aTarget,
74                     nsCOMPtr<nsIFile>&& aLocalFile, nsAutoString& aPath,
75                     UINT aInfoFlags)
76       : Runnable("IconAsyncOpenTask"),
77         mChannel(aChannel),
78 
79         mTarget(aTarget),
80         mLocalFile(std::move(aLocalFile)),
81         mPath(aPath),
82         mInfoFlags(aInfoFlags) {}
83 
84   NS_IMETHOD Run() override;
85 
86  private:
87   RefPtr<nsIconChannel> mChannel;
88   nsCOMPtr<nsIEventTarget> mTarget;
89   nsCOMPtr<nsIFile> mLocalFile;
90   nsAutoString mPath;
91   UINT mInfoFlags;
92 };
93 
Run()94 NS_IMETHODIMP nsIconChannel::IconAsyncOpenTask::Run() {
95   HICON hIcon = nullptr;
96   nsresult rv =
97       mChannel->GetHIconFromFile(mLocalFile, mPath, mInfoFlags, &hIcon);
98   // Effectively give ownership of mChannel to the runnable so it get released
99   // on the main thread.
100   RefPtr<nsIconChannel> channel = mChannel.forget();
101   nsCOMPtr<nsIRunnable> task = NewRunnableMethod<HICON, nsresult>(
102       "nsIconChannel::FinishAsyncOpen", channel,
103       &nsIconChannel::FinishAsyncOpen, hIcon, rv);
104   mTarget->Dispatch(task.forget(), NS_DISPATCH_NORMAL);
105   return NS_OK;
106 }
107 
108 class nsIconChannel::IconSyncOpenTask final : public Runnable {
109  public:
IconSyncOpenTask(nsIconChannel * aChannel,nsIEventTarget * aTarget,nsCOMPtr<nsIFile> && aLocalFile,nsAutoString & aPath,UINT aInfoFlags)110   IconSyncOpenTask(nsIconChannel* aChannel, nsIEventTarget* aTarget,
111                    nsCOMPtr<nsIFile>&& aLocalFile, nsAutoString& aPath,
112                    UINT aInfoFlags)
113       : Runnable("IconSyncOpenTask"),
114         mMonitor("IconSyncOpenTask"),
115         mDone(false),
116         mChannel(aChannel),
117         mTarget(aTarget),
118         mLocalFile(std::move(aLocalFile)),
119         mPath(aPath),
120         mInfoFlags(aInfoFlags),
121         mHIcon(nullptr),
122         mRv(NS_OK) {}
123 
124   NS_IMETHOD Run() override;
125 
GetMonitor()126   Monitor& GetMonitor() { return mMonitor; }
Done() const127   bool Done() const {
128     mMonitor.AssertCurrentThreadOwns();
129     return mDone;
130   }
GetHIcon() const131   HICON GetHIcon() const {
132     mMonitor.AssertCurrentThreadOwns();
133     return mHIcon;
134   }
GetRv() const135   nsresult GetRv() const {
136     mMonitor.AssertCurrentThreadOwns();
137     return mRv;
138   }
139 
140  private:
141   Monitor mMonitor;
142   bool mDone;
143   // Parameters in
144   RefPtr<nsIconChannel> mChannel;
145   nsCOMPtr<nsIEventTarget> mTarget;
146   nsCOMPtr<nsIFile> mLocalFile;
147   nsAutoString mPath;
148   UINT mInfoFlags;
149   // Return values
150   HICON mHIcon;
151   nsresult mRv;
152 };
153 
154 NS_IMETHODIMP
Run()155 nsIconChannel::IconSyncOpenTask::Run() {
156   MonitorAutoLock lock(mMonitor);
157   mRv = mChannel->GetHIconFromFile(mLocalFile, mPath, mInfoFlags, &mHIcon);
158   mDone = true;
159   mMonitor.NotifyAll();
160   // Do this little dance because nsIconChannel multiple inherits from
161   // nsISupports.
162   nsCOMPtr<nsIChannel> channel = mChannel.forget();
163   NS_ProxyRelease("IconSyncOpenTask::mChannel", mTarget, channel.forget());
164   return NS_OK;
165 }
166 
167 // nsIconChannel methods
nsIconChannel()168 nsIconChannel::nsIconChannel() {}
169 
~nsIconChannel()170 nsIconChannel::~nsIconChannel() {
171   if (mLoadInfo) {
172     NS_ReleaseOnMainThread("nsIconChannel::mLoadInfo", mLoadInfo.forget());
173   }
174   if (mLoadGroup) {
175     NS_ReleaseOnMainThread("nsIconChannel::mLoadGroup", mLoadGroup.forget());
176   }
177 }
178 
NS_IMPL_ISUPPORTS(nsIconChannel,nsIChannel,nsIRequest,nsIRequestObserver,nsIStreamListener)179 NS_IMPL_ISUPPORTS(nsIconChannel, nsIChannel, nsIRequest, nsIRequestObserver,
180                   nsIStreamListener)
181 
182 nsresult nsIconChannel::Init(nsIURI* uri) {
183   NS_ASSERTION(uri, "no uri");
184   mUrl = uri;
185   mOriginalURI = uri;
186   nsresult rv;
187   mPump = do_CreateInstance(NS_INPUTSTREAMPUMP_CONTRACTID, &rv);
188   return rv;
189 }
190 
191 ////////////////////////////////////////////////////////////////////////////////
192 // nsIRequest methods:
193 
194 NS_IMETHODIMP
GetName(nsACString & result)195 nsIconChannel::GetName(nsACString& result) { return mUrl->GetSpec(result); }
196 
197 NS_IMETHODIMP
IsPending(bool * result)198 nsIconChannel::IsPending(bool* result) { return mPump->IsPending(result); }
199 
200 NS_IMETHODIMP
GetStatus(nsresult * status)201 nsIconChannel::GetStatus(nsresult* status) { return mPump->GetStatus(status); }
202 
203 NS_IMETHODIMP
Cancel(nsresult status)204 nsIconChannel::Cancel(nsresult status) {
205   mCanceled = true;
206   return mPump->Cancel(status);
207 }
208 
209 NS_IMETHODIMP
GetCanceled(bool * result)210 nsIconChannel::GetCanceled(bool* result) {
211   *result = mCanceled;
212   return NS_OK;
213 }
214 
215 NS_IMETHODIMP
Suspend(void)216 nsIconChannel::Suspend(void) { return mPump->Suspend(); }
217 
218 NS_IMETHODIMP
Resume(void)219 nsIconChannel::Resume(void) { return mPump->Resume(); }
220 NS_IMETHODIMP
GetLoadGroup(nsILoadGroup ** aLoadGroup)221 nsIconChannel::GetLoadGroup(nsILoadGroup** aLoadGroup) {
222   *aLoadGroup = mLoadGroup;
223   NS_IF_ADDREF(*aLoadGroup);
224   return NS_OK;
225 }
226 
227 NS_IMETHODIMP
SetLoadGroup(nsILoadGroup * aLoadGroup)228 nsIconChannel::SetLoadGroup(nsILoadGroup* aLoadGroup) {
229   mLoadGroup = aLoadGroup;
230   return NS_OK;
231 }
232 
233 NS_IMETHODIMP
GetLoadFlags(uint32_t * aLoadAttributes)234 nsIconChannel::GetLoadFlags(uint32_t* aLoadAttributes) {
235   return mPump->GetLoadFlags(aLoadAttributes);
236 }
237 
238 NS_IMETHODIMP
SetLoadFlags(uint32_t aLoadAttributes)239 nsIconChannel::SetLoadFlags(uint32_t aLoadAttributes) {
240   return mPump->SetLoadFlags(aLoadAttributes);
241 }
242 
243 NS_IMETHODIMP
GetTRRMode(nsIRequest::TRRMode * aTRRMode)244 nsIconChannel::GetTRRMode(nsIRequest::TRRMode* aTRRMode) {
245   return GetTRRModeImpl(aTRRMode);
246 }
247 
248 NS_IMETHODIMP
SetTRRMode(nsIRequest::TRRMode aTRRMode)249 nsIconChannel::SetTRRMode(nsIRequest::TRRMode aTRRMode) {
250   return SetTRRModeImpl(aTRRMode);
251 }
252 
253 NS_IMETHODIMP
GetIsDocument(bool * aIsDocument)254 nsIconChannel::GetIsDocument(bool* aIsDocument) {
255   return NS_GetIsDocumentChannel(this, aIsDocument);
256 }
257 
258 ////////////////////////////////////////////////////////////////////////////////
259 // nsIChannel methods:
260 
261 NS_IMETHODIMP
GetOriginalURI(nsIURI ** aURI)262 nsIconChannel::GetOriginalURI(nsIURI** aURI) {
263   *aURI = mOriginalURI;
264   NS_ADDREF(*aURI);
265   return NS_OK;
266 }
267 
268 NS_IMETHODIMP
SetOriginalURI(nsIURI * aURI)269 nsIconChannel::SetOriginalURI(nsIURI* aURI) {
270   NS_ENSURE_ARG_POINTER(aURI);
271   mOriginalURI = aURI;
272   return NS_OK;
273 }
274 
275 NS_IMETHODIMP
GetURI(nsIURI ** aURI)276 nsIconChannel::GetURI(nsIURI** aURI) {
277   *aURI = mUrl;
278   NS_IF_ADDREF(*aURI);
279   return NS_OK;
280 }
281 
282 NS_IMETHODIMP
Open(nsIInputStream ** aStream)283 nsIconChannel::Open(nsIInputStream** aStream) {
284   nsCOMPtr<nsIStreamListener> listener;
285   nsresult rv =
286       nsContentSecurityManager::doContentSecurityCheck(this, listener);
287   NS_ENSURE_SUCCESS(rv, rv);
288 
289   HICON hIcon = nullptr;
290   rv = GetHIcon(/* aNonBlocking */ false, &hIcon);
291   if (NS_FAILED(rv)) {
292     return rv;
293   }
294 
295   return MakeInputStream(aStream, /* aNonBlocking */ false, hIcon);
296 }
297 
ExtractIconInfoFromUrl(nsIFile ** aLocalFile,uint32_t * aDesiredImageSize,nsCString & aContentType,nsCString & aFileExtension)298 nsresult nsIconChannel::ExtractIconInfoFromUrl(nsIFile** aLocalFile,
299                                                uint32_t* aDesiredImageSize,
300                                                nsCString& aContentType,
301                                                nsCString& aFileExtension) {
302   nsresult rv = NS_OK;
303   nsCOMPtr<nsIMozIconURI> iconURI(do_QueryInterface(mUrl, &rv));
304   NS_ENSURE_SUCCESS(rv, rv);
305 
306   iconURI->GetImageSize(aDesiredImageSize);
307   iconURI->GetContentType(aContentType);
308   iconURI->GetFileExtension(aFileExtension);
309 
310   nsCOMPtr<nsIURL> url;
311   rv = iconURI->GetIconURL(getter_AddRefs(url));
312   if (NS_FAILED(rv) || !url) return NS_OK;
313 
314   nsCOMPtr<nsIFileURL> fileURL = do_QueryInterface(url, &rv);
315   if (NS_FAILED(rv) || !fileURL) return NS_OK;
316 
317   nsCOMPtr<nsIFile> file;
318   rv = fileURL->GetFile(getter_AddRefs(file));
319   if (NS_FAILED(rv) || !file) return NS_OK;
320 
321   return file->Clone(aLocalFile);
322 }
323 
OnAsyncError(nsresult aStatus)324 void nsIconChannel::OnAsyncError(nsresult aStatus) {
325   OnStartRequest(this);
326   OnStopRequest(this, aStatus);
327 }
328 
FinishAsyncOpen(HICON aIcon,nsresult aStatus)329 void nsIconChannel::FinishAsyncOpen(HICON aIcon, nsresult aStatus) {
330   MOZ_ASSERT(NS_IsMainThread());
331 
332   if (NS_FAILED(aStatus)) {
333     OnAsyncError(aStatus);
334     return;
335   }
336 
337   nsCOMPtr<nsIInputStream> inStream;
338   nsresult rv = MakeInputStream(getter_AddRefs(inStream),
339                                 /* aNonBlocking */ true, aIcon);
340   if (NS_FAILED(rv)) {
341     OnAsyncError(rv);
342     return;
343   }
344 
345   rv = mPump->Init(inStream, 0, 0, false, mListenerTarget);
346   if (NS_FAILED(rv)) {
347     OnAsyncError(rv);
348     return;
349   }
350 
351   rv = mPump->AsyncRead(this);
352   if (NS_FAILED(rv)) {
353     OnAsyncError(rv);
354   }
355 }
356 
357 NS_IMETHODIMP
AsyncOpen(nsIStreamListener * aListener)358 nsIconChannel::AsyncOpen(nsIStreamListener* aListener) {
359   nsCOMPtr<nsIStreamListener> listener = aListener;
360   nsresult rv =
361       nsContentSecurityManager::doContentSecurityCheck(this, listener);
362   if (NS_FAILED(rv)) {
363     mCallbacks = nullptr;
364     return rv;
365   }
366 
367   MOZ_ASSERT(
368       mLoadInfo->GetSecurityMode() == 0 ||
369           mLoadInfo->GetInitialSecurityCheckDone() ||
370           (mLoadInfo->GetSecurityMode() ==
371                nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_SEC_CONTEXT_IS_NULL &&
372            mLoadInfo->GetLoadingPrincipal() &&
373            mLoadInfo->GetLoadingPrincipal()->IsSystemPrincipal()),
374       "security flags in loadInfo but doContentSecurityCheck() not called");
375 
376   nsCOMPtr<nsIInputStream> inStream;
377   rv = EnsurePipeCreated(/* aIconSize */ 0, /* aNonBlocking */ true);
378   if (NS_FAILED(rv)) {
379     mCallbacks = nullptr;
380     return rv;
381   }
382 
383   mListenerTarget = nsContentUtils::GetEventTargetByLoadInfo(
384       mLoadInfo, mozilla::TaskCategory::Other);
385   if (!mListenerTarget) {
386     mListenerTarget = do_GetMainThread();
387   }
388 
389   // If we pass aNonBlocking as true, GetHIcon will always have dispatched
390   // upon success.
391   HICON hIcon = nullptr;
392   rv = GetHIcon(/* aNonBlocking */ true, &hIcon);
393   if (NS_FAILED(rv)) {
394     mCallbacks = nullptr;
395     mInputStream = nullptr;
396     mOutputStream = nullptr;
397     mListenerTarget = nullptr;
398     return rv;
399   }
400 
401   // We shouldn't have the icon yet if it is non-blocking.
402   MOZ_ASSERT(!hIcon);
403 
404   // Add ourself to the load group, if available
405   if (mLoadGroup) {
406     mLoadGroup->AddRequest(this, nullptr);
407   }
408 
409   // Store our real listener
410   mListener = aListener;
411   return NS_OK;
412 }
413 
GetSpecialFolderIcon(nsIFile * aFile,int aFolder,SHFILEINFOW * aSFI,UINT aInfoFlags)414 static DWORD GetSpecialFolderIcon(nsIFile* aFile, int aFolder,
415                                   SHFILEINFOW* aSFI, UINT aInfoFlags) {
416   DWORD shellResult = 0;
417 
418   if (!aFile) {
419     return shellResult;
420   }
421 
422   wchar_t fileNativePath[MAX_PATH];
423   nsAutoString fileNativePathStr;
424   aFile->GetPath(fileNativePathStr);
425   ::GetShortPathNameW(fileNativePathStr.get(), fileNativePath,
426                       ArrayLength(fileNativePath));
427 
428   LPITEMIDLIST idList;
429   HRESULT hr = ::SHGetSpecialFolderLocation(nullptr, aFolder, &idList);
430   if (SUCCEEDED(hr)) {
431     wchar_t specialNativePath[MAX_PATH];
432     ::SHGetPathFromIDListW(idList, specialNativePath);
433     ::GetShortPathNameW(specialNativePath, specialNativePath,
434                         ArrayLength(specialNativePath));
435 
436     if (!wcsicmp(fileNativePath, specialNativePath)) {
437       aInfoFlags |= (SHGFI_PIDL | SHGFI_SYSICONINDEX);
438       shellResult = ::SHGetFileInfoW((LPCWSTR)(LPCITEMIDLIST)idList, 0, aSFI,
439                                      sizeof(*aSFI), aInfoFlags);
440     }
441   }
442   CoTaskMemFree(idList);
443   return shellResult;
444 }
445 
GetSizeInfoFlag(uint32_t aDesiredImageSize)446 static UINT GetSizeInfoFlag(uint32_t aDesiredImageSize) {
447   return (UINT)(aDesiredImageSize > 16 ? SHGFI_SHELLICONSIZE : SHGFI_SMALLICON);
448 }
449 
GetHIconFromFile(bool aNonBlocking,HICON * hIcon)450 nsresult nsIconChannel::GetHIconFromFile(bool aNonBlocking, HICON* hIcon) {
451   if (IsWin32kLockedDown()) {
452     MOZ_DIAGNOSTIC_ASSERT(false,
453                           "GetHIconFromFile requires call to SHGetFileInfo, "
454                           "which cannot be used when win32k is disabled.");
455     return NS_ERROR_NOT_AVAILABLE;
456   }
457 
458   nsCString contentType;
459   nsCString fileExt;
460   nsCOMPtr<nsIFile> localFile;  // file we want an icon for
461   uint32_t desiredImageSize;
462   nsresult rv = ExtractIconInfoFromUrl(getter_AddRefs(localFile),
463                                        &desiredImageSize, contentType, fileExt);
464   NS_ENSURE_SUCCESS(rv, rv);
465 
466   // if the file exists, we are going to use it's real attributes...
467   // otherwise we only want to use it for it's extension...
468   UINT infoFlags = SHGFI_ICON;
469 
470   bool fileExists = false;
471 
472   nsAutoString filePath;
473   CopyASCIItoUTF16(fileExt, filePath);
474   if (localFile) {
475     rv = localFile->Normalize();
476     NS_ENSURE_SUCCESS(rv, rv);
477 
478     localFile->GetPath(filePath);
479     if (filePath.Length() < 2 || filePath[1] != ':') {
480       return NS_ERROR_MALFORMED_URI;  // UNC
481     }
482 
483     if (filePath.Last() == ':') {
484       filePath.Append('\\');
485     } else {
486       localFile->Exists(&fileExists);
487       if (!fileExists) {
488         localFile->GetLeafName(filePath);
489       }
490     }
491   }
492 
493   if (!fileExists) {
494     infoFlags |= SHGFI_USEFILEATTRIBUTES;
495   }
496 
497   infoFlags |= GetSizeInfoFlag(desiredImageSize);
498 
499   // if we have a content type... then use it! but for existing files,
500   // we want to show their real icon.
501   if (!fileExists && !contentType.IsEmpty()) {
502     nsCOMPtr<nsIMIMEService> mimeService(
503         do_GetService(NS_MIMESERVICE_CONTRACTID, &rv));
504     NS_ENSURE_SUCCESS(rv, rv);
505 
506     nsAutoCString defFileExt;
507     mimeService->GetPrimaryExtension(contentType, fileExt, defFileExt);
508     // If the mime service does not know about this mime type, we show
509     // the generic icon.
510     // In any case, we need to insert a '.' before the extension.
511     filePath = u"."_ns + NS_ConvertUTF8toUTF16(defFileExt);
512   }
513 
514   if (!localFile && !fileExists &&
515       ((filePath.Length() == 1 && filePath.Last() == '.') ||
516        filePath.Length() == 0)) {
517     filePath = u".MozBogusExtensionMoz"_ns;
518   }
519 
520   if (aNonBlocking) {
521     RefPtr<nsIEventTarget> target = DecodePool::Singleton()->GetIOEventTarget();
522     RefPtr<IconAsyncOpenTask> task = new IconAsyncOpenTask(
523         this, mListenerTarget, std::move(localFile), filePath, infoFlags);
524     target->Dispatch(task.forget(), NS_DISPATCH_NORMAL);
525     return NS_OK;
526   }
527 
528   // We cannot call SHGetFileInfo on more than one thread (at a time), so it
529   // must be called on the same thread every time, even now when we need sync
530   // behaviour. So we synchronously wait on the other thread to finish.
531   RefPtr<nsIEventTarget> target = DecodePool::Singleton()->GetIOEventTarget();
532   RefPtr<IconSyncOpenTask> task = new IconSyncOpenTask(
533       this, mListenerTarget, std::move(localFile), filePath, infoFlags);
534   MonitorAutoLock lock(task->GetMonitor());
535   target->Dispatch(task, NS_DISPATCH_NORMAL);
536   do {
537     task->GetMonitor().Wait();
538   } while (!task->Done());
539   *hIcon = task->GetHIcon();
540   return task->GetRv();
541 }
542 
GetHIconFromFile(nsIFile * aLocalFile,const nsAutoString & aPath,UINT aInfoFlags,HICON * hIcon)543 nsresult nsIconChannel::GetHIconFromFile(nsIFile* aLocalFile,
544                                          const nsAutoString& aPath,
545                                          UINT aInfoFlags, HICON* hIcon) {
546   SHFILEINFOW sfi;
547 
548   // Is this the "Desktop" folder?
549   DWORD shellResult =
550       GetSpecialFolderIcon(aLocalFile, CSIDL_DESKTOP, &sfi, aInfoFlags);
551   if (!shellResult) {
552     // Is this the "My Documents" folder?
553     shellResult =
554         GetSpecialFolderIcon(aLocalFile, CSIDL_PERSONAL, &sfi, aInfoFlags);
555   }
556 
557   // There are other "Special Folders" and Namespace entities that we
558   // are not fetching icons for, see:
559   // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/
560   //        shellcc/platform/shell/reference/enums/csidl.asp
561   // If we ever need to get them, code to do so would be inserted here.
562 
563   // Not a special folder, or something else failed above.
564   if (!shellResult) {
565     shellResult = ::SHGetFileInfoW(aPath.get(), FILE_ATTRIBUTE_ARCHIVE, &sfi,
566                                    sizeof(sfi), aInfoFlags);
567   }
568 
569   if (!shellResult || !sfi.hIcon) {
570     return NS_ERROR_NOT_AVAILABLE;
571   }
572 
573   *hIcon = sfi.hIcon;
574   return NS_OK;
575 }
576 
GetStockHIcon(nsIMozIconURI * aIconURI,HICON * hIcon)577 nsresult nsIconChannel::GetStockHIcon(nsIMozIconURI* aIconURI, HICON* hIcon) {
578   nsresult rv = NS_OK;
579 
580   uint32_t desiredImageSize;
581   aIconURI->GetImageSize(&desiredImageSize);
582   nsAutoCString stockIcon;
583   aIconURI->GetStockIcon(stockIcon);
584 
585   SHSTOCKICONID stockIconID = GetStockIconIDForName(stockIcon);
586   if (stockIconID == SIID_INVALID) {
587     return NS_ERROR_NOT_AVAILABLE;
588   }
589 
590   UINT infoFlags = SHGSI_ICON;
591   infoFlags |= GetSizeInfoFlag(desiredImageSize);
592 
593   SHSTOCKICONINFO sii = {0};
594   sii.cbSize = sizeof(sii);
595   HRESULT hr = SHGetStockIconInfo(stockIconID, infoFlags, &sii);
596 
597   if (SUCCEEDED(hr)) {
598     *hIcon = sii.hIcon;
599   } else {
600     rv = NS_ERROR_FAILURE;
601   }
602 
603   return rv;
604 }
605 
606 // Given a BITMAPINFOHEADER, returns the size of the color table.
GetColorTableSize(BITMAPINFOHEADER * aHeader)607 static int GetColorTableSize(BITMAPINFOHEADER* aHeader) {
608   int colorTableSize = -1;
609 
610   // http://msdn.microsoft.com/en-us/library/dd183376%28v=VS.85%29.aspx
611   switch (aHeader->biBitCount) {
612     case 0:
613       colorTableSize = 0;
614       break;
615     case 1:
616       colorTableSize = 2 * sizeof(RGBQUAD);
617       break;
618     case 4:
619     case 8: {
620       // The maximum possible size for the color table is 2**bpp, so check for
621       // that and fail if we're not in those bounds
622       unsigned int maxEntries = 1 << (aHeader->biBitCount);
623       if (aHeader->biClrUsed > 0 && aHeader->biClrUsed <= maxEntries) {
624         colorTableSize = aHeader->biClrUsed * sizeof(RGBQUAD);
625       } else if (aHeader->biClrUsed == 0) {
626         colorTableSize = maxEntries * sizeof(RGBQUAD);
627       }
628       break;
629     }
630     case 16:
631     case 32:
632       // If we have BI_BITFIELDS compression, we would normally need 3 DWORDS
633       // for the bitfields mask which would be stored in the color table;
634       // However, we instead force the bitmap to request data of type BI_RGB so
635       // the color table should be of size 0. Setting aHeader->biCompression =
636       // BI_RGB forces the later call to GetDIBits to return to us BI_RGB data.
637       if (aHeader->biCompression == BI_BITFIELDS) {
638         aHeader->biCompression = BI_RGB;
639       }
640       colorTableSize = 0;
641       break;
642     case 24:
643       colorTableSize = 0;
644       break;
645   }
646 
647   if (colorTableSize < 0) {
648     NS_WARNING("Unable to figure out the color table size for this bitmap");
649   }
650 
651   return colorTableSize;
652 }
653 
654 // Given a header and a size, creates a freshly allocated BITMAPINFO structure.
655 // It is the caller's responsibility to null-check and delete the structure.
CreateBitmapInfo(BITMAPINFOHEADER * aHeader,size_t aColorTableSize)656 static BITMAPINFO* CreateBitmapInfo(BITMAPINFOHEADER* aHeader,
657                                     size_t aColorTableSize) {
658   BITMAPINFO* bmi = (BITMAPINFO*)::operator new(
659       sizeof(BITMAPINFOHEADER) + aColorTableSize, mozilla::fallible);
660   if (bmi) {
661     memcpy(bmi, aHeader, sizeof(BITMAPINFOHEADER));
662     memset(bmi->bmiColors, 0, aColorTableSize);
663   }
664   return bmi;
665 }
666 
EnsurePipeCreated(uint32_t aIconSize,bool aNonBlocking)667 nsresult nsIconChannel::EnsurePipeCreated(uint32_t aIconSize,
668                                           bool aNonBlocking) {
669   if (mInputStream || mOutputStream) {
670     return NS_OK;
671   }
672 
673   return NS_NewPipe(getter_AddRefs(mInputStream), getter_AddRefs(mOutputStream),
674                     aIconSize, aIconSize > 0 ? aIconSize : UINT32_MAX,
675                     aNonBlocking);
676 }
677 
GetHIcon(bool aNonBlocking,HICON * aIcon)678 nsresult nsIconChannel::GetHIcon(bool aNonBlocking, HICON* aIcon) {
679   // Check whether the icon requested's a file icon or a stock icon
680   nsresult rv = NS_ERROR_NOT_AVAILABLE;
681 
682   // GetDIBits does not exist on windows mobile.
683   nsCOMPtr<nsIMozIconURI> iconURI(do_QueryInterface(mUrl, &rv));
684   NS_ENSURE_SUCCESS(rv, rv);
685 
686   nsAutoCString stockIcon;
687   iconURI->GetStockIcon(stockIcon);
688   if (!stockIcon.IsEmpty()) {
689     return GetStockHIcon(iconURI, aIcon);
690   }
691 
692   return GetHIconFromFile(aNonBlocking, aIcon);
693 }
694 
MakeInputStream(nsIInputStream ** _retval,bool aNonBlocking,HICON aIcon)695 nsresult nsIconChannel::MakeInputStream(nsIInputStream** _retval,
696                                         bool aNonBlocking, HICON aIcon) {
697   nsresult rv = NS_ERROR_FAILURE;
698 
699   if (aIcon) {
700     // we got a handle to an icon. Now we want to get a bitmap for the icon
701     // using GetIconInfo....
702     ICONINFO iconInfo;
703     if (GetIconInfo(aIcon, &iconInfo)) {
704       // we got the bitmaps, first find out their size
705       HDC hDC = CreateCompatibleDC(nullptr);  // get a device context for
706                                               // the screen.
707       BITMAPINFOHEADER maskHeader = {sizeof(BITMAPINFOHEADER)};
708       BITMAPINFOHEADER colorHeader = {sizeof(BITMAPINFOHEADER)};
709       int colorTableSize, maskTableSize;
710       if (GetDIBits(hDC, iconInfo.hbmMask, 0, 0, nullptr,
711                     (BITMAPINFO*)&maskHeader, DIB_RGB_COLORS) &&
712           GetDIBits(hDC, iconInfo.hbmColor, 0, 0, nullptr,
713                     (BITMAPINFO*)&colorHeader, DIB_RGB_COLORS) &&
714           maskHeader.biHeight == colorHeader.biHeight &&
715           maskHeader.biWidth == colorHeader.biWidth &&
716           colorHeader.biBitCount > 8 && colorHeader.biSizeImage > 0 &&
717           colorHeader.biWidth >= 0 && colorHeader.biWidth <= 255 &&
718           colorHeader.biHeight >= 0 && colorHeader.biHeight <= 255 &&
719           maskHeader.biSizeImage > 0 &&
720           (colorTableSize = GetColorTableSize(&colorHeader)) >= 0 &&
721           (maskTableSize = GetColorTableSize(&maskHeader)) >= 0) {
722         uint32_t iconSize = sizeof(ICONFILEHEADER) + sizeof(ICONENTRY) +
723                             sizeof(BITMAPINFOHEADER) + colorHeader.biSizeImage +
724                             maskHeader.biSizeImage;
725 
726         UniquePtr<char[]> buffer = MakeUnique<char[]>(iconSize);
727         if (!buffer) {
728           rv = NS_ERROR_OUT_OF_MEMORY;
729         } else {
730           char* whereTo = buffer.get();
731           int howMuch;
732 
733           // the data starts with an icon file header
734           ICONFILEHEADER iconHeader;
735           iconHeader.ifhReserved = 0;
736           iconHeader.ifhType = 1;
737           iconHeader.ifhCount = 1;
738           howMuch = sizeof(ICONFILEHEADER);
739           memcpy(whereTo, &iconHeader, howMuch);
740           whereTo += howMuch;
741 
742           // followed by the single icon entry
743           ICONENTRY iconEntry;
744           iconEntry.ieWidth = static_cast<int8_t>(colorHeader.biWidth);
745           iconEntry.ieHeight = static_cast<int8_t>(colorHeader.biHeight);
746           iconEntry.ieColors = 0;
747           iconEntry.ieReserved = 0;
748           iconEntry.iePlanes = 1;
749           iconEntry.ieBitCount = colorHeader.biBitCount;
750           iconEntry.ieSizeImage = sizeof(BITMAPINFOHEADER) +
751                                   colorHeader.biSizeImage +
752                                   maskHeader.biSizeImage;
753           iconEntry.ieFileOffset = sizeof(ICONFILEHEADER) + sizeof(ICONENTRY);
754           howMuch = sizeof(ICONENTRY);
755           memcpy(whereTo, &iconEntry, howMuch);
756           whereTo += howMuch;
757 
758           // followed by the bitmap info header
759           // (doubling the height because icons have two bitmaps)
760           colorHeader.biHeight *= 2;
761           colorHeader.biSizeImage += maskHeader.biSizeImage;
762           howMuch = sizeof(BITMAPINFOHEADER);
763           memcpy(whereTo, &colorHeader, howMuch);
764           whereTo += howMuch;
765           colorHeader.biHeight /= 2;
766           colorHeader.biSizeImage -= maskHeader.biSizeImage;
767 
768           // followed by the XOR bitmap data (colorHeader)
769           // (you'd expect the color table to come here, but it apparently
770           // doesn't)
771           BITMAPINFO* colorInfo =
772               CreateBitmapInfo(&colorHeader, colorTableSize);
773           if (colorInfo &&
774               GetDIBits(hDC, iconInfo.hbmColor, 0, colorHeader.biHeight,
775                         whereTo, colorInfo, DIB_RGB_COLORS)) {
776             whereTo += colorHeader.biSizeImage;
777 
778             // and finally the AND bitmap data (maskHeader)
779             BITMAPINFO* maskInfo = CreateBitmapInfo(&maskHeader, maskTableSize);
780             if (maskInfo &&
781                 GetDIBits(hDC, iconInfo.hbmMask, 0, maskHeader.biHeight,
782                           whereTo, maskInfo, DIB_RGB_COLORS)) {
783               // Now, create a pipe and stuff our data into it
784               rv = EnsurePipeCreated(iconSize, aNonBlocking);
785               if (NS_SUCCEEDED(rv)) {
786                 uint32_t written;
787                 rv = mOutputStream->Write(buffer.get(), iconSize, &written);
788                 if (NS_SUCCEEDED(rv)) {
789                   NS_ADDREF(*_retval = mInputStream);
790                 }
791               }
792 
793             }  // if we got bitmap bits
794             delete maskInfo;
795           }  // if we got mask bits
796           delete colorInfo;
797         }  // if we allocated the buffer
798       }    // if we got mask size
799 
800       DeleteDC(hDC);
801       DeleteObject(iconInfo.hbmColor);
802       DeleteObject(iconInfo.hbmMask);
803     }  // if we got icon info
804     DestroyIcon(aIcon);
805   }  // if we got an hIcon
806 
807   // If we didn't make a stream, then fail.
808   if (!*_retval && NS_SUCCEEDED(rv)) {
809     rv = NS_ERROR_NOT_AVAILABLE;
810   }
811 
812   mInputStream = nullptr;
813   mOutputStream = nullptr;
814   return rv;
815 }
816 
817 NS_IMETHODIMP
GetContentType(nsACString & aContentType)818 nsIconChannel::GetContentType(nsACString& aContentType) {
819   aContentType.AssignLiteral(IMAGE_ICO);
820   return NS_OK;
821 }
822 
823 NS_IMETHODIMP
SetContentType(const nsACString & aContentType)824 nsIconChannel::SetContentType(const nsACString& aContentType) {
825   // It doesn't make sense to set the content-type on this type
826   // of channel...
827   return NS_ERROR_FAILURE;
828 }
829 
GetContentCharset(nsACString & aContentCharset)830 NS_IMETHODIMP nsIconChannel::GetContentCharset(nsACString& aContentCharset) {
831   aContentCharset.Truncate();
832   return NS_OK;
833 }
834 
835 NS_IMETHODIMP
SetContentCharset(const nsACString & aContentCharset)836 nsIconChannel::SetContentCharset(const nsACString& aContentCharset) {
837   // It doesn't make sense to set the content-charset on this type
838   // of channel...
839   return NS_ERROR_FAILURE;
840 }
841 
842 NS_IMETHODIMP
GetContentDisposition(uint32_t * aContentDisposition)843 nsIconChannel::GetContentDisposition(uint32_t* aContentDisposition) {
844   return NS_ERROR_NOT_AVAILABLE;
845 }
846 
847 NS_IMETHODIMP
SetContentDisposition(uint32_t aContentDisposition)848 nsIconChannel::SetContentDisposition(uint32_t aContentDisposition) {
849   return NS_ERROR_NOT_AVAILABLE;
850 }
851 
852 NS_IMETHODIMP
GetContentDispositionFilename(nsAString & aContentDispositionFilename)853 nsIconChannel::GetContentDispositionFilename(
854     nsAString& aContentDispositionFilename) {
855   return NS_ERROR_NOT_AVAILABLE;
856 }
857 
858 NS_IMETHODIMP
SetContentDispositionFilename(const nsAString & aContentDispositionFilename)859 nsIconChannel::SetContentDispositionFilename(
860     const nsAString& aContentDispositionFilename) {
861   return NS_ERROR_NOT_AVAILABLE;
862 }
863 
864 NS_IMETHODIMP
GetContentDispositionHeader(nsACString & aContentDispositionHeader)865 nsIconChannel::GetContentDispositionHeader(
866     nsACString& aContentDispositionHeader) {
867   return NS_ERROR_NOT_AVAILABLE;
868 }
869 
870 NS_IMETHODIMP
GetContentLength(int64_t * aContentLength)871 nsIconChannel::GetContentLength(int64_t* aContentLength) {
872   *aContentLength = 0;
873   return NS_ERROR_FAILURE;
874 }
875 
876 NS_IMETHODIMP
SetContentLength(int64_t aContentLength)877 nsIconChannel::SetContentLength(int64_t aContentLength) {
878   MOZ_ASSERT_UNREACHABLE("nsIconChannel::SetContentLength");
879   return NS_ERROR_NOT_IMPLEMENTED;
880 }
881 
882 NS_IMETHODIMP
GetOwner(nsISupports ** aOwner)883 nsIconChannel::GetOwner(nsISupports** aOwner) {
884   *aOwner = mOwner.get();
885   NS_IF_ADDREF(*aOwner);
886   return NS_OK;
887 }
888 
889 NS_IMETHODIMP
SetOwner(nsISupports * aOwner)890 nsIconChannel::SetOwner(nsISupports* aOwner) {
891   mOwner = aOwner;
892   return NS_OK;
893 }
894 
895 NS_IMETHODIMP
GetLoadInfo(nsILoadInfo ** aLoadInfo)896 nsIconChannel::GetLoadInfo(nsILoadInfo** aLoadInfo) {
897   NS_IF_ADDREF(*aLoadInfo = mLoadInfo);
898   return NS_OK;
899 }
900 
901 NS_IMETHODIMP
SetLoadInfo(nsILoadInfo * aLoadInfo)902 nsIconChannel::SetLoadInfo(nsILoadInfo* aLoadInfo) {
903   MOZ_RELEASE_ASSERT(aLoadInfo, "loadinfo can't be null");
904   mLoadInfo = aLoadInfo;
905   return NS_OK;
906 }
907 
908 NS_IMETHODIMP
GetNotificationCallbacks(nsIInterfaceRequestor ** aNotificationCallbacks)909 nsIconChannel::GetNotificationCallbacks(
910     nsIInterfaceRequestor** aNotificationCallbacks) {
911   *aNotificationCallbacks = mCallbacks.get();
912   NS_IF_ADDREF(*aNotificationCallbacks);
913   return NS_OK;
914 }
915 
916 NS_IMETHODIMP
SetNotificationCallbacks(nsIInterfaceRequestor * aNotificationCallbacks)917 nsIconChannel::SetNotificationCallbacks(
918     nsIInterfaceRequestor* aNotificationCallbacks) {
919   mCallbacks = aNotificationCallbacks;
920   return NS_OK;
921 }
922 
923 NS_IMETHODIMP
GetSecurityInfo(nsISupports ** aSecurityInfo)924 nsIconChannel::GetSecurityInfo(nsISupports** aSecurityInfo) {
925   *aSecurityInfo = nullptr;
926   return NS_OK;
927 }
928 
929 // nsIRequestObserver methods
OnStartRequest(nsIRequest * aRequest)930 NS_IMETHODIMP nsIconChannel::OnStartRequest(nsIRequest* aRequest) {
931   if (mListener) {
932     return mListener->OnStartRequest(this);
933   }
934   return NS_OK;
935 }
936 
937 NS_IMETHODIMP
OnStopRequest(nsIRequest * aRequest,nsresult aStatus)938 nsIconChannel::OnStopRequest(nsIRequest* aRequest, nsresult aStatus) {
939   if (mListener) {
940     mListener->OnStopRequest(this, aStatus);
941     mListener = nullptr;
942   }
943 
944   // Remove from load group
945   if (mLoadGroup) {
946     mLoadGroup->RemoveRequest(this, nullptr, aStatus);
947   }
948 
949   // Drop notification callbacks to prevent cycles.
950   mCallbacks = nullptr;
951   mListenerTarget = nullptr;
952 
953   return NS_OK;
954 }
955 
956 // nsIStreamListener methods
957 NS_IMETHODIMP
OnDataAvailable(nsIRequest * aRequest,nsIInputStream * aStream,uint64_t aOffset,uint32_t aCount)958 nsIconChannel::OnDataAvailable(nsIRequest* aRequest, nsIInputStream* aStream,
959                                uint64_t aOffset, uint32_t aCount) {
960   if (mListener) {
961     return mListener->OnDataAvailable(this, aStream, aOffset, aCount);
962   }
963   return NS_OK;
964 }
965