forked from microsoft/winget-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDownloader.cpp
More file actions
210 lines (168 loc) · 7.18 KB
/
Copy pathDownloader.cpp
File metadata and controls
210 lines (168 loc) · 7.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#include "pch.h"
#include "Public/AppInstallerRuntime.h"
#include "Public/AppInstallerDownloader.h"
#include "Public/AppInstallerSHA256.h"
#include "Public/AppInstallerStrings.h"
#include "Public/AppInstallerLogging.h"
using namespace AppInstaller::Runtime;
namespace AppInstaller::Utility
{
std::optional<std::vector<BYTE>> DownloadToStream(
const std::string& url,
std::ostream& dest,
IProgressCallback& progress,
bool computeHash)
{
THROW_HR_IF(E_INVALIDARG, url.empty());
AICLI_LOG(Core, Info, << "Downloading from url: " << url);
wil::unique_hinternet session(InternetOpenA(
"winget-cli",
INTERNET_OPEN_TYPE_PRECONFIG,
NULL,
NULL,
0));
THROW_LAST_ERROR_IF_NULL_MSG(session, "InternetOpen() failed.");
wil::unique_hinternet urlFile(InternetOpenUrlA(
session.get(),
url.c_str(),
NULL,
0,
INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS, // This allows http->https redirection
0));
THROW_LAST_ERROR_IF_NULL_MSG(urlFile, "InternetOpenUrl() failed.");
// Check http return status
DWORD requestStatus = 0;
DWORD cbRequestStatus = sizeof(requestStatus);
THROW_LAST_ERROR_IF_MSG(!HttpQueryInfoA(urlFile.get(),
HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER,
&requestStatus,
&cbRequestStatus,
nullptr), "Query download request status failed.");
if (requestStatus != HTTP_STATUS_OK)
{
AICLI_LOG(Core, Error, << "Download request failed. Returned status: " << requestStatus);
THROW_HR_MSG(MAKE_HRESULT(SEVERITY_ERROR, FACILITY_HTTP, requestStatus), "Download request status is not success.");
}
AICLI_LOG(Core, Verbose, << "Download request status success.");
// Get content length. Don't fail the download if failed.
LONGLONG contentLength = 0;
DWORD cbContentLength = sizeof(contentLength);
HttpQueryInfoA(
urlFile.get(),
HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER64,
&contentLength,
&cbContentLength,
nullptr);
AICLI_LOG(Core, Verbose, << "Download size: " << contentLength);
// Setup hash engine
SHA256 hashEngine;
std::string contentHash;
const int bufferSize = 1024 * 1024; // 1MB
auto buffer = std::make_unique<BYTE[]>(bufferSize);
BOOL readSuccess = true;
DWORD bytesRead = 0;
LONGLONG bytesDownloaded = 0;
do
{
if (progress.IsCancelled())
{
AICLI_LOG(Core, Info, << "Download cancelled.");
return {};
}
readSuccess = InternetReadFile(urlFile.get(), buffer.get(), bufferSize, &bytesRead);
THROW_LAST_ERROR_IF_MSG(!readSuccess, "InternetReadFile() failed.");
if (computeHash)
{
hashEngine.Add(buffer.get(), bytesRead);
}
dest.write((char*)buffer.get(), bytesRead);
bytesDownloaded += bytesRead;
if (bytesRead != 0)
{
progress.OnProgress(bytesDownloaded, contentLength, ProgressType::Bytes);
}
} while (bytesRead != 0);
dest.flush();
std::vector<BYTE> result;
if (computeHash)
{
result = hashEngine.Get();
AICLI_LOG(Core, Info, << "Download hash: " << SHA256::ConvertToString(result));
}
AICLI_LOG(Core, Info, << "Download completed.");
return result;
}
std::optional<std::vector<BYTE>> Download(
const std::string& url,
const std::filesystem::path& dest,
IProgressCallback& progress,
bool computeHash)
{
THROW_HR_IF(E_INVALIDARG, url.empty());
THROW_HR_IF(E_INVALIDARG, dest.empty());
AICLI_LOG(Core, Info, << "Downloading to path: " << dest);
std::filesystem::create_directories(dest.parent_path());
std::ofstream emptyDestFile(dest);
emptyDestFile.close();
ApplyMotwIfApplicable(dest);
// Use std::ofstream::app to append to previous empty file so that it will not
// create a new file and clear motw.
std::ofstream outfile(dest, std::ofstream::binary | std::ofstream::app);
return DownloadToStream(url, outfile, progress, computeHash);
}
bool IsUrlRemote(std::string_view url)
{
using namespace std::string_view_literals;
constexpr std::string_view s_http_start = "http://"sv;
constexpr std::string_view s_https_start = "https://"sv;
// Very simple choice right now: "does it start with http:// or https://"?
if (CaseInsensitiveEquals(url.substr(0, s_http_start.length()), s_http_start) ||
CaseInsensitiveEquals(url.substr(0, s_https_start.length()), s_https_start))
{
return true;
}
return false;
}
void ApplyMotwIfApplicable(const std::filesystem::path& filePath)
{
AICLI_LOG(Core, Info, << "Started applying motw to " << filePath);
{
// Check the file system the input file is on.
wil::unique_hfile fileHandle{ CreateFileW(
filePath.c_str(), /*lpFileName*/
GENERIC_READ, /*dwDesiredAccess*/
0, /*dwShareMode*/
NULL, /*lpSecurityAttributes*/
OPEN_EXISTING, /*dwCreationDisposition*/
FILE_ATTRIBUTE_NORMAL, /*dwFlagsAndAttributes*/
NULL /*hTemplateFile*/) };
THROW_LAST_ERROR_IF(fileHandle.get() == INVALID_HANDLE_VALUE);
wchar_t fileSystemName[MAX_PATH];
THROW_LAST_ERROR_IF(!GetVolumeInformationByHandleW(
fileHandle.get(), /*hFile*/
NULL, /*lpVolumeNameBuffer*/
0, /*nVolumeNameSize*/
NULL, /*lpVolumeSerialNumber*/
NULL, /*lpMaximumComponentLength*/
NULL, /*lpFileSystemFlags*/
fileSystemName, /*lpFileSystemNameBuffer*/
MAX_PATH /*nFileSystemNameSize*/));
if (_wcsicmp(fileSystemName, L"NTFS") != 0)
{
AICLI_LOG(Core, Info, << "File system is not NTFS. Skipped applying motw");
return;
}
}
// Zone Indentifier stream name
// https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-fscc/6e3f7352-d11c-4d76-8c39-2516a9df36e8
std::filesystem::path motwPath(filePath);
motwPath += L":Zone.Identifier:$DATA";
// Apply mark of the web. ZoneId 3 means downloaded from internet.
std::ofstream motwStream(motwPath);
motwStream << "[ZoneTransfer]" << std::endl;
motwStream << "ZoneId=3" << std::endl;
AICLI_LOG(Core, Info, << "Finished applying motw");
}
}