[RAPPS] Don't use CDownloadManager outside loaddlg.cpp
[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 "rapps.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 SIZE_T len = wcslen(szStatusText) + 1;
194 ATL::CStringW buf;
195 DWORD dummyLen;
196
197 /* beautify our url for display purposes */
198 if (!InternetCanonicalizeUrlW(szStatusText, buf.GetBuffer(len), &dummyLen, ICU_DECODE | ICU_NO_ENCODE))
199 {
200 /* just use the original */
201 buf.ReleaseBuffer();
202 buf = szStatusText;
203 }
204 else
205 {
206 buf.ReleaseBuffer();
207 }
208
209 /* paste it into our dialog and don't do it again in this instance */
210 SendMessageW(Item, WM_SETTEXT, 0, (LPARAM) buf.GetString());
211 m_UrlHasBeenCopied = TRUE;
212 }
213
214 SetLastError(ERROR_SUCCESS);
215 r = GetWindowLongPtrW(m_hDialog, GWLP_USERDATA);
216 if (r || GetLastError() != ERROR_SUCCESS)
217 {
218 *m_pbCancelled = TRUE;
219 return E_ABORT;
220 }
221
222 return S_OK;
223 }
224
225 virtual HRESULT STDMETHODCALLTYPE OnStopBinding(
226 HRESULT hresult,
227 LPCWSTR szError)
228 {
229 return S_OK;
230 }
231
232 virtual HRESULT STDMETHODCALLTYPE GetBindInfo(
233 DWORD *grfBINDF,
234 BINDINFO *pbindinfo)
235 {
236 return S_OK;
237 }
238
239 virtual HRESULT STDMETHODCALLTYPE OnDataAvailable(
240 DWORD grfBSCF,
241 DWORD dwSize,
242 FORMATETC *pformatetc,
243 STGMEDIUM *pstgmed)
244 {
245 return S_OK;
246 }
247
248 virtual HRESULT STDMETHODCALLTYPE OnObjectAvailable(
249 REFIID riid,
250 IUnknown *punk)
251 {
252 return S_OK;
253 }
254
255 BEGIN_COM_MAP(CDownloadDialog)
256 COM_INTERFACE_ENTRY_IID(IID_IBindStatusCallback, IBindStatusCallback)
257 END_COM_MAP()
258 };
259
260 class CDowloadingAppsListView
261 : public CUiWindow<CListView>
262 {
263 public:
264 HWND Create(HWND hwndParent)
265 {
266 RECT r = {10, 150, 320, 350};
267 const DWORD style = WS_CHILD | WS_VISIBLE | LVS_REPORT | LVS_SINGLESEL
268 | LVS_SHOWSELALWAYS | LVS_NOSORTHEADER | LVS_NOCOLUMNHEADER;
269
270 HWND hwnd = CListView::Create(hwndParent, r, NULL, style, WS_EX_CLIENTEDGE);
271
272 AddColumn(0, 150, LVCFMT_LEFT);
273 AddColumn(1, 120, LVCFMT_LEFT);
274
275 return hwnd;
276 }
277
278 VOID LoadList(ATL::CSimpleArray<DownloadInfo> arrInfo)
279 {
280 for (INT i = 0; i < arrInfo.GetSize(); ++i)
281 {
282 AddRow(i, arrInfo[i].szName.GetString(), DLSTATUS_WAITING);
283 }
284 }
285
286 VOID SetDownloadStatus(INT ItemIndex, DownloadStatus Status)
287 {
288 HWND hListView = GetWindow();
289 ATL::CStringW szBuffer = LoadStatusString(Status);
290 ListView_SetItemText(hListView, ItemIndex, 1, const_cast<LPWSTR>(szBuffer.GetString()));
291 }
292
293 BOOL AddItem(INT ItemIndex, LPWSTR lpText)
294 {
295 LVITEMW Item;
296
297 ZeroMemory(&Item, sizeof(Item));
298
299 Item.mask = LVIF_TEXT | LVIF_STATE;
300 Item.pszText = lpText;
301 Item.iItem = ItemIndex;
302
303 return InsertItem(&Item);
304 }
305
306 VOID AddRow(INT RowIndex, LPCWSTR szAppName, const DownloadStatus Status)
307 {
308 ATL::CStringW szStatus = LoadStatusString(Status);
309 AddItem(RowIndex,
310 const_cast<LPWSTR>(szAppName));
311 SetDownloadStatus(RowIndex, Status);
312 }
313
314 BOOL AddColumn(INT Index, INT Width, INT Format)
315 {
316 LVCOLUMNW Column;
317 ZeroMemory(&Column, sizeof(Column));
318
319 Column.mask = LVCF_FMT | LVCF_WIDTH | LVCF_SUBITEM;
320 Column.iSubItem = Index;
321 Column.cx = Width;
322 Column.fmt = Format;
323
324 return (InsertColumn(Index, &Column) == -1) ? FALSE : TRUE;
325 }
326 };
327
328 extern "C"
329 HRESULT WINAPI CDownloadDialog_Constructor(HWND Dlg, BOOL *pbCancelled, REFIID riid, LPVOID *ppv)
330 {
331 return ShellObjectCreatorInit<CDownloadDialog>(Dlg, pbCancelled, riid, ppv);
332 }
333
334 #ifdef USE_CERT_PINNING
335 typedef CHeapPtr<char, CLocalAllocator> CLocalPtr;
336
337 static BOOL CertGetSubjectAndIssuer(HINTERNET hFile, CLocalPtr& subjectInfo, CLocalPtr& issuerInfo)
338 {
339 DWORD certInfoLength;
340 INTERNET_CERTIFICATE_INFOA certInfo;
341 DWORD size, flags;
342
343 size = sizeof(flags);
344 if (!InternetQueryOptionA(hFile, INTERNET_OPTION_SECURITY_FLAGS, &flags, &size))
345 {
346 return FALSE;
347 }
348
349 if (!flags & SECURITY_FLAG_SECURE)
350 {
351 return FALSE;
352 }
353
354 /* Despite what the header indicates, the implementation of INTERNET_CERTIFICATE_INFO is not Unicode-aware. */
355 certInfoLength = sizeof(certInfo);
356 if (!InternetQueryOptionA(hFile,
357 INTERNET_OPTION_SECURITY_CERTIFICATE_STRUCT,
358 &certInfo,
359 &certInfoLength))
360 {
361 return FALSE;
362 }
363
364 subjectInfo.Attach(certInfo.lpszSubjectInfo);
365 issuerInfo.Attach(certInfo.lpszIssuerInfo);
366
367 if (certInfo.lpszProtocolName)
368 LocalFree(certInfo.lpszProtocolName);
369 if (certInfo.lpszSignatureAlgName)
370 LocalFree(certInfo.lpszSignatureAlgName);
371 if (certInfo.lpszEncryptionAlgName)
372 LocalFree(certInfo.lpszEncryptionAlgName);
373
374 return certInfo.lpszSubjectInfo && certInfo.lpszIssuerInfo;
375 }
376 #endif
377
378 inline VOID MessageBox_LoadString(HWND hMainWnd, INT StringID)
379 {
380 ATL::CStringW szMsgText;
381 if (szMsgText.LoadStringW(StringID))
382 {
383 MessageBoxW(hMainWnd, szMsgText.GetString(), NULL, MB_OK | MB_ICONERROR);
384 }
385 }
386
387
388 // Download dialog (loaddlg.cpp)
389 class CDownloadManager
390 {
391 static ATL::CSimpleArray<DownloadInfo> AppsToInstallList;
392 static CDowloadingAppsListView DownloadsListView;
393
394 static VOID SetProgressMarquee(HWND Item, BOOL Enable);
395
396 public:
397 static VOID Add(DownloadInfo info);
398 static VOID Download(const DownloadInfo& DLInfo, BOOL bIsModal = FALSE);
399 static INT_PTR CALLBACK DownloadDlgProc(HWND Dlg, UINT uMsg, WPARAM wParam, LPARAM lParam);
400 static LRESULT CALLBACK DownloadProgressProc(HWND hWnd,
401 UINT uMsg,
402 WPARAM wParam,
403 LPARAM lParam,
404 UINT_PTR uIdSubclass,
405 DWORD_PTR dwRefData);
406
407 static DWORD WINAPI ThreadFunc(LPVOID Context);
408 static BOOL DownloadListOfApplications(const ATL::CSimpleArray<CAvailableApplicationInfo>& AppsList, BOOL bIsModal = FALSE);
409 static BOOL DownloadApplication(CAvailableApplicationInfo* pAppInfo, BOOL bIsModal = FALSE);
410 static VOID DownloadApplicationsDB(LPCWSTR lpUrl);
411 static VOID LaunchDownloadDialog(BOOL);
412 };
413
414
415 // CDownloadManager
416 ATL::CSimpleArray<DownloadInfo> CDownloadManager::AppsToInstallList;
417 CDowloadingAppsListView CDownloadManager::DownloadsListView;
418
419 VOID CDownloadManager::Add(DownloadInfo info)
420 {
421 AppsToInstallList.Add(info);
422 }
423
424 VOID CDownloadManager::Download(const DownloadInfo &DLInfo, BOOL bIsModal)
425 {
426 AppsToInstallList.RemoveAll();
427 AppsToInstallList.Add(DLInfo);
428 LaunchDownloadDialog(bIsModal);
429 }
430
431 INT_PTR CALLBACK CDownloadManager::DownloadDlgProc(HWND Dlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
432 {
433 static WCHAR szCaption[MAX_PATH];
434
435 switch (uMsg)
436 {
437 case WM_INITDIALOG:
438 {
439 HICON hIconSm, hIconBg;
440 ATL::CStringW szTempCaption;
441
442 hIconBg = (HICON) GetClassLongPtrW(hMainWnd, GCLP_HICON);
443 hIconSm = (HICON) GetClassLongPtrW(hMainWnd, GCLP_HICONSM);
444
445 if (hIconBg && hIconSm)
446 {
447 SendMessageW(Dlg, WM_SETICON, ICON_BIG, (LPARAM) hIconBg);
448 SendMessageW(Dlg, WM_SETICON, ICON_SMALL, (LPARAM) hIconSm);
449 }
450
451 SetWindowLongW(Dlg, GWLP_USERDATA, 0);
452 HWND Item = GetDlgItem(Dlg, IDC_DOWNLOAD_PROGRESS);
453 if (Item)
454 {
455 // initialize the default values for our nifty progress bar
456 // and subclass it so that it learns to print a status text
457 SendMessageW(Item, PBM_SETRANGE, 0, MAKELPARAM(0, 100));
458 SendMessageW(Item, PBM_SETPOS, 0, 0);
459
460 SetWindowSubclass(Item, DownloadProgressProc, 0, 0);
461 }
462
463 // Add a ListView
464 HWND hListView = DownloadsListView.Create(Dlg);
465 if (!hListView)
466 {
467 return FALSE;
468 }
469 DownloadsListView.LoadList(AppsToInstallList);
470
471 // Get a dlg string for later use
472 GetWindowTextW(Dlg, szCaption, _countof(szCaption));
473
474 // Hide a placeholder from displaying
475 szTempCaption = szCaption;
476 szTempCaption.Replace(L"%ls", L"");
477 SetWindowText(Dlg, szTempCaption.GetString());
478
479 ShowWindow(Dlg, SW_SHOW);
480
481 // Start download process
482 DownloadParam *param = new DownloadParam(Dlg, AppsToInstallList, szCaption);
483 DWORD ThreadId;
484 HANDLE Thread = CreateThread(NULL, 0, ThreadFunc, (LPVOID) param, 0, &ThreadId);
485
486 if (!Thread)
487 {
488 return FALSE;
489 }
490
491 CloseHandle(Thread);
492 AppsToInstallList.RemoveAll();
493 return TRUE;
494 }
495
496 case WM_COMMAND:
497 if (wParam == IDCANCEL)
498 {
499 SetWindowLongW(Dlg, GWLP_USERDATA, 1);
500 PostMessageW(Dlg, WM_CLOSE, 0, 0);
501 }
502 return FALSE;
503
504 case WM_CLOSE:
505 EndDialog(Dlg, 0);
506 //DestroyWindow(Dlg);
507 return TRUE;
508
509 default:
510 return FALSE;
511 }
512 }
513
514 LRESULT CALLBACK CDownloadManager::DownloadProgressProc(HWND hWnd,
515 UINT uMsg,
516 WPARAM wParam,
517 LPARAM lParam,
518 UINT_PTR uIdSubclass,
519 DWORD_PTR dwRefData)
520 {
521 static ATL::CStringW szProgressText;
522
523 switch (uMsg)
524 {
525 case WM_SETTEXT:
526 {
527 if (lParam)
528 {
529 szProgressText = (PCWSTR) lParam;
530 }
531 return TRUE;
532 }
533
534 case WM_ERASEBKGND:
535 case WM_PAINT:
536 {
537 PAINTSTRUCT ps;
538 HDC hDC = BeginPaint(hWnd, &ps), hdcMem;
539 HBITMAP hbmMem;
540 HANDLE hOld;
541 RECT myRect;
542 UINT win_width, win_height;
543
544 GetClientRect(hWnd, &myRect);
545
546 /* grab the progress bar rect size */
547 win_width = myRect.right - myRect.left;
548 win_height = myRect.bottom - myRect.top;
549
550 /* create an off-screen DC for double-buffering */
551 hdcMem = CreateCompatibleDC(hDC);
552 hbmMem = CreateCompatibleBitmap(hDC, win_width, win_height);
553
554 hOld = SelectObject(hdcMem, hbmMem);
555
556 /* call the original draw code and redirect it to our memory buffer */
557 DefSubclassProc(hWnd, uMsg, (WPARAM) hdcMem, lParam);
558
559 /* draw our nifty progress text over it */
560 SelectFont(hdcMem, GetStockFont(DEFAULT_GUI_FONT));
561 DrawShadowText(hdcMem, szProgressText.GetString(), szProgressText.GetLength(),
562 &myRect,
563 DT_CENTER | DT_VCENTER | DT_NOPREFIX | DT_SINGLELINE,
564 GetSysColor(COLOR_CAPTIONTEXT),
565 GetSysColor(COLOR_3DSHADOW),
566 1, 1);
567
568 /* transfer the off-screen DC to the screen */
569 BitBlt(hDC, 0, 0, win_width, win_height, hdcMem, 0, 0, SRCCOPY);
570
571 /* free the off-screen DC */
572 SelectObject(hdcMem, hOld);
573 DeleteObject(hbmMem);
574 DeleteDC(hdcMem);
575
576 EndPaint(hWnd, &ps);
577 return 0;
578 }
579
580 /* Raymond Chen says that we should safely unsubclass all the things!
581 (http://blogs.msdn.com/b/oldnewthing/archive/2003/11/11/55653.aspx) */
582
583 case WM_NCDESTROY:
584 {
585 szProgressText.Empty();
586 RemoveWindowSubclass(hWnd, DownloadProgressProc, uIdSubclass);
587 }
588 /* Fall-through */
589 default:
590 return DefSubclassProc(hWnd, uMsg, wParam, lParam);
591 }
592 }
593
594 VOID CDownloadManager::SetProgressMarquee(HWND Item, BOOL Enable)
595 {
596 if (!Item)
597 return;
598
599 DWORD style = GetWindowLongPtr(Item, GWL_STYLE);
600 if (!style)
601 return;
602
603 if (!SetWindowLongPtr(Item, GWL_STYLE, (Enable ? style | PBS_MARQUEE : style & ~PBS_MARQUEE)))
604 return;
605
606 SendMessageW(Item, PBM_SETMARQUEE, Enable, 0);
607 }
608
609 DWORD WINAPI CDownloadManager::ThreadFunc(LPVOID param)
610 {
611 CComPtr<IBindStatusCallback> dl;
612 ATL::CStringW Path;
613 PWSTR p, q;
614
615 HWND hDlg = static_cast<DownloadParam*>(param)->Dialog;
616 HWND Item;
617 INT iAppId;
618
619 ULONG dwContentLen, dwBytesWritten, dwBytesRead, dwStatus;
620 ULONG dwCurrentBytesRead = 0;
621 ULONG dwStatusLen = sizeof(dwStatus);
622
623 BOOL bCancelled = FALSE;
624 BOOL bTempfile = FALSE;
625 BOOL bCab = FALSE;
626
627 HINTERNET hOpen = NULL;
628 HINTERNET hFile = NULL;
629 HANDLE hOut = INVALID_HANDLE_VALUE;
630
631 unsigned char lpBuffer[4096];
632 LPCWSTR lpszAgent = L"RApps/1.0";
633 URL_COMPONENTS urlComponents;
634 size_t urlLength, filenameLength;
635
636 const ATL::CSimpleArray<DownloadInfo> &InfoArray = static_cast<DownloadParam*>(param)->AppInfo;
637 LPCWSTR szCaption = static_cast<DownloadParam*>(param)->szCaption;
638 ATL::CStringW szNewCaption;
639
640 const DWORD dwUrlConnectFlags = INTERNET_FLAG_DONT_CACHE | INTERNET_FLAG_PRAGMA_NOCACHE | INTERNET_FLAG_KEEP_CONNECTION;
641
642 if (InfoArray.GetSize() <= 0)
643 {
644 MessageBox_LoadString(hMainWnd, IDS_UNABLE_TO_DOWNLOAD);
645 goto end;
646 }
647
648 for (iAppId = 0; iAppId < InfoArray.GetSize(); ++iAppId)
649 {
650 // Reset progress bar
651 Item = GetDlgItem(hDlg, IDC_DOWNLOAD_PROGRESS);
652 if (Item)
653 {
654 SetProgressMarquee(Item, FALSE);
655 SendMessageW(Item, WM_SETTEXT, 0, (LPARAM) L"");
656 SendMessageW(Item, PBM_SETPOS, 0, 0);
657 }
658
659 // is this URL an update package for RAPPS? if so store it in a different place
660 if (InfoArray[iAppId].szUrl == APPLICATION_DATABASE_URL)
661 {
662 bCab = TRUE;
663 if (!GetStorageDirectory(Path))
664 goto end;
665 }
666 else
667 {
668 bCab = FALSE;
669 Path = SettingsInfo.szDownloadDir;
670 }
671
672 // Change caption to show the currently downloaded app
673 if (!bCab)
674 {
675 szNewCaption.Format(szCaption, InfoArray[iAppId].szName.GetString());
676 }
677 else
678 {
679 szNewCaption.LoadStringW(IDS_DL_DIALOG_DB_DOWNLOAD_DISP);
680 }
681
682 SetWindowTextW(hDlg, szNewCaption.GetString());
683
684 // build the path for the download
685 p = wcsrchr(InfoArray[iAppId].szUrl.GetString(), L'/');
686 q = wcsrchr(InfoArray[iAppId].szUrl.GetString(), L'?');
687
688 // do we have a final slash separator?
689 if (!p)
690 goto end;
691
692 // prepare the tentative length of the filename, maybe we've to remove part of it later on
693 filenameLength = wcslen(p) * sizeof(WCHAR);
694
695 /* do we have query arguments in the target URL after the filename? account for them
696 (e.g. https://example.org/myfile.exe?no_adware_plz) */
697 if (q && q > p && (q - p) > 0)
698 filenameLength -= wcslen(q - 1) * sizeof(WCHAR);
699
700 // is the path valid? can we access it?
701 if (GetFileAttributesW(Path.GetString()) == INVALID_FILE_ATTRIBUTES)
702 {
703 if (!CreateDirectoryW(Path.GetString(), NULL))
704 goto end;
705 }
706
707 // append a \ to the provided file system path, and the filename portion from the URL after that
708 Path += L"\\";
709 Path += (LPWSTR) (p + 1);
710
711 if (!bCab && InfoArray[iAppId].szSHA1[0] && GetFileAttributesW(Path.GetString()) != INVALID_FILE_ATTRIBUTES)
712 {
713 // only open it in case of total correctness
714 if (VerifyInteg(InfoArray[iAppId].szSHA1.GetString(), Path))
715 goto run;
716 }
717
718 // Add the download URL
719 SetDlgItemTextW(hDlg, IDC_DOWNLOAD_STATUS, InfoArray[iAppId].szUrl.GetString());
720
721 DownloadsListView.SetDownloadStatus(iAppId, DLSTATUS_DOWNLOADING);
722
723 // download it
724 bTempfile = TRUE;
725 CDownloadDialog_Constructor(hDlg, &bCancelled, IID_PPV_ARG(IBindStatusCallback, &dl));
726
727 if (dl == NULL)
728 goto end;
729
730 /* FIXME: this should just be using the system-wide proxy settings */
731 switch (SettingsInfo.Proxy)
732 {
733 case 0: // preconfig
734 default:
735 hOpen = InternetOpenW(lpszAgent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
736 break;
737 case 1: // direct (no proxy)
738 hOpen = InternetOpenW(lpszAgent, INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
739 break;
740 case 2: // use proxy
741 hOpen = InternetOpenW(lpszAgent, INTERNET_OPEN_TYPE_PROXY, SettingsInfo.szProxyServer, SettingsInfo.szNoProxyFor, 0);
742 break;
743 }
744
745 if (!hOpen)
746 goto end;
747
748 dwStatusLen = sizeof(dwStatus);
749
750 memset(&urlComponents, 0, sizeof(urlComponents));
751 urlComponents.dwStructSize = sizeof(urlComponents);
752
753 urlLength = InfoArray[iAppId].szUrl.GetLength();
754 urlComponents.dwSchemeLength = urlLength + 1;
755 urlComponents.lpszScheme = (LPWSTR) malloc(urlComponents.dwSchemeLength * sizeof(WCHAR));
756 urlComponents.dwHostNameLength = urlLength + 1;
757 urlComponents.lpszHostName = (LPWSTR) malloc(urlComponents.dwHostNameLength * sizeof(WCHAR));
758
759 if (!InternetCrackUrlW(InfoArray[iAppId].szUrl, urlLength + 1, ICU_DECODE | ICU_ESCAPE, &urlComponents))
760 goto end;
761
762 dwContentLen = 0;
763
764 if (urlComponents.nScheme == INTERNET_SCHEME_HTTP || urlComponents.nScheme == INTERNET_SCHEME_HTTPS)
765 {
766 hFile = InternetOpenUrlW(hOpen, InfoArray[iAppId].szUrl.GetString(), NULL, 0,
767 dwUrlConnectFlags,
768 0);
769 if (!hFile)
770 {
771 MessageBox_LoadString(hMainWnd, IDS_UNABLE_TO_DOWNLOAD2);
772 goto end;
773 }
774
775 // query connection
776 if (!HttpQueryInfoW(hFile, HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER, &dwStatus, &dwStatusLen, NULL))
777 goto end;
778
779 if (dwStatus != HTTP_STATUS_OK)
780 {
781 MessageBox_LoadString(hMainWnd, IDS_UNABLE_TO_DOWNLOAD);
782 goto end;
783 }
784
785 // query content length
786 HttpQueryInfoW(hFile, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &dwContentLen, &dwStatusLen, NULL);
787 }
788
789 if (urlComponents.nScheme == INTERNET_SCHEME_FTP)
790 {
791 // force passive mode on FTP
792 hFile = InternetOpenUrlW(hOpen, InfoArray[iAppId].szUrl.GetString(), NULL, 0,
793 dwUrlConnectFlags | INTERNET_FLAG_PASSIVE,
794 0);
795 if (!hFile)
796 {
797 MessageBox_LoadString(hMainWnd, IDS_UNABLE_TO_DOWNLOAD2);
798 goto end;
799 }
800
801 dwContentLen = FtpGetFileSize(hFile, &dwStatus);
802 }
803
804 if (!dwContentLen)
805 {
806 // content-length is not known, enable marquee mode
807 SetProgressMarquee(Item, TRUE);
808 }
809
810 free(urlComponents.lpszScheme);
811 free(urlComponents.lpszHostName);
812
813 #ifdef USE_CERT_PINNING
814 // are we using HTTPS to download the RAPPS update package? check if the certificate is original
815 if ((urlComponents.nScheme == INTERNET_SCHEME_HTTPS) &&
816 (wcscmp(InfoArray[iAppId].szUrl, APPLICATION_DATABASE_URL) == 0))
817 {
818 CLocalPtr subjectName, issuerName;
819 CStringW szMsgText;
820 bool bAskQuestion = false;
821 if (!CertGetSubjectAndIssuer(hFile, subjectName, issuerName))
822 {
823 szMsgText.LoadStringW(IDS_UNABLE_TO_QUERY_CERT);
824 bAskQuestion = true;
825 }
826 else
827 {
828 if (strcmp(subjectName, CERT_SUBJECT_INFO) ||
829 strcmp(issuerName, CERT_ISSUER_INFO))
830 {
831 szMsgText.Format(IDS_MISMATCH_CERT_INFO, (char*)subjectName, (const char*)issuerName);
832 bAskQuestion = true;
833 }
834 }
835
836 if (bAskQuestion)
837 {
838 if (MessageBoxW(hMainWnd, szMsgText.GetString(), NULL, MB_YESNO | MB_ICONERROR) != IDYES)
839 {
840 goto end;
841 }
842 }
843 }
844 #endif
845
846 hOut = CreateFileW(Path.GetString(), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, 0, NULL);
847
848 if (hOut == INVALID_HANDLE_VALUE)
849 goto end;
850
851 dwCurrentBytesRead = 0;
852 do
853 {
854 if (!InternetReadFile(hFile, lpBuffer, _countof(lpBuffer), &dwBytesRead))
855 {
856 MessageBox_LoadString(hMainWnd, IDS_INTERRUPTED_DOWNLOAD);
857 goto end;
858 }
859
860 if (!WriteFile(hOut, &lpBuffer[0], dwBytesRead, &dwBytesWritten, NULL))
861 {
862 MessageBox_LoadString(hMainWnd, IDS_UNABLE_TO_WRITE);
863 goto end;
864 }
865
866 dwCurrentBytesRead += dwBytesRead;
867 dl->OnProgress(dwCurrentBytesRead, dwContentLen, 0, InfoArray[iAppId].szUrl.GetString());
868 } while (dwBytesRead && !bCancelled);
869
870 CloseHandle(hOut);
871 hOut = INVALID_HANDLE_VALUE;
872
873 if (bCancelled)
874 goto end;
875
876 if (!dwContentLen)
877 {
878 // set progress bar to 100%
879 SetProgressMarquee(Item, FALSE);
880
881 dwContentLen = dwCurrentBytesRead;
882 dl->OnProgress(dwCurrentBytesRead, dwContentLen, 0, InfoArray[iAppId].szUrl.GetString());
883 }
884
885 /* if this thing isn't a RAPPS update and it has a SHA-1 checksum
886 verify its integrity by using the native advapi32.A_SHA1 functions */
887 if (!bCab && InfoArray[iAppId].szSHA1[0] != 0)
888 {
889 ATL::CStringW szMsgText;
890
891 // change a few strings in the download dialog to reflect the verification process
892 if (!szMsgText.LoadStringW(IDS_INTEG_CHECK_TITLE))
893 goto end;
894
895 SetWindowTextW(hDlg, szMsgText.GetString());
896 SendMessageW(GetDlgItem(hDlg, IDC_DOWNLOAD_STATUS), WM_SETTEXT, 0, (LPARAM) Path.GetString());
897
898 // this may take a while, depending on the file size
899 if (!VerifyInteg(InfoArray[iAppId].szSHA1.GetString(), Path.GetString()))
900 {
901 if (!szMsgText.LoadStringW(IDS_INTEG_CHECK_FAIL))
902 goto end;
903
904 MessageBoxW(hDlg, szMsgText.GetString(), NULL, MB_OK | MB_ICONERROR);
905 goto end;
906 }
907 }
908
909 run:
910 DownloadsListView.SetDownloadStatus(iAppId, DLSTATUS_WAITING_INSTALL);
911
912 // run it
913 if (!bCab)
914 {
915 SHELLEXECUTEINFOW shExInfo = {0};
916 shExInfo.cbSize = sizeof(shExInfo);
917 shExInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
918 shExInfo.lpVerb = L"open";
919 shExInfo.lpFile = Path.GetString();
920 shExInfo.lpParameters = L"";
921 shExInfo.nShow = SW_SHOW;
922
923 if (ShellExecuteExW(&shExInfo))
924 {
925 //reflect installation progress in the titlebar
926 //TODO: make a separate string with a placeholder to include app name?
927 ATL::CStringW szMsgText = LoadStatusString(DLSTATUS_INSTALLING);
928 SetWindowTextW(hDlg, szMsgText.GetString());
929
930 DownloadsListView.SetDownloadStatus(iAppId, DLSTATUS_INSTALLING);
931
932 //TODO: issue an install operation separately so that the apps could be downloaded in the background
933 WaitForSingleObject(shExInfo.hProcess, INFINITE);
934 CloseHandle(shExInfo.hProcess);
935 }
936 else
937 {
938 MessageBox_LoadString(hMainWnd, IDS_UNABLE_TO_INSTALL);
939 }
940 }
941
942 end:
943 if (hOut != INVALID_HANDLE_VALUE)
944 CloseHandle(hOut);
945
946 InternetCloseHandle(hFile);
947 InternetCloseHandle(hOpen);
948
949 if (bTempfile)
950 {
951 if (bCancelled || (SettingsInfo.bDelInstaller && !bCab))
952 DeleteFileW(Path.GetString());
953 }
954
955 DownloadsListView.SetDownloadStatus(iAppId, DLSTATUS_FINISHED);
956 }
957
958 delete static_cast<DownloadParam*>(param);
959 SendMessageW(hDlg, WM_CLOSE, 0, 0);
960 return 0;
961 }
962
963 //TODO: Reuse the dialog
964 VOID CDownloadManager::LaunchDownloadDialog(BOOL bIsModal)
965 {
966 if (bIsModal)
967 {
968 DialogBoxW(hInst,
969 MAKEINTRESOURCEW(IDD_DOWNLOAD_DIALOG),
970 hMainWnd,
971 DownloadDlgProc);
972 }
973 else
974 {
975 CreateDialogW(hInst,
976 MAKEINTRESOURCEW(IDD_DOWNLOAD_DIALOG),
977 hMainWnd,
978 DownloadDlgProc);
979 }
980 }
981 // CDownloadManager
982
983
984 BOOL DownloadListOfApplications(const ATL::CSimpleArray<CAvailableApplicationInfo>& AppsList, BOOL bIsModal)
985 {
986 if (AppsList.GetSize() == 0)
987 return FALSE;
988
989 // Initialize shared variables
990 for (INT i = 0; i < AppsList.GetSize(); ++i)
991 {
992 CDownloadManager::Add(AppsList[i]); // implicit conversion to DownloadInfo
993 }
994
995 // Create a dialog and issue a download process
996 CDownloadManager::LaunchDownloadDialog(bIsModal);
997
998 return TRUE;
999 }
1000
1001 BOOL DownloadApplication(CAvailableApplicationInfo* pAppInfo, BOOL bIsModal)
1002 {
1003 if (!pAppInfo)
1004 return FALSE;
1005
1006 CDownloadManager::Download(*pAppInfo, bIsModal);
1007 return TRUE;
1008 }
1009
1010 VOID DownloadApplicationsDB(LPCWSTR lpUrl)
1011 {
1012 static DownloadInfo DatabaseDLInfo;
1013 DatabaseDLInfo.szUrl = lpUrl;
1014 DatabaseDLInfo.szName.LoadStringW(IDS_DL_DIALOG_DB_DISP);
1015 CDownloadManager::Download(DatabaseDLInfo, TRUE);
1016 }
1017