30aa4a2f3c1b41d68c6faf0bb4af06043660f8e8
[reactos.git] / base / applications / rapps / loaddlg.cpp
1 /*
2 * PROJECT: ReactOS Applications Manager
3 * LICENSE: GPL-2.0+ (https://spdx.org/licenses/GPL-2.0+)
4 * FILE: base/applications/rapps/loaddlg.cpp
5 * PURPOSE: Displaying a download dialog
6 * COPYRIGHT: Copyright 2001 John R. Sheets (for CodeWeavers)
7 * Copyright 2004 Mike McCormack (for CodeWeavers)
8 * Copyright 2005 Ge van Geldorp (gvg@reactos.org)
9 * Copyright 2009 Dmitry Chapyshev (dmitry@reactos.org)
10 * Copyright 2015 Ismael Ferreras Morezuelas (swyterzone+ros@gmail.com)
11 * Copyright 2017 Alexander Shaposhnikov (sanchaez@reactos.org)
12 */
13
14 /*
15 * Based on Wine dlls/shdocvw/shdocvw_main.c
16 *
17 * This library is free software; you can redistribute it and/or
18 * modify it under the terms of the GNU Lesser General Public
19 * License as published by the Free Software Foundation; either
20 * version 2.1 of the License, or (at your option) any later version.
21 *
22 * This library is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
25 * Lesser General Public License for more details.
26 *
27 * You should have received a copy of the GNU Lesser General Public
28 * License along with this library; if not, write to the Free Software
29 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
30 */
31 #include "rapps.h"
32
33 #include <shlobj_undoc.h>
34 #include <shlguid_undoc.h>
35
36 #include <atlbase.h>
37 #include <atlcom.h>
38 #include <atlwin.h>
39 #include <wininet.h>
40 #include <shellutils.h>
41
42 #include <rosctrls.h>
43 #include <windowsx.h>
44
45 #include "rosui.h"
46 #include "dialogs.h"
47 #include "misc.h"
48
49 #ifdef USE_CERT_PINNING
50 #define CERT_ISSUER_INFO "US\r\nLet's Encrypt\r\nLet's Encrypt Authority X3"
51 #define CERT_SUBJECT_INFO "svn.reactos.org"
52 #endif
53
54 enum DownloadStatus
55 {
56 DLSTATUS_WAITING = IDS_STATUS_WAITING,
57 DLSTATUS_DOWNLOADING = IDS_STATUS_DOWNLOADING,
58 DLSTATUS_WAITING_INSTALL = IDS_STATUS_DOWNLOADED,
59 DLSTATUS_INSTALLING = IDS_STATUS_INSTALLING,
60 DLSTATUS_INSTALLED = IDS_STATUS_INSTALLED,
61 DLSTATUS_FINISHED = IDS_STATUS_FINISHED
62 };
63
64 ATL::CStringW LoadStatusString(DownloadStatus StatusParam)
65 {
66 ATL::CStringW szString;
67 szString.LoadStringW(StatusParam);
68 return szString;
69 }
70
71 struct DownloadInfo
72 {
73 DownloadInfo() {}
74 DownloadInfo(const CAvailableApplicationInfo& AppInfo)
75 :szUrl(AppInfo.m_szUrlDownload), szName(AppInfo.m_szName), szSHA1(AppInfo.m_szSHA1)
76 {
77 }
78
79 ATL::CStringW szUrl;
80 ATL::CStringW szName;
81 ATL::CStringW szSHA1;
82 };
83
84 struct DownloadParam
85 {
86 DownloadParam() : Dialog(NULL), AppInfo(), szCaption(NULL) {}
87 DownloadParam(HWND dlg, const ATL::CSimpleArray<DownloadInfo> &info, LPCWSTR caption)
88 : Dialog(dlg), AppInfo(info), szCaption(caption)
89 {
90 }
91
92 HWND Dialog;
93 ATL::CSimpleArray<DownloadInfo> AppInfo;
94 LPCWSTR szCaption;
95 };
96
97
98 class CDownloadDialog :
99 public CComObjectRootEx<CComMultiThreadModelNoCS>,
100 public IBindStatusCallback
101 {
102 HWND m_hDialog;
103 PBOOL m_pbCancelled;
104 BOOL m_UrlHasBeenCopied;
105
106 public:
107 ~CDownloadDialog()
108 {
109 //DestroyWindow(m_hDialog);
110 }
111
112 HRESULT Initialize(HWND Dlg, BOOL *pbCancelled)
113 {
114 m_hDialog = Dlg;
115 m_pbCancelled = pbCancelled;
116 m_UrlHasBeenCopied = FALSE;
117 return S_OK;
118 }
119
120 virtual HRESULT STDMETHODCALLTYPE OnStartBinding(
121 DWORD dwReserved,
122 IBinding *pib)
123 {
124 return S_OK;
125 }
126
127 virtual HRESULT STDMETHODCALLTYPE GetPriority(
128 LONG *pnPriority)
129 {
130 return S_OK;
131 }
132
133 virtual HRESULT STDMETHODCALLTYPE OnLowResource(
134 DWORD reserved)
135 {
136 return S_OK;
137 }
138
139 virtual HRESULT STDMETHODCALLTYPE OnProgress(
140 ULONG ulProgress,
141 ULONG ulProgressMax,
142 ULONG ulStatusCode,
143 LPCWSTR szStatusText)
144 {
145 HWND Item;
146 LONG r;
147
148 Item = GetDlgItem(m_hDialog, IDC_DOWNLOAD_PROGRESS);
149 if (Item)
150 {
151 WCHAR szProgress[100];
152
153 /* format the bits and bytes into pretty and accessible units... */
154 StrFormatByteSizeW(ulProgress, szProgress, _countof(szProgress));
155
156 /* use our subclassed progress bar text subroutine */
157 ATL::CStringW m_ProgressText;
158
159 if (ulProgressMax)
160 {
161 /* total size is known */
162 WCHAR szProgressMax[100];
163 UINT uiPercentage = ((ULONGLONG) ulProgress * 100) / ulProgressMax;
164
165 /* send the current progress to the progress bar */
166 SendMessageW(Item, PBM_SETPOS, uiPercentage, 0);
167
168 /* format total download size */
169 StrFormatByteSizeW(ulProgressMax, szProgressMax, _countof(szProgressMax));
170
171 /* generate the text on progress bar */
172 m_ProgressText.Format(L"%u%% \x2014 %ls / %ls",
173 uiPercentage,
174 szProgress,
175 szProgressMax);
176 }
177 else
178 {
179 /* send the current progress to the progress bar */
180 SendMessageW(Item, PBM_SETPOS, 0, 0);
181
182 /* total size is not known, display only current size */
183 m_ProgressText.Format(L"%ls...",
184 szProgress);
185 }
186 /* and finally display it */
187 SendMessageW(Item, WM_SETTEXT, 0, (LPARAM) m_ProgressText.GetString());
188 }
189
190 Item = GetDlgItem(m_hDialog, IDC_DOWNLOAD_STATUS);
191 if (Item && szStatusText && wcslen(szStatusText) > 0 && m_UrlHasBeenCopied == FALSE)
192 {
193 DWORD len = wcslen(szStatusText) + 1;
194 ATL::CStringW buf;
195
196 /* beautify our url for display purposes */
197 if (!InternetCanonicalizeUrlW(szStatusText, buf.GetBuffer(len), &len, ICU_DECODE | ICU_NO_ENCODE))
198 {
199 /* just use the original */
200 buf.ReleaseBuffer();
201 buf = szStatusText;
202 }
203 else
204 {
205 buf.ReleaseBuffer();
206 }
207
208 /* paste it into our dialog and don't do it again in this instance */
209 SendMessageW(Item, WM_SETTEXT, 0, (LPARAM) buf.GetString());
210 m_UrlHasBeenCopied = TRUE;
211 }
212
213 SetLastError(ERROR_SUCCESS);
214 r = GetWindowLongPtrW(m_hDialog, GWLP_USERDATA);
215 if (r || GetLastError() != ERROR_SUCCESS)
216 {
217 *m_pbCancelled = TRUE;
218 return E_ABORT;
219 }
220
221 return S_OK;
222 }
223
224 virtual HRESULT STDMETHODCALLTYPE OnStopBinding(
225 HRESULT hresult,
226 LPCWSTR szError)
227 {
228 return S_OK;
229 }
230
231 virtual HRESULT STDMETHODCALLTYPE GetBindInfo(
232 DWORD *grfBINDF,
233 BINDINFO *pbindinfo)
234 {
235 return S_OK;
236 }
237
238 virtual HRESULT STDMETHODCALLTYPE OnDataAvailable(
239 DWORD grfBSCF,
240 DWORD dwSize,
241 FORMATETC *pformatetc,
242 STGMEDIUM *pstgmed)
243 {
244 return S_OK;
245 }
246
247 virtual HRESULT STDMETHODCALLTYPE OnObjectAvailable(
248 REFIID riid,
249 IUnknown *punk)
250 {
251 return S_OK;
252 }
253
254 BEGIN_COM_MAP(CDownloadDialog)
255 COM_INTERFACE_ENTRY_IID(IID_IBindStatusCallback, IBindStatusCallback)
256 END_COM_MAP()
257 };
258
259 class CDowloadingAppsListView
260 : public CUiWindow<CListView>
261 {
262 public:
263 HWND Create(HWND hwndParent)
264 {
265 RECT r = {10, 150, 320, 350};
266 const DWORD style = WS_CHILD | WS_VISIBLE | LVS_REPORT | LVS_SINGLESEL
267 | LVS_SHOWSELALWAYS | LVS_NOSORTHEADER | LVS_NOCOLUMNHEADER;
268
269 HWND hwnd = CListView::Create(hwndParent, r, NULL, style, WS_EX_CLIENTEDGE);
270
271 AddColumn(0, 150, LVCFMT_LEFT);
272 AddColumn(1, 120, LVCFMT_LEFT);
273
274 return hwnd;
275 }
276
277 VOID LoadList(ATL::CSimpleArray<DownloadInfo> arrInfo)
278 {
279 for (INT i = 0; i < arrInfo.GetSize(); ++i)
280 {
281 AddRow(i, arrInfo[i].szName.GetString(), DLSTATUS_WAITING);
282 }
283 }
284
285 VOID SetDownloadStatus(INT ItemIndex, DownloadStatus Status)
286 {
287 HWND hListView = GetWindow();
288 ATL::CStringW szBuffer = LoadStatusString(Status);
289 ListView_SetItemText(hListView, ItemIndex, 1, const_cast<LPWSTR>(szBuffer.GetString()));
290 }
291
292 BOOL AddItem(INT ItemIndex, LPWSTR lpText)
293 {
294 LVITEMW Item;
295
296 ZeroMemory(&Item, sizeof(Item));
297
298 Item.mask = LVIF_TEXT | LVIF_STATE;
299 Item.pszText = lpText;
300 Item.iItem = ItemIndex;
301
302 return InsertItem(&Item);
303 }
304
305 VOID AddRow(INT RowIndex, LPCWSTR szAppName, const DownloadStatus Status)
306 {
307 ATL::CStringW szStatus = LoadStatusString(Status);
308 AddItem(RowIndex,
309 const_cast<LPWSTR>(szAppName));
310 SetDownloadStatus(RowIndex, Status);
311 }
312
313 BOOL AddColumn(INT Index, INT Width, INT Format)
314 {
315 LVCOLUMNW Column;
316 ZeroMemory(&Column, sizeof(Column));
317
318 Column.mask = LVCF_FMT | LVCF_WIDTH | LVCF_SUBITEM;
319 Column.iSubItem = Index;
320 Column.cx = Width;
321 Column.fmt = Format;
322
323 return (InsertColumn(Index, &Column) == -1) ? FALSE : TRUE;
324 }
325 };
326
327 extern "C"
328 HRESULT WINAPI CDownloadDialog_Constructor(HWND Dlg, BOOL *pbCancelled, REFIID riid, LPVOID *ppv)
329 {
330 return ShellObjectCreatorInit<CDownloadDialog>(Dlg, pbCancelled, riid, ppv);
331 }
332
333 #ifdef USE_CERT_PINNING
334 typedef CHeapPtr<char, CLocalAllocator> CLocalPtr;
335
336 static BOOL CertGetSubjectAndIssuer(HINTERNET hFile, CLocalPtr& subjectInfo, CLocalPtr& issuerInfo)
337 {
338 DWORD certInfoLength;
339 INTERNET_CERTIFICATE_INFOA certInfo;
340 DWORD size, flags;
341
342 size = sizeof(flags);
343 if (!InternetQueryOptionA(hFile, INTERNET_OPTION_SECURITY_FLAGS, &flags, &size))
344 {
345 return FALSE;
346 }
347
348 if (!flags & SECURITY_FLAG_SECURE)
349 {
350 return FALSE;
351 }
352
353 /* Despite what the header indicates, the implementation of INTERNET_CERTIFICATE_INFO is not Unicode-aware. */
354 certInfoLength = sizeof(certInfo);
355 if (!InternetQueryOptionA(hFile,
356 INTERNET_OPTION_SECURITY_CERTIFICATE_STRUCT,
357 &certInfo,
358 &certInfoLength))
359 {
360 return FALSE;
361 }
362
363 subjectInfo.Attach(certInfo.lpszSubjectInfo);
364 issuerInfo.Attach(certInfo.lpszIssuerInfo);
365
366 if (certInfo.lpszProtocolName)
367 LocalFree(certInfo.lpszProtocolName);
368 if (certInfo.lpszSignatureAlgName)
369 LocalFree(certInfo.lpszSignatureAlgName);
370 if (certInfo.lpszEncryptionAlgName)
371 LocalFree(certInfo.lpszEncryptionAlgName);
372
373 return certInfo.lpszSubjectInfo && certInfo.lpszIssuerInfo;
374 }
375 #endif
376
377 inline VOID MessageBox_LoadString(HWND hMainWnd, INT StringID)
378 {
379 ATL::CStringW szMsgText;
380 if (szMsgText.LoadStringW(StringID))
381 {
382 MessageBoxW(hMainWnd, szMsgText.GetString(), NULL, MB_OK | MB_ICONERROR);
383 }
384 }
385
386 // CDownloadManager
387 ATL::CSimpleArray<DownloadInfo> CDownloadManager::AppsToInstallList;
388 CDowloadingAppsListView CDownloadManager::DownloadsListView;
389
390 VOID CDownloadManager::Download(const DownloadInfo &DLInfo, BOOL bIsModal)
391 {
392 AppsToInstallList.RemoveAll();
393 AppsToInstallList.Add(DLInfo);
394 LaunchDownloadDialog(bIsModal);
395 }
396
397 INT_PTR CALLBACK CDownloadManager::DownloadDlgProc(HWND Dlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
398 {
399 static WCHAR szCaption[MAX_PATH];
400
401 switch (uMsg)
402 {
403 case WM_INITDIALOG:
404 {
405 HICON hIconSm, hIconBg;
406 ATL::CStringW szTempCaption;
407
408 hIconBg = (HICON) GetClassLongW(hMainWnd, GCLP_HICON);
409 hIconSm = (HICON) GetClassLongW(hMainWnd, GCLP_HICONSM);
410
411 if (hIconBg && hIconSm)
412 {
413 SendMessageW(Dlg, WM_SETICON, ICON_BIG, (LPARAM) hIconBg);
414 SendMessageW(Dlg, WM_SETICON, ICON_SMALL, (LPARAM) hIconSm);
415 }
416
417 SetWindowLongW(Dlg, GWLP_USERDATA, 0);
418 HWND Item = GetDlgItem(Dlg, IDC_DOWNLOAD_PROGRESS);
419 if (Item)
420 {
421 // initialize the default values for our nifty progress bar
422 // and subclass it so that it learns to print a status text
423 SendMessageW(Item, PBM_SETRANGE, 0, MAKELPARAM(0, 100));
424 SendMessageW(Item, PBM_SETPOS, 0, 0);
425
426 SetWindowSubclass(Item, DownloadProgressProc, 0, 0);
427 }
428
429 // Add a ListView
430 HWND hListView = DownloadsListView.Create(Dlg);
431 if (!hListView)
432 {
433 return FALSE;
434 }
435 DownloadsListView.LoadList(AppsToInstallList);
436
437 // Get a dlg string for later use
438 GetWindowTextW(Dlg, szCaption, _countof(szCaption));
439
440 // Hide a placeholder from displaying
441 szTempCaption = szCaption;
442 szTempCaption.Replace(L"%ls", L"");
443 SetWindowText(Dlg, szTempCaption.GetString());
444
445 ShowWindow(Dlg, SW_SHOW);
446
447 // Start download process
448 DownloadParam *param = new DownloadParam(Dlg, AppsToInstallList, szCaption);
449 DWORD ThreadId;
450 HANDLE Thread = CreateThread(NULL, 0, ThreadFunc, (LPVOID) param, 0, &ThreadId);
451
452 if (!Thread)
453 {
454 return FALSE;
455 }
456
457 CloseHandle(Thread);
458 AppsToInstallList.RemoveAll();
459 return TRUE;
460 }
461
462 case WM_COMMAND:
463 if (wParam == IDCANCEL)
464 {
465 SetWindowLongW(Dlg, GWLP_USERDATA, 1);
466 PostMessageW(Dlg, WM_CLOSE, 0, 0);
467 }
468 return FALSE;
469
470 case WM_CLOSE:
471 EndDialog(Dlg, 0);
472 //DestroyWindow(Dlg);
473 return TRUE;
474
475 default:
476 return FALSE;
477 }
478 }
479
480 LRESULT CALLBACK CDownloadManager::DownloadProgressProc(HWND hWnd,
481 UINT uMsg,
482 WPARAM wParam,
483 LPARAM lParam,
484 UINT_PTR uIdSubclass,
485 DWORD_PTR dwRefData)
486 {
487 static ATL::CStringW szProgressText;
488
489 switch (uMsg)
490 {
491 case WM_SETTEXT:
492 {
493 if (lParam)
494 {
495 szProgressText = (PCWSTR) lParam;
496 }
497 return TRUE;
498 }
499
500 case WM_ERASEBKGND:
501 case WM_PAINT:
502 {
503 PAINTSTRUCT ps;
504 HDC hDC = BeginPaint(hWnd, &ps), hdcMem;
505 HBITMAP hbmMem;
506 HANDLE hOld;
507 RECT myRect;
508 UINT win_width, win_height;
509
510 GetClientRect(hWnd, &myRect);
511
512 /* grab the progress bar rect size */
513 win_width = myRect.right - myRect.left;
514 win_height = myRect.bottom - myRect.top;
515
516 /* create an off-screen DC for double-buffering */
517 hdcMem = CreateCompatibleDC(hDC);
518 hbmMem = CreateCompatibleBitmap(hDC, win_width, win_height);
519
520 hOld = SelectObject(hdcMem, hbmMem);
521
522 /* call the original draw code and redirect it to our memory buffer */
523 DefSubclassProc(hWnd, uMsg, (WPARAM) hdcMem, lParam);
524
525 /* draw our nifty progress text over it */
526 SelectFont(hdcMem, GetStockFont(DEFAULT_GUI_FONT));
527 DrawShadowText(hdcMem, szProgressText.GetString(), szProgressText.GetLength(),
528 &myRect,
529 DT_CENTER | DT_VCENTER | DT_NOPREFIX | DT_SINGLELINE,
530 GetSysColor(COLOR_CAPTIONTEXT),
531 GetSysColor(COLOR_3DSHADOW),
532 1, 1);
533
534 /* transfer the off-screen DC to the screen */
535 BitBlt(hDC, 0, 0, win_width, win_height, hdcMem, 0, 0, SRCCOPY);
536
537 /* free the off-screen DC */
538 SelectObject(hdcMem, hOld);
539 DeleteObject(hbmMem);
540 DeleteDC(hdcMem);
541
542 EndPaint(hWnd, &ps);
543 return 0;
544 }
545
546 /* Raymond Chen says that we should safely unsubclass all the things!
547 (http://blogs.msdn.com/b/oldnewthing/archive/2003/11/11/55653.aspx) */
548
549 case WM_NCDESTROY:
550 {
551 szProgressText.Empty();
552 RemoveWindowSubclass(hWnd, DownloadProgressProc, uIdSubclass);
553 }
554 /* Fall-through */
555 default:
556 return DefSubclassProc(hWnd, uMsg, wParam, lParam);
557 }
558 }
559
560 VOID CDownloadManager::SetProgressMarquee(HWND Item, BOOL Enable)
561 {
562 if (!Item)
563 return;
564
565 DWORD style = GetWindowLongPtr(Item, GWL_STYLE);
566 if (!style)
567 return;
568
569 if (!SetWindowLongPtr(Item, GWL_STYLE, (Enable ? style | PBS_MARQUEE : style & ~PBS_MARQUEE)))
570 return;
571
572 SendMessageW(Item, PBM_SETMARQUEE, Enable, 0);
573 }
574
575 DWORD WINAPI CDownloadManager::ThreadFunc(LPVOID param)
576 {
577 CComPtr<IBindStatusCallback> dl;
578 ATL::CStringW Path;
579 PWSTR p, q;
580
581 HWND hDlg = static_cast<DownloadParam*>(param)->Dialog;
582 HWND Item;
583 INT iAppId;
584
585 ULONG dwContentLen, dwBytesWritten, dwBytesRead, dwStatus;
586 ULONG dwCurrentBytesRead = 0;
587 ULONG dwStatusLen = sizeof(dwStatus);
588
589 BOOL bCancelled = FALSE;
590 BOOL bTempfile = FALSE;
591 BOOL bCab = FALSE;
592
593 HINTERNET hOpen = NULL;
594 HINTERNET hFile = NULL;
595 HANDLE hOut = INVALID_HANDLE_VALUE;
596
597 unsigned char lpBuffer[4096];
598 LPCWSTR lpszAgent = L"RApps/1.0";
599 URL_COMPONENTS urlComponents;
600 size_t urlLength, filenameLength;
601
602 const ATL::CSimpleArray<DownloadInfo> &InfoArray = static_cast<DownloadParam*>(param)->AppInfo;
603 LPCWSTR szCaption = static_cast<DownloadParam*>(param)->szCaption;
604 ATL::CStringW szNewCaption;
605
606 if (InfoArray.GetSize() <= 0)
607 {
608 MessageBox_LoadString(hMainWnd, IDS_UNABLE_TO_DOWNLOAD);
609 goto end;
610 }
611
612 for (iAppId = 0; iAppId < InfoArray.GetSize(); ++iAppId)
613 {
614 // Reset progress bar
615 Item = GetDlgItem(hDlg, IDC_DOWNLOAD_PROGRESS);
616 if (Item)
617 {
618 SetProgressMarquee(Item, FALSE);
619 SendMessageW(Item, WM_SETTEXT, 0, (LPARAM) L"");
620 SendMessageW(Item, PBM_SETPOS, 0, 0);
621 }
622
623 // is this URL an update package for RAPPS? if so store it in a different place
624 if (InfoArray[iAppId].szUrl == APPLICATION_DATABASE_URL)
625 {
626 bCab = TRUE;
627 if (!GetStorageDirectory(Path))
628 goto end;
629 }
630 else
631 {
632 bCab = FALSE;
633 Path = SettingsInfo.szDownloadDir;
634 }
635
636 // Change caption to show the currently downloaded app
637 if (!bCab)
638 {
639 szNewCaption.Format(szCaption, InfoArray[iAppId].szName.GetString());
640 }
641 else
642 {
643 szNewCaption.LoadStringW(IDS_DL_DIALOG_DB_DOWNLOAD_DISP);
644 }
645
646 SetWindowTextW(hDlg, szNewCaption.GetString());
647
648 // build the path for the download
649 p = wcsrchr(InfoArray[iAppId].szUrl.GetString(), L'/');
650 q = wcsrchr(InfoArray[iAppId].szUrl.GetString(), L'?');
651
652 // do we have a final slash separator?
653 if (!p)
654 goto end;
655
656 // prepare the tentative length of the filename, maybe we've to remove part of it later on
657 filenameLength = wcslen(p) * sizeof(WCHAR);
658
659 /* do we have query arguments in the target URL after the filename? account for them
660 (e.g. https://example.org/myfile.exe?no_adware_plz) */
661 if (q && q > p && (q - p) > 0)
662 filenameLength -= wcslen(q - 1) * sizeof(WCHAR);
663
664 // is the path valid? can we access it?
665 if (GetFileAttributesW(Path.GetString()) == INVALID_FILE_ATTRIBUTES)
666 {
667 if (!CreateDirectoryW(Path.GetString(), NULL))
668 goto end;
669 }
670
671 // append a \ to the provided file system path, and the filename portion from the URL after that
672 Path += L"\\";
673 Path += (LPWSTR) (p + 1);
674
675 if (!bCab && InfoArray[iAppId].szSHA1[0] && GetFileAttributesW(Path.GetString()) != INVALID_FILE_ATTRIBUTES)
676 {
677 // only open it in case of total correctness
678 if (VerifyInteg(InfoArray[iAppId].szSHA1.GetString(), Path))
679 goto run;
680 }
681
682 // Add the download URL
683 SetDlgItemTextW(hDlg, IDC_DOWNLOAD_STATUS, InfoArray[iAppId].szUrl.GetString());
684
685 DownloadsListView.SetDownloadStatus(iAppId, DLSTATUS_DOWNLOADING);
686
687 // download it
688 bTempfile = TRUE;
689 CDownloadDialog_Constructor(hDlg, &bCancelled, IID_PPV_ARG(IBindStatusCallback, &dl));
690
691 if (dl == NULL)
692 goto end;
693
694 /* FIXME: this should just be using the system-wide proxy settings */
695 switch (SettingsInfo.Proxy)
696 {
697 case 0: // preconfig
698 default:
699 hOpen = InternetOpenW(lpszAgent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
700 break;
701 case 1: // direct (no proxy)
702 hOpen = InternetOpenW(lpszAgent, INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
703 break;
704 case 2: // use proxy
705 hOpen = InternetOpenW(lpszAgent, INTERNET_OPEN_TYPE_PROXY, SettingsInfo.szProxyServer, SettingsInfo.szNoProxyFor, 0);
706 break;
707 }
708
709 if (!hOpen)
710 goto end;
711
712 hFile = InternetOpenUrlW(hOpen, InfoArray[iAppId].szUrl.GetString(), NULL, 0,
713 INTERNET_FLAG_DONT_CACHE | INTERNET_FLAG_PRAGMA_NOCACHE | INTERNET_FLAG_KEEP_CONNECTION,
714 0);
715
716 if (!hFile)
717 {
718 MessageBox_LoadString(hMainWnd, IDS_UNABLE_TO_DOWNLOAD2);
719 goto end;
720 }
721
722 if (!HttpQueryInfoW(hFile, HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER, &dwStatus, &dwStatusLen, NULL))
723 goto end;
724
725 if (dwStatus != HTTP_STATUS_OK)
726 {
727 MessageBox_LoadString(hMainWnd, IDS_UNABLE_TO_DOWNLOAD);
728 goto end;
729 }
730
731 dwStatusLen = sizeof(dwStatus);
732
733 memset(&urlComponents, 0, sizeof(urlComponents));
734 urlComponents.dwStructSize = sizeof(urlComponents);
735
736 urlLength = InfoArray[iAppId].szUrl.GetLength();
737 urlComponents.dwSchemeLength = urlLength + 1;
738 urlComponents.lpszScheme = (LPWSTR) malloc(urlComponents.dwSchemeLength * sizeof(WCHAR));
739 urlComponents.dwHostNameLength = urlLength + 1;
740 urlComponents.lpszHostName = (LPWSTR) malloc(urlComponents.dwHostNameLength * sizeof(WCHAR));
741
742 if (!InternetCrackUrlW(InfoArray[iAppId].szUrl, urlLength + 1, ICU_DECODE | ICU_ESCAPE, &urlComponents))
743 goto end;
744
745 dwContentLen = 0;
746
747 if (urlComponents.nScheme == INTERNET_SCHEME_HTTP || urlComponents.nScheme == INTERNET_SCHEME_HTTPS)
748 HttpQueryInfoW(hFile, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &dwContentLen, &dwStatusLen, 0);
749
750 if (urlComponents.nScheme == INTERNET_SCHEME_FTP)
751 dwContentLen = FtpGetFileSize(hFile, &dwStatus);
752
753 if (!dwContentLen)
754 {
755 // content-length is not known, enable marquee mode
756 SetProgressMarquee(Item, TRUE);
757 }
758
759 free(urlComponents.lpszScheme);
760 free(urlComponents.lpszHostName);
761
762 #ifdef USE_CERT_PINNING
763 // are we using HTTPS to download the RAPPS update package? check if the certificate is original
764 if ((urlComponents.nScheme == INTERNET_SCHEME_HTTPS) &&
765 (wcscmp(InfoArray[iAppId].szUrl, APPLICATION_DATABASE_URL) == 0))
766 {
767 CLocalPtr subjectName, issuerName;
768 CStringW szMsgText;
769 bool bAskQuestion = false;
770 if (!CertGetSubjectAndIssuer(hFile, subjectName, issuerName))
771 {
772 szMsgText.LoadStringW(IDS_UNABLE_TO_QUERY_CERT);
773 bAskQuestion = true;
774 }
775 else
776 {
777 if (strcmp(subjectName, CERT_SUBJECT_INFO) ||
778 strcmp(issuerName, CERT_ISSUER_INFO))
779 {
780 szMsgText.Format(IDS_MISMATCH_CERT_INFO, (char*)subjectName, (const char*)issuerName);
781 bAskQuestion = true;
782 }
783 }
784
785 if (bAskQuestion)
786 {
787 if (MessageBoxW(hMainWnd, szMsgText.GetString(), NULL, MB_YESNO | MB_ICONERROR) != IDYES)
788 {
789 goto end;
790 }
791 }
792 }
793 #endif
794
795 hOut = CreateFileW(Path.GetString(), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, 0, NULL);
796
797 if (hOut == INVALID_HANDLE_VALUE)
798 goto end;
799
800 dwCurrentBytesRead = 0;
801 do
802 {
803 if (!InternetReadFile(hFile, lpBuffer, _countof(lpBuffer), &dwBytesRead))
804 {
805 MessageBox_LoadString(hMainWnd, IDS_INTERRUPTED_DOWNLOAD);
806 goto end;
807 }
808
809 if (!WriteFile(hOut, &lpBuffer[0], dwBytesRead, &dwBytesWritten, NULL))
810 {
811 MessageBox_LoadString(hMainWnd, IDS_UNABLE_TO_WRITE);
812 goto end;
813 }
814
815 dwCurrentBytesRead += dwBytesRead;
816 dl->OnProgress(dwCurrentBytesRead, dwContentLen, 0, InfoArray[iAppId].szUrl.GetString());
817 } while (dwBytesRead && !bCancelled);
818
819 CloseHandle(hOut);
820 hOut = INVALID_HANDLE_VALUE;
821
822 if (bCancelled)
823 goto end;
824
825 if (!dwContentLen)
826 {
827 // set progress bar to 100%
828 SetProgressMarquee(Item, FALSE);
829
830 dwContentLen = dwCurrentBytesRead;
831 dl->OnProgress(dwCurrentBytesRead, dwContentLen, 0, InfoArray[iAppId].szUrl.GetString());
832 }
833
834 /* if this thing isn't a RAPPS update and it has a SHA-1 checksum
835 verify its integrity by using the native advapi32.A_SHA1 functions */
836 if (!bCab && InfoArray[iAppId].szSHA1[0] != 0)
837 {
838 ATL::CStringW szMsgText;
839
840 // change a few strings in the download dialog to reflect the verification process
841 if (!szMsgText.LoadStringW(IDS_INTEG_CHECK_TITLE))
842 goto end;
843
844 SetWindowTextW(hDlg, szMsgText.GetString());
845 SendMessageW(GetDlgItem(hDlg, IDC_DOWNLOAD_STATUS), WM_SETTEXT, 0, (LPARAM) Path.GetString());
846
847 // this may take a while, depending on the file size
848 if (!VerifyInteg(InfoArray[iAppId].szSHA1.GetString(), Path.GetString()))
849 {
850 if (!szMsgText.LoadStringW(IDS_INTEG_CHECK_FAIL))
851 goto end;
852
853 MessageBoxW(hDlg, szMsgText.GetString(), NULL, MB_OK | MB_ICONERROR);
854 goto end;
855 }
856 }
857
858 run:
859 DownloadsListView.SetDownloadStatus(iAppId, DLSTATUS_WAITING_INSTALL);
860
861 // run it
862 if (!bCab)
863 {
864 SHELLEXECUTEINFOW shExInfo = {0};
865 shExInfo.cbSize = sizeof(shExInfo);
866 shExInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
867 shExInfo.lpVerb = L"open";
868 shExInfo.lpFile = Path.GetString();
869 shExInfo.lpParameters = L"";
870 shExInfo.nShow = SW_SHOW;
871
872 if (ShellExecuteExW(&shExInfo))
873 {
874 //reflect installation progress in the titlebar
875 //TODO: make a separate string with a placeholder to include app name?
876 ATL::CStringW szMsgText = LoadStatusString(DLSTATUS_INSTALLING);
877 SetWindowTextW(hDlg, szMsgText.GetString());
878
879 DownloadsListView.SetDownloadStatus(iAppId, DLSTATUS_INSTALLING);
880
881 //TODO: issue an install operation separately so that the apps could be downloaded in the background
882 WaitForSingleObject(shExInfo.hProcess, INFINITE);
883 CloseHandle(shExInfo.hProcess);
884 }
885 else
886 {
887 MessageBox_LoadString(hMainWnd, IDS_UNABLE_TO_INSTALL);
888 }
889 }
890
891 end:
892 if (hOut != INVALID_HANDLE_VALUE)
893 CloseHandle(hOut);
894
895 InternetCloseHandle(hFile);
896 InternetCloseHandle(hOpen);
897
898 if (bTempfile)
899 {
900 if (bCancelled || (SettingsInfo.bDelInstaller && !bCab))
901 DeleteFileW(Path.GetString());
902 }
903
904 DownloadsListView.SetDownloadStatus(iAppId, DLSTATUS_FINISHED);
905 }
906
907 delete static_cast<DownloadParam*>(param);
908 SendMessageW(hDlg, WM_CLOSE, 0, 0);
909 return 0;
910 }
911
912 BOOL CDownloadManager::DownloadListOfApplications(const ATL::CSimpleArray<CAvailableApplicationInfo>& AppsList, BOOL bIsModal)
913 {
914 if (AppsList.GetSize() == 0)
915 return FALSE;
916
917 // Initialize shared variables
918 for (INT i = 0; i < AppsList.GetSize(); ++i)
919 {
920 AppsToInstallList.Add(AppsList[i]); // implicit conversion to DownloadInfo
921 }
922
923 // Create a dialog and issue a download process
924 LaunchDownloadDialog(bIsModal);
925
926 return TRUE;
927 }
928
929 BOOL CDownloadManager::DownloadApplication(CAvailableApplicationInfo* pAppInfo, BOOL bIsModal)
930 {
931 if (!pAppInfo)
932 return FALSE;
933
934 Download(*pAppInfo, bIsModal);
935 return TRUE;
936 }
937
938 VOID CDownloadManager::DownloadApplicationsDB(LPCWSTR lpUrl)
939 {
940 static DownloadInfo DatabaseDLInfo;
941 DatabaseDLInfo.szUrl = lpUrl;
942 DatabaseDLInfo.szName.LoadStringW(IDS_DL_DIALOG_DB_DISP);
943 Download(DatabaseDLInfo, TRUE);
944 }
945
946 //TODO: Reuse the dialog
947 VOID CDownloadManager::LaunchDownloadDialog(BOOL bIsModal)
948 {
949 if (bIsModal)
950 {
951 DialogBoxW(hInst,
952 MAKEINTRESOURCEW(IDD_DOWNLOAD_DIALOG),
953 hMainWnd,
954 DownloadDlgProc);
955 }
956 else
957 {
958 CreateDialogW(hInst,
959 MAKEINTRESOURCEW(IDD_DOWNLOAD_DIALOG),
960 hMainWnd,
961 DownloadDlgProc);
962 }
963 }
964 // CDownloadManager