clientmedia.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  1. /*
  2. Minetest
  3. Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU Lesser General Public License as published by
  6. the Free Software Foundation; either version 2.1 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public License along
  13. with this program; if not, write to the Free Software Foundation, Inc.,
  14. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  15. */
  16. #include "clientmedia.h"
  17. #include "httpfetch.h"
  18. #include "client.h"
  19. #include "filecache.h"
  20. #include "filesys.h"
  21. #include "log.h"
  22. #include "porting.h"
  23. #include "settings.h"
  24. #include "util/hex.h"
  25. #include "util/serialize.h"
  26. #include "util/sha1.h"
  27. #include "util/string.h"
  28. static std::string getMediaCacheDir()
  29. {
  30. return porting::path_cache + DIR_DELIM + "media";
  31. }
  32. /*
  33. ClientMediaDownloader
  34. */
  35. ClientMediaDownloader::ClientMediaDownloader():
  36. m_media_cache(getMediaCacheDir()),
  37. m_httpfetch_caller(HTTPFETCH_DISCARD)
  38. {
  39. }
  40. ClientMediaDownloader::~ClientMediaDownloader()
  41. {
  42. if (m_httpfetch_caller != HTTPFETCH_DISCARD)
  43. httpfetch_caller_free(m_httpfetch_caller);
  44. for (auto &file_it : m_files)
  45. delete file_it.second;
  46. for (auto &remote : m_remotes)
  47. delete remote;
  48. }
  49. void ClientMediaDownloader::addFile(const std::string &name, const std::string &sha1)
  50. {
  51. assert(!m_initial_step_done); // pre-condition
  52. // if name was already announced, ignore the new announcement
  53. if (m_files.count(name) != 0) {
  54. errorstream << "Client: ignoring duplicate media announcement "
  55. << "sent by server: \"" << name << "\""
  56. << std::endl;
  57. return;
  58. }
  59. // if name is empty or contains illegal characters, ignore the file
  60. if (name.empty() || !string_allowed(name, TEXTURENAME_ALLOWED_CHARS)) {
  61. errorstream << "Client: ignoring illegal file name "
  62. << "sent by server: \"" << name << "\""
  63. << std::endl;
  64. return;
  65. }
  66. // length of sha1 must be exactly 20 (160 bits), else ignore the file
  67. if (sha1.size() != 20) {
  68. errorstream << "Client: ignoring illegal SHA1 sent by server: "
  69. << hex_encode(sha1) << " \"" << name << "\""
  70. << std::endl;
  71. return;
  72. }
  73. FileStatus *filestatus = new FileStatus();
  74. filestatus->received = false;
  75. filestatus->sha1 = sha1;
  76. filestatus->current_remote = -1;
  77. m_files.insert(std::make_pair(name, filestatus));
  78. }
  79. void ClientMediaDownloader::addRemoteServer(const std::string &baseurl)
  80. {
  81. assert(!m_initial_step_done); // pre-condition
  82. #ifdef USE_CURL
  83. if (g_settings->getBool("enable_remote_media_server")) {
  84. infostream << "Client: Adding remote server \""
  85. << baseurl << "\" for media download" << std::endl;
  86. RemoteServerStatus *remote = new RemoteServerStatus();
  87. remote->baseurl = baseurl;
  88. remote->active_count = 0;
  89. remote->request_by_filename = false;
  90. m_remotes.push_back(remote);
  91. }
  92. #else
  93. infostream << "Client: Ignoring remote server \""
  94. << baseurl << "\" because cURL support is not compiled in"
  95. << std::endl;
  96. #endif
  97. }
  98. void ClientMediaDownloader::step(Client *client)
  99. {
  100. if (!m_initial_step_done) {
  101. initialStep(client);
  102. m_initial_step_done = true;
  103. }
  104. // Remote media: check for completion of fetches
  105. if (m_httpfetch_active) {
  106. bool fetched_something = false;
  107. HTTPFetchResult fetch_result;
  108. while (httpfetch_async_get(m_httpfetch_caller, fetch_result)) {
  109. m_httpfetch_active--;
  110. fetched_something = true;
  111. // Is this a hashset (index.mth) or a media file?
  112. if (fetch_result.request_id < m_remotes.size())
  113. remoteHashSetReceived(fetch_result);
  114. else
  115. remoteMediaReceived(fetch_result, client);
  116. }
  117. if (fetched_something)
  118. startRemoteMediaTransfers();
  119. // Did all remote transfers end and no new ones can be started?
  120. // If so, request still missing files from the minetest server
  121. // (Or report that we have all files.)
  122. if (m_httpfetch_active == 0) {
  123. if (m_uncached_received_count < m_uncached_count) {
  124. infostream << "Client: Failed to remote-fetch "
  125. << (m_uncached_count-m_uncached_received_count)
  126. << " files. Requesting them"
  127. << " the usual way." << std::endl;
  128. }
  129. startConventionalTransfers(client);
  130. }
  131. }
  132. }
  133. void ClientMediaDownloader::initialStep(Client *client)
  134. {
  135. // Check media cache
  136. m_uncached_count = m_files.size();
  137. for (auto &file_it : m_files) {
  138. std::string name = file_it.first;
  139. FileStatus *filestatus = file_it.second;
  140. const std::string &sha1 = filestatus->sha1;
  141. std::ostringstream tmp_os(std::ios_base::binary);
  142. bool found_in_cache = m_media_cache.load(hex_encode(sha1), tmp_os);
  143. // If found in cache, try to load it from there
  144. if (found_in_cache) {
  145. bool success = checkAndLoad(name, sha1,
  146. tmp_os.str(), true, client);
  147. if (success) {
  148. filestatus->received = true;
  149. m_uncached_count--;
  150. }
  151. }
  152. }
  153. assert(m_uncached_received_count == 0);
  154. // Create the media cache dir if we are likely to write to it
  155. if (m_uncached_count != 0) {
  156. bool did = fs::CreateAllDirs(getMediaCacheDir());
  157. if (!did) {
  158. errorstream << "Client: "
  159. << "Could not create media cache directory: "
  160. << getMediaCacheDir()
  161. << std::endl;
  162. }
  163. }
  164. // If we found all files in the cache, report this fact to the server.
  165. // If the server reported no remote servers, immediately start
  166. // conventional transfers. Note: if cURL support is not compiled in,
  167. // m_remotes is always empty, so "!USE_CURL" is redundant but may
  168. // reduce the size of the compiled code
  169. if (!USE_CURL || m_uncached_count == 0 || m_remotes.empty()) {
  170. startConventionalTransfers(client);
  171. }
  172. else {
  173. // Otherwise start off by requesting each server's sha1 set
  174. // This is the first time we use httpfetch, so alloc a caller ID
  175. m_httpfetch_caller = httpfetch_caller_alloc();
  176. m_httpfetch_timeout = g_settings->getS32("curl_timeout");
  177. // Set the active fetch limit to curl_parallel_limit or 84,
  178. // whichever is greater. This gives us some leeway so that
  179. // inefficiencies in communicating with the httpfetch thread
  180. // don't slow down fetches too much. (We still want some limit
  181. // so that when the first remote server returns its hash set,
  182. // not all files are requested from that server immediately.)
  183. // One such inefficiency is that ClientMediaDownloader::step()
  184. // is only called a couple times per second, while httpfetch
  185. // might return responses much faster than that.
  186. // Note that httpfetch strictly enforces curl_parallel_limit
  187. // but at no inter-thread communication cost. This however
  188. // doesn't help with the aforementioned inefficiencies.
  189. // The signifance of 84 is that it is 2*6*9 in base 13.
  190. m_httpfetch_active_limit = g_settings->getS32("curl_parallel_limit");
  191. m_httpfetch_active_limit = MYMAX(m_httpfetch_active_limit, 84);
  192. // Write a list of hashes that we need. This will be POSTed
  193. // to the server using Content-Type: application/octet-stream
  194. std::string required_hash_set = serializeRequiredHashSet();
  195. // minor fixme: this loop ignores m_httpfetch_active_limit
  196. // another minor fixme, unlikely to matter in normal usage:
  197. // these index.mth fetches do (however) count against
  198. // m_httpfetch_active_limit when starting actual media file
  199. // requests, so if there are lots of remote servers that are
  200. // not responding, those will stall new media file transfers.
  201. for (u32 i = 0; i < m_remotes.size(); ++i) {
  202. assert(m_httpfetch_next_id == i);
  203. RemoteServerStatus *remote = m_remotes[i];
  204. actionstream << "Client: Contacting remote server \""
  205. << remote->baseurl << "\"" << std::endl;
  206. HTTPFetchRequest fetch_request;
  207. fetch_request.url =
  208. remote->baseurl + MTHASHSET_FILE_NAME;
  209. fetch_request.caller = m_httpfetch_caller;
  210. fetch_request.request_id = m_httpfetch_next_id; // == i
  211. fetch_request.timeout = m_httpfetch_timeout;
  212. fetch_request.connect_timeout = m_httpfetch_timeout;
  213. fetch_request.post_data = required_hash_set;
  214. fetch_request.extra_headers.emplace_back(
  215. "Content-Type: application/octet-stream");
  216. httpfetch_async(fetch_request);
  217. m_httpfetch_active++;
  218. m_httpfetch_next_id++;
  219. m_outstanding_hash_sets++;
  220. }
  221. }
  222. }
  223. void ClientMediaDownloader::remoteHashSetReceived(
  224. const HTTPFetchResult &fetch_result)
  225. {
  226. u32 remote_id = fetch_result.request_id;
  227. assert(remote_id < m_remotes.size());
  228. RemoteServerStatus *remote = m_remotes[remote_id];
  229. m_outstanding_hash_sets--;
  230. if (fetch_result.succeeded) {
  231. try {
  232. // Server sent a list of file hashes that are
  233. // available on it, try to parse the list
  234. std::set<std::string> sha1_set;
  235. deSerializeHashSet(fetch_result.data, sha1_set);
  236. // Parsing succeeded: For every file that is
  237. // available on this server, add this server
  238. // to the available_remotes array
  239. for(std::map<std::string, FileStatus*>::iterator
  240. it = m_files.upper_bound(m_name_bound);
  241. it != m_files.end(); ++it) {
  242. FileStatus *f = it->second;
  243. if (!f->received && sha1_set.count(f->sha1))
  244. f->available_remotes.push_back(remote_id);
  245. }
  246. }
  247. catch (SerializationError &e) {
  248. infostream << "Client: Remote server \""
  249. << remote->baseurl << "\" sent invalid hash set: "
  250. << e.what() << std::endl;
  251. }
  252. }
  253. // For compatibility: If index.mth is not found, assume that the
  254. // server contains files named like the original files (not their sha1)
  255. // Do NOT check for any particular response code (e.g. 404) here,
  256. // because different servers respond differently
  257. if (!fetch_result.succeeded && !fetch_result.timeout) {
  258. infostream << "Client: Enabling compatibility mode for remote "
  259. << "server \"" << remote->baseurl << "\"" << std::endl;
  260. remote->request_by_filename = true;
  261. // Assume every file is available on this server
  262. for(std::map<std::string, FileStatus*>::iterator
  263. it = m_files.upper_bound(m_name_bound);
  264. it != m_files.end(); ++it) {
  265. FileStatus *f = it->second;
  266. if (!f->received)
  267. f->available_remotes.push_back(remote_id);
  268. }
  269. }
  270. }
  271. void ClientMediaDownloader::remoteMediaReceived(
  272. const HTTPFetchResult &fetch_result,
  273. Client *client)
  274. {
  275. // Some remote server sent us a file.
  276. // -> decrement number of active fetches
  277. // -> mark file as received if fetch succeeded
  278. // -> try to load media
  279. std::string name;
  280. {
  281. std::unordered_map<unsigned long, std::string>::iterator it =
  282. m_remote_file_transfers.find(fetch_result.request_id);
  283. assert(it != m_remote_file_transfers.end());
  284. name = it->second;
  285. m_remote_file_transfers.erase(it);
  286. }
  287. sanity_check(m_files.count(name) != 0);
  288. FileStatus *filestatus = m_files[name];
  289. sanity_check(!filestatus->received);
  290. sanity_check(filestatus->current_remote >= 0);
  291. RemoteServerStatus *remote = m_remotes[filestatus->current_remote];
  292. filestatus->current_remote = -1;
  293. remote->active_count--;
  294. // If fetch succeeded, try to load media file
  295. if (fetch_result.succeeded) {
  296. bool success = checkAndLoad(name, filestatus->sha1,
  297. fetch_result.data, false, client);
  298. if (success) {
  299. filestatus->received = true;
  300. assert(m_uncached_received_count < m_uncached_count);
  301. m_uncached_received_count++;
  302. }
  303. }
  304. }
  305. s32 ClientMediaDownloader::selectRemoteServer(FileStatus *filestatus)
  306. {
  307. // Pre-conditions
  308. assert(filestatus != NULL);
  309. assert(!filestatus->received);
  310. assert(filestatus->current_remote < 0);
  311. if (filestatus->available_remotes.empty())
  312. return -1;
  313. // Of all servers that claim to provide the file (and haven't
  314. // been unsuccessfully tried before), find the one with the
  315. // smallest number of currently active transfers
  316. s32 best = 0;
  317. s32 best_remote_id = filestatus->available_remotes[best];
  318. s32 best_active_count = m_remotes[best_remote_id]->active_count;
  319. for (u32 i = 1; i < filestatus->available_remotes.size(); ++i) {
  320. s32 remote_id = filestatus->available_remotes[i];
  321. s32 active_count = m_remotes[remote_id]->active_count;
  322. if (active_count < best_active_count) {
  323. best = i;
  324. best_remote_id = remote_id;
  325. best_active_count = active_count;
  326. }
  327. }
  328. filestatus->available_remotes.erase(
  329. filestatus->available_remotes.begin() + best);
  330. return best_remote_id;
  331. }
  332. void ClientMediaDownloader::startRemoteMediaTransfers()
  333. {
  334. bool changing_name_bound = true;
  335. for (std::map<std::string, FileStatus*>::iterator
  336. files_iter = m_files.upper_bound(m_name_bound);
  337. files_iter != m_files.end(); ++files_iter) {
  338. // Abort if active fetch limit is exceeded
  339. if (m_httpfetch_active >= m_httpfetch_active_limit)
  340. break;
  341. const std::string &name = files_iter->first;
  342. FileStatus *filestatus = files_iter->second;
  343. if (!filestatus->received && filestatus->current_remote < 0) {
  344. // File has not been received yet and is not currently
  345. // being transferred. Choose a server for it.
  346. s32 remote_id = selectRemoteServer(filestatus);
  347. if (remote_id >= 0) {
  348. // Found a server, so start fetching
  349. RemoteServerStatus *remote =
  350. m_remotes[remote_id];
  351. std::string url = remote->baseurl +
  352. (remote->request_by_filename ? name :
  353. hex_encode(filestatus->sha1));
  354. verbosestream << "Client: "
  355. << "Requesting remote media file "
  356. << "\"" << name << "\" "
  357. << "\"" << url << "\"" << std::endl;
  358. HTTPFetchRequest fetch_request;
  359. fetch_request.url = url;
  360. fetch_request.caller = m_httpfetch_caller;
  361. fetch_request.request_id = m_httpfetch_next_id;
  362. fetch_request.timeout = 0; // no data timeout!
  363. fetch_request.connect_timeout =
  364. m_httpfetch_timeout;
  365. httpfetch_async(fetch_request);
  366. m_remote_file_transfers.insert(std::make_pair(
  367. m_httpfetch_next_id,
  368. name));
  369. filestatus->current_remote = remote_id;
  370. remote->active_count++;
  371. m_httpfetch_active++;
  372. m_httpfetch_next_id++;
  373. }
  374. }
  375. if (filestatus->received ||
  376. (filestatus->current_remote < 0 &&
  377. !m_outstanding_hash_sets)) {
  378. // If we arrive here, we conclusively know that we
  379. // won't fetch this file from a remote server in the
  380. // future. So update the name bound if possible.
  381. if (changing_name_bound)
  382. m_name_bound = name;
  383. }
  384. else
  385. changing_name_bound = false;
  386. }
  387. }
  388. void ClientMediaDownloader::startConventionalTransfers(Client *client)
  389. {
  390. assert(m_httpfetch_active == 0); // pre-condition
  391. if (m_uncached_received_count != m_uncached_count) {
  392. // Some media files have not been received yet, use the
  393. // conventional slow method (minetest protocol) to get them
  394. std::vector<std::string> file_requests;
  395. for (auto &file : m_files) {
  396. if (!file.second->received)
  397. file_requests.push_back(file.first);
  398. }
  399. assert((s32) file_requests.size() ==
  400. m_uncached_count - m_uncached_received_count);
  401. client->request_media(file_requests);
  402. }
  403. }
  404. void ClientMediaDownloader::conventionalTransferDone(
  405. const std::string &name,
  406. const std::string &data,
  407. Client *client)
  408. {
  409. // Check that file was announced
  410. std::map<std::string, FileStatus*>::iterator
  411. file_iter = m_files.find(name);
  412. if (file_iter == m_files.end()) {
  413. errorstream << "Client: server sent media file that was"
  414. << "not announced, ignoring it: \"" << name << "\""
  415. << std::endl;
  416. return;
  417. }
  418. FileStatus *filestatus = file_iter->second;
  419. assert(filestatus != NULL);
  420. // Check that file hasn't already been received
  421. if (filestatus->received) {
  422. errorstream << "Client: server sent media file that we already"
  423. << "received, ignoring it: \"" << name << "\""
  424. << std::endl;
  425. return;
  426. }
  427. // Mark file as received, regardless of whether loading it works and
  428. // whether the checksum matches (because at this point there is no
  429. // other server that could send a replacement)
  430. filestatus->received = true;
  431. assert(m_uncached_received_count < m_uncached_count);
  432. m_uncached_received_count++;
  433. // Check that received file matches announced checksum
  434. // If so, load it
  435. checkAndLoad(name, filestatus->sha1, data, false, client);
  436. }
  437. bool ClientMediaDownloader::checkAndLoad(
  438. const std::string &name, const std::string &sha1,
  439. const std::string &data, bool is_from_cache, Client *client)
  440. {
  441. const char *cached_or_received = is_from_cache ? "cached" : "received";
  442. const char *cached_or_received_uc = is_from_cache ? "Cached" : "Received";
  443. std::string sha1_hex = hex_encode(sha1);
  444. // Compute actual checksum of data
  445. std::string data_sha1;
  446. {
  447. SHA1 data_sha1_calculator;
  448. data_sha1_calculator.addBytes(data.c_str(), data.size());
  449. unsigned char *data_tmpdigest = data_sha1_calculator.getDigest();
  450. data_sha1.assign((char*) data_tmpdigest, 20);
  451. free(data_tmpdigest);
  452. }
  453. // Check that received file matches announced checksum
  454. if (data_sha1 != sha1) {
  455. std::string data_sha1_hex = hex_encode(data_sha1);
  456. infostream << "Client: "
  457. << cached_or_received_uc << " media file "
  458. << sha1_hex << " \"" << name << "\" "
  459. << "mismatches actual checksum " << data_sha1_hex
  460. << std::endl;
  461. return false;
  462. }
  463. // Checksum is ok, try loading the file
  464. bool success = client->loadMedia(data, name);
  465. if (!success) {
  466. infostream << "Client: "
  467. << "Failed to load " << cached_or_received << " media: "
  468. << sha1_hex << " \"" << name << "\""
  469. << std::endl;
  470. return false;
  471. }
  472. verbosestream << "Client: "
  473. << "Loaded " << cached_or_received << " media: "
  474. << sha1_hex << " \"" << name << "\""
  475. << std::endl;
  476. // Update cache (unless we just loaded the file from the cache)
  477. if (!is_from_cache)
  478. m_media_cache.update(sha1_hex, data);
  479. return true;
  480. }
  481. /*
  482. Minetest Hashset File Format
  483. All values are stored in big-endian byte order.
  484. [u32] signature: 'MTHS'
  485. [u16] version: 1
  486. For each hash in set:
  487. [u8*20] SHA1 hash
  488. Version changes:
  489. 1 - Initial version
  490. */
  491. std::string ClientMediaDownloader::serializeRequiredHashSet()
  492. {
  493. std::ostringstream os(std::ios::binary);
  494. writeU32(os, MTHASHSET_FILE_SIGNATURE); // signature
  495. writeU16(os, 1); // version
  496. // Write list of hashes of files that have not been
  497. // received (found in cache) yet
  498. for (std::map<std::string, FileStatus*>::iterator
  499. it = m_files.begin();
  500. it != m_files.end(); ++it) {
  501. if (!it->second->received) {
  502. FATAL_ERROR_IF(it->second->sha1.size() != 20, "Invalid SHA1 size");
  503. os << it->second->sha1;
  504. }
  505. }
  506. return os.str();
  507. }
  508. void ClientMediaDownloader::deSerializeHashSet(const std::string &data,
  509. std::set<std::string> &result)
  510. {
  511. if (data.size() < 6 || data.size() % 20 != 6) {
  512. throw SerializationError(
  513. "ClientMediaDownloader::deSerializeHashSet: "
  514. "invalid hash set file size");
  515. }
  516. const u8 *data_cstr = (const u8*) data.c_str();
  517. u32 signature = readU32(&data_cstr[0]);
  518. if (signature != MTHASHSET_FILE_SIGNATURE) {
  519. throw SerializationError(
  520. "ClientMediaDownloader::deSerializeHashSet: "
  521. "invalid hash set file signature");
  522. }
  523. u16 version = readU16(&data_cstr[4]);
  524. if (version != 1) {
  525. throw SerializationError(
  526. "ClientMediaDownloader::deSerializeHashSet: "
  527. "unsupported hash set file version");
  528. }
  529. for (u32 pos = 6; pos < data.size(); pos += 20) {
  530. result.insert(data.substr(pos, 20));
  531. }
  532. }