Debian Codegraph @

src/common/download.cpp

raw symbols SCIP
1 // Copyright (c) 2017-2022, The Monero Project
2 //
3 // All rights reserved.
4 //
5 // Redistribution and use in source and binary forms, with or without modification, are
6 // permitted provided that the following conditions are met:
7 //
8 // 1. Redistributions of source code must retain the above copyright notice, this list of
9 // conditions and the following disclaimer.
10 //
11 // 2. Redistributions in binary form must reproduce the above copyright notice, this list
12 // of conditions and the following disclaimer in the documentation and/or other
13 // materials provided with the distribution.
14 //
15 // 3. Neither the name of the copyright holder nor the names of its contributors may be
16 // used to endorse or promote products derived from this software without specific
17 // prior written permission.
18 //
19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
20 // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
21 // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
22 // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25 // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
26 // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
27 // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
29 #include <string>
30 #include <atomic>
31 #include <boost/filesystem.hpp>
32 #include <boost/thread/thread.hpp>
33 #include "net/http_client.h"
34 #include "download.h"
35
36 #undef MONERO_DEFAULT_LOG_CATEGORY
37 #define MONERO_DEFAULT_LOG_CATEGORY "net.dl"
38
39 namespace tools
40 {
41 struct download_thread_control
42 {
43 const std::string path;
44 const std::string uri;
45 std::function<void(const std::string&, const std::string&, bool)> result_cb;
46 std::function<bool(const std::string&, const std::string&, size_t, ssize_t)> progress_cb;
47 bool stop;
48 bool stopped;
49 bool success;
50 boost::thread thread;
51 boost::mutex mutex;
52
53 download_thread_control(const std::string &path, const std::string &uri, std::function<void(const std::string&, const std::string&, bool)> result_cb, std::function<bool(const std::string&, const std::string&, size_t, ssize_t)> progress_cb):
54 path(path), uri(uri), result_cb(result_cb), progress_cb(progress_cb), stop(false), stopped(false), success(false) {}
55 ~download_thread_control() { if (thread.joinable()) { thread.detach(); thread = {}; } }
56 };
57
58 static void download_thread(download_async_handle control)
59 {
60 static std::atomic<unsigned int> thread_id(0);
61
62 MLOG_SET_THREAD_NAME("DL" + std::to_string(thread_id++));
63
64 struct stopped_setter
65 {
66 stopped_setter(const download_async_handle &control): control(control) {}
67 ~stopped_setter() { control->stopped = true; }
68 download_async_handle control;
69 } stopped_setter(control);
70
71 try
72 {
73 boost::unique_lock<boost::mutex> lock(control->mutex);
74 std::ios_base::openmode mode = std::ios_base::out | std::ios_base::binary;
75 boost::system::error_code ec{};
76 uint64_t existing_size = static_cast<uint64_t>(boost::filesystem::file_size(control->path, ec));
77 if (ec)
78 existing_size = 0;
79 if (existing_size > 0)
80 {
81 MINFO("Resuming downloading " << control->uri << " to " << control->path << " from " << existing_size);
82 mode |= std::ios_base::app;
83 }
84 else
85 {
86 MINFO("Downloading " << control->uri << " to " << control->path);
87 mode |= std::ios_base::trunc;
88 }
89 std::ofstream f;
90 f.open(control->path, mode);
91 if (!f.good()) {
92 MERROR("Failed to open file " << control->path);
93 control->result_cb(control->path, control->uri, control->success);
94 return;
95 }
96 class download_client: public epee::net_utils::http::http_simple_client
97 {
98 public:
99 download_client(download_async_handle control, std::ofstream &f, uint64_t offset = 0):
100 control(control), f(f), content_length(-1), total(0), offset(offset) {}
101 virtual ~download_client() { f.close(); }
102 virtual bool on_header(const epee::net_utils::http::http_response_info &headers)
103 {
104 for (const auto &kv: headers.m_header_info.m_etc_fields)
105 MDEBUG("Header: " << kv.first << ": " << kv.second);
106 ssize_t length;
107 if (epee::string_tools::get_xtype_from_string(length, headers.m_header_info.m_content_length) && length >= 0)
108 {
109 MINFO("Content-Length: " << length);
110 content_length = length;
111 boost::filesystem::path path(control->path);
112 try
113 {
114 boost::filesystem::space_info si = boost::filesystem::space(path);
115 if (si.available < (size_t)content_length)
116 {
117 const uint64_t avail = (si.available + 1023) / 1024, needed = (content_length + 1023) / 1024;
118 MERROR("Not enough space to download " << needed << " kB to " << path << " (" << avail << " kB available)");
119 return false;
120 }
121 }
122 catch (const std::exception &e) { MWARNING("Failed to check for free space: " << e.what()); }
123 }
124 if (offset > 0)
125 {
126 // we requested a range, so check if we're getting it, otherwise truncate
127 bool got_range = false;
128 const std::string prefix = "bytes=" + std::to_string(offset) + "-";
129 for (const auto &kv: headers.m_header_info.m_etc_fields)
130 {
131 if (kv.first == "Content-Range" && strncmp(kv.second.c_str(), prefix.c_str(), prefix.size()))
132 {
133 got_range = true;
134 break;
135 }
136 }
137 if (!got_range)
138 {
139 MWARNING("We did not get the requested range, downloading from start");
140 f.close();
141 f.open(control->path, std::ios_base::out | std::ios_base::binary | std::ios_base::trunc);
142 }
143 }
144 return true;
145 }
146 virtual bool handle_target_data(std::string &piece_of_transfer)
147 {
148 try
149 {
150 boost::lock_guard<boost::mutex> lock(control->mutex);
151 if (control->stop)
152 return false;
153 f << piece_of_transfer;
154 total += piece_of_transfer.size();
155 if (control->progress_cb && !control->progress_cb(control->path, control->uri, total, content_length))
156 return false;
157 return f.good();
158 }
159 catch (const std::exception &e)
160 {
161 MERROR("Error writing data: " << e.what());
162 return false;
163 }
164 }
165 private:
166 download_async_handle control;
167 std::ofstream &f;
168 ssize_t content_length;
169 size_t total;
170 uint64_t offset;
171 } client(control, f, existing_size);
172 epee::net_utils::http::url_content u_c;
173 if (!epee::net_utils::parse_url(control->uri, u_c))
174 {
175 MERROR("Failed to parse URL " << control->uri);
176 control->result_cb(control->path, control->uri, control->success);
177 return;
178 }
179 if (u_c.host.empty())
180 {
181 MERROR("Failed to determine address from URL " << control->uri);
182 control->result_cb(control->path, control->uri, control->success);
183 return;
184 }
185
186 lock.unlock();
187
188 epee::net_utils::ssl_support_t ssl = u_c.schema == "https" ? epee::net_utils::ssl_support_t::e_ssl_support_enabled : epee::net_utils::ssl_support_t::e_ssl_support_disabled;
189 uint16_t port = u_c.port ? u_c.port : ssl == epee::net_utils::ssl_support_t::e_ssl_support_enabled ? 443 : 80;
190 MDEBUG("Connecting to " << u_c.host << ":" << port);
191 client.set_server(u_c.host, std::to_string(port), boost::none, ssl);
192 if (!client.connect(std::chrono::seconds(30)))
193 {
194 boost::lock_guard<boost::mutex> lock(control->mutex);
195 MERROR("Failed to connect to " << control->uri);
196 control->result_cb(control->path, control->uri, control->success);
197 return;
198 }
199 MDEBUG("GETting " << u_c.uri);
200 const epee::net_utils::http::http_response_info *info = NULL;
201 epee::net_utils::http::fields_list fields;
202 if (existing_size > 0)
203 {
204 const std::string range = "bytes=" + std::to_string(existing_size) + "-";
205 MDEBUG("Asking for range: " << range);
206 fields.push_back(std::make_pair("Range", range));
207 }
208 if (!client.invoke_get(u_c.uri, std::chrono::seconds(30), "", &info, fields))
209 {
210 boost::lock_guard<boost::mutex> lock(control->mutex);
211 MERROR("Failed to connect to " << control->uri);
212 client.disconnect();
213 control->result_cb(control->path, control->uri, control->success);
214 return;
215 }
216 if (control->stop)
217 {
218 boost::lock_guard<boost::mutex> lock(control->mutex);
219 MDEBUG("Download cancelled");
220 client.disconnect();
221 control->result_cb(control->path, control->uri, control->success);
222 return;
223 }
224 if (!info)
225 {
226 boost::lock_guard<boost::mutex> lock(control->mutex);
227 MERROR("Failed invoking GET command to " << control->uri << ", no status info returned");
228 client.disconnect();
229 control->result_cb(control->path, control->uri, control->success);
230 return;
231 }
232 MDEBUG("response code: " << info->m_response_code);
233 MDEBUG("response length: " << info->m_header_info.m_content_length);
234 MDEBUG("response comment: " << info->m_response_comment);
235 MDEBUG("response body: " << info->m_body);
236 for (const auto &f: info->m_additional_fields)
237 MDEBUG("additional field: " << f.first << ": " << f.second);
238 if (info->m_response_code != 200 && info->m_response_code != 206)
239 {
240 boost::lock_guard<boost::mutex> lock(control->mutex);
241 MERROR("Status code " << info->m_response_code);
242 client.disconnect();
243 control->result_cb(control->path, control->uri, control->success);
244 return;
245 }
246 client.disconnect();
247 f.close();
248 MDEBUG("Download complete");
249 lock.lock();
250 control->success = true;
251 control->result_cb(control->path, control->uri, control->success);
252 return;
253 }
254 catch (const std::exception &e)
255 {
256 MERROR("Exception in download thread: " << e.what());
257 // fall through and call result_cb not from the catch block to avoid another exception
258 }
259 boost::lock_guard<boost::mutex> lock(control->mutex);
260 control->result_cb(control->path, control->uri, control->success);
261 }
262
263 bool download(const std::string &path, const std::string &url, std::function<bool(const std::string&, const std::string&, size_t, ssize_t)> cb)
264 {
265 bool success = false;
266 download_async_handle handle = download_async(path, url, [&success](const std::string&, const std::string&, bool result) {success = result;}, cb);
267 download_wait(handle);
268 return success;
269 }
270
271 download_async_handle download_async(const std::string &path, const std::string &url, std::function<void(const std::string&, const std::string&, bool)> result, std::function<bool(const std::string&, const std::string&, size_t, ssize_t)> progress)
272 {
273 download_async_handle control = std::make_shared<download_thread_control>(path, url, result, progress);
274 control->thread = boost::thread([control](){ download_thread(control); });
275 return control;
276 }
277
278 bool download_finished(const download_async_handle &control)
279 {
280 CHECK_AND_ASSERT_MES(control != 0, false, "NULL async download handle");
281 boost::lock_guard<boost::mutex> lock(control->mutex);
282 return control->stopped;
283 }
284
285 bool download_error(const download_async_handle &control)
286 {
287 CHECK_AND_ASSERT_MES(control != 0, false, "NULL async download handle");
288 boost::lock_guard<boost::mutex> lock(control->mutex);
289 return !control->success;
290 }
291
292 bool download_wait(const download_async_handle &control)
293 {
294 CHECK_AND_ASSERT_MES(control != 0, false, "NULL async download handle");
295 {
296 boost::lock_guard<boost::mutex> lock(control->mutex);
297 if (control->stopped)
298 {
299 control->thread = {};
300 return true;
301 }
302 }
303 control->thread.join();
304 control->thread = {};
305 return true;
306 }
307
308 bool download_cancel(const download_async_handle &control)
309 {
310 CHECK_AND_ASSERT_MES(control != 0, false, "NULL async download handle");
311 {
312 boost::lock_guard<boost::mutex> lock(control->mutex);
313 if (control->stopped)
314 {
315 control->thread = {};
316 return true;
317 }
318 control->stop = true;
319 }
320 control->thread.join();
321 control->thread = {};
322 return true;
323 }
324 }