CCDownloader-curl.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857
  1. /****************************************************************************
  2. Copyright (c) 2015-2016 Chukong Technologies Inc.
  3. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
  4. http://www.cocos2d-x.org
  5. Permission is hereby granted, free of charge, to any person obtaining a copy
  6. of this software and associated documentation files (the "Software"), to deal
  7. in the Software without restriction, including without limitation the rights
  8. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. copies of the Software, and to permit persons to whom the Software is
  10. furnished to do so, subject to the following conditions:
  11. The above copyright notice and this permission notice shall be included in
  12. all copies or substantial portions of the Software.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. THE SOFTWARE.
  20. ****************************************************************************/
  21. #include "network/CCDownloader-curl.h"
  22. #include <set>
  23. #include <curl/curl.h>
  24. #include "base/CCDirector.h"
  25. #include "base/CCScheduler.h"
  26. #include "platform/CCFileUtils.h"
  27. #include "network/CCDownloader.h"
  28. // **NOTE**
  29. // In the file:
  30. // member function with suffix "Proc" designed called in DownloaderCURL::_threadProc
  31. // member function without suffix designed called in main thread
  32. namespace cocos2d { namespace network {
  33. using namespace std;
  34. ////////////////////////////////////////////////////////////////////////////////
  35. // Implementation DownloadTaskCURL
  36. class DownloadTaskCURL : public IDownloadTask
  37. {
  38. static int _sSerialId;
  39. // if more than one task write to one file, cause file broken
  40. // so use a set to check this situation
  41. static set<string> _sStoragePathSet;
  42. public:
  43. int serialId;
  44. DownloadTaskCURL()
  45. : serialId(_sSerialId++)
  46. , _fp(nullptr)
  47. {
  48. _initInternal();
  49. DLLOG("Construct DownloadTaskCURL %p", this);
  50. }
  51. virtual ~DownloadTaskCURL()
  52. {
  53. // if task destroyed unnormally, we should release WritenFileName stored in set.
  54. // Normally, this action should done when task finished.
  55. if (_tempFileName.length() && _sStoragePathSet.end() != _sStoragePathSet.find(_tempFileName))
  56. {
  57. DownloadTaskCURL::_sStoragePathSet.erase(_tempFileName);
  58. }
  59. if (_fp)
  60. {
  61. fclose(_fp);
  62. _fp = nullptr;
  63. }
  64. DLLOG("Destruct DownloadTaskCURL %p", this);
  65. }
  66. bool init(const string& filename, const string& tempSuffix)
  67. {
  68. if (0 == filename.length())
  69. {
  70. // data task
  71. _buf.reserve(CURL_MAX_WRITE_SIZE);
  72. return true;
  73. }
  74. // file task
  75. _fileName = filename;
  76. _tempFileName = filename;
  77. _tempFileName.append(tempSuffix);
  78. if (_sStoragePathSet.end() != _sStoragePathSet.find(_tempFileName))
  79. {
  80. // there is another task uses this storage path
  81. _errCode = DownloadTask::ERROR_FILE_OP_FAILED;
  82. _errCodeInternal = 0;
  83. _errDescription = "More than one download file task write to same file:";
  84. _errDescription.append(_tempFileName);
  85. return false;
  86. }
  87. _sStoragePathSet.insert(_tempFileName);
  88. // open temp file handle for write
  89. bool ret = false;
  90. do
  91. {
  92. string dir;
  93. size_t found = _tempFileName.find_last_of("/\\");
  94. if (found == string::npos)
  95. {
  96. _errCode = DownloadTask::ERROR_INVALID_PARAMS;
  97. _errCodeInternal = 0;
  98. _errDescription = "Can't find dirname in storagePath.";
  99. break;
  100. }
  101. // ensure directory is exist
  102. auto util = FileUtils::getInstance();
  103. dir = _tempFileName.substr(0, found+1);
  104. if (false == util->isDirectoryExist(dir))
  105. {
  106. if (false == util->createDirectory(dir))
  107. {
  108. _errCode = DownloadTask::ERROR_FILE_OP_FAILED;
  109. _errCodeInternal = 0;
  110. _errDescription = "Can't create dir:";
  111. _errDescription.append(dir);
  112. break;
  113. }
  114. }
  115. // open file
  116. _fp = fopen(util->getSuitableFOpen(_tempFileName).c_str(), "ab");
  117. if (nullptr == _fp)
  118. {
  119. _errCode = DownloadTask::ERROR_FILE_OP_FAILED;
  120. _errCodeInternal = 0;
  121. _errDescription = "Can't open file:";
  122. _errDescription.append(_tempFileName);
  123. }
  124. ret = true;
  125. } while (0);
  126. return ret;
  127. }
  128. void initProc()
  129. {
  130. lock_guard<mutex> lock(_mutex);
  131. _initInternal();
  132. }
  133. void setErrorProc(int code, int codeInternal, const char *desc)
  134. {
  135. lock_guard<mutex> lock(_mutex);
  136. _errCode = code;
  137. _errCodeInternal = codeInternal;
  138. _errDescription = desc;
  139. }
  140. size_t writeDataProc(unsigned char *buffer, size_t size, size_t count)
  141. {
  142. lock_guard<mutex> lock(_mutex);
  143. size_t ret = 0;
  144. if (_fp)
  145. {
  146. ret = fwrite(buffer, size, count, _fp);
  147. }
  148. else
  149. {
  150. ret = size * count;
  151. auto cap = _buf.capacity();
  152. auto bufSize = _buf.size();
  153. if (cap < bufSize + ret)
  154. {
  155. _buf.reserve(bufSize * 2);
  156. }
  157. _buf.insert(_buf.end() , buffer, buffer + ret);
  158. }
  159. if (ret)
  160. {
  161. _bytesReceived += ret;
  162. _totalBytesReceived += ret;
  163. }
  164. return ret;
  165. }
  166. private:
  167. friend class DownloaderCURL;
  168. // for lock object instance
  169. mutex _mutex;
  170. // header info
  171. bool _acceptRanges;
  172. bool _headerAchieved;
  173. int64_t _totalBytesExpected;
  174. string _header; // temp buffer for receive header string, only used in thread proc
  175. // progress
  176. int64_t _bytesReceived;
  177. int64_t _totalBytesReceived;
  178. // error
  179. int _errCode;
  180. int _errCodeInternal;
  181. string _errDescription;
  182. // for saving data
  183. string _fileName;
  184. string _tempFileName;
  185. vector<unsigned char> _buf;
  186. FILE* _fp;
  187. void _initInternal()
  188. {
  189. _acceptRanges = (false);
  190. _headerAchieved = (false);
  191. _bytesReceived = (0);
  192. _totalBytesReceived = (0);
  193. _totalBytesExpected = (0);
  194. _errCode = (DownloadTask::ERROR_NO_ERROR);
  195. _errCodeInternal = (CURLE_OK);
  196. _header.resize(0);
  197. _header.reserve(384); // pre alloc header string buffer
  198. }
  199. };
  200. int DownloadTaskCURL::_sSerialId;
  201. set<string> DownloadTaskCURL::_sStoragePathSet;
  202. typedef pair< shared_ptr<const DownloadTask>, DownloadTaskCURL *> TaskWrapper;
  203. ////////////////////////////////////////////////////////////////////////////////
  204. // Implementation DownloaderCURL::Impl
  205. // This class shared by DownloaderCURL and work thread.
  206. class DownloaderCURL::Impl : public enable_shared_from_this<DownloaderCURL::Impl>
  207. {
  208. public:
  209. DownloaderHints hints;
  210. Impl()
  211. // : _thread(nullptr)
  212. {
  213. DLLOG("Construct DownloaderCURL::Impl %p", this);
  214. }
  215. ~Impl()
  216. {
  217. DLLOG("Destruct DownloaderCURL::Impl %p %d", this, _thread.joinable());
  218. }
  219. void addTask(std::shared_ptr<const DownloadTask> task, DownloadTaskCURL* coTask)
  220. {
  221. if (DownloadTask::ERROR_NO_ERROR == coTask->_errCode)
  222. {
  223. lock_guard<mutex> lock(_requestMutex);
  224. _requestQueue.push_back(make_pair(task, coTask));
  225. }
  226. else
  227. {
  228. lock_guard<mutex> lock(_finishedMutex);
  229. _finishedQueue.push_back(make_pair(task, coTask));
  230. }
  231. }
  232. void run()
  233. {
  234. lock_guard<mutex> lock(_threadMutex);
  235. if (false == _thread.joinable())
  236. {
  237. thread newThread(&DownloaderCURL::Impl::_threadProc, this);
  238. _thread.swap(newThread);
  239. }
  240. }
  241. void stop()
  242. {
  243. lock_guard<mutex> lock(_threadMutex);
  244. if (_thread.joinable())
  245. {
  246. _thread.detach();
  247. }
  248. }
  249. bool stoped()
  250. {
  251. lock_guard<mutex> lock(_threadMutex);
  252. return false == _thread.joinable() ? true : false;
  253. }
  254. void getProcessTasks(vector<TaskWrapper>& outList)
  255. {
  256. lock_guard<mutex> lock(_processMutex);
  257. outList.reserve(_processSet.size());
  258. outList.insert(outList.end(), _processSet.begin(), _processSet.end());
  259. }
  260. void getFinishedTasks(vector<TaskWrapper>& outList)
  261. {
  262. lock_guard<mutex> lock(_finishedMutex);
  263. outList.reserve(_finishedQueue.size());
  264. outList.insert(outList.end(), _finishedQueue.begin(), _finishedQueue.end());
  265. _finishedQueue.clear();
  266. }
  267. private:
  268. static size_t _outputHeaderCallbackProc(void *buffer, size_t size, size_t count, void *userdata)
  269. {
  270. int strLen = int(size * count);
  271. DLLOG(" _outputHeaderCallbackProc: %.*s", strLen, buffer);
  272. DownloadTaskCURL& coTask = *((DownloadTaskCURL*)(userdata));
  273. coTask._header.append((const char *)buffer, strLen);
  274. return strLen;
  275. }
  276. static size_t _outputDataCallbackProc(void *buffer, size_t size, size_t count, void *userdata)
  277. {
  278. // DLLOG(" _outputDataCallbackProc: size(%ld), count(%ld)", size, count);
  279. DownloadTaskCURL *coTask = (DownloadTaskCURL*)userdata;
  280. // If your callback function returns CURL_WRITEFUNC_PAUSE it will cause this transfer to become paused.
  281. return coTask->writeDataProc((unsigned char *)buffer, size, count);
  282. }
  283. // this function designed call in work thread
  284. // the curl handle destroyed in _threadProc
  285. // handle inited for get header
  286. void _initCurlHandleProc(CURL *handle, TaskWrapper& wrapper, bool forContent = false)
  287. {
  288. const DownloadTask& task = *wrapper.first;
  289. const DownloadTaskCURL* coTask = wrapper.second;
  290. // set url
  291. curl_easy_setopt(handle, CURLOPT_URL, task.requestURL.c_str());
  292. // set write func
  293. if (forContent)
  294. {
  295. curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, DownloaderCURL::Impl::_outputDataCallbackProc);
  296. }
  297. else
  298. {
  299. curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, DownloaderCURL::Impl::_outputHeaderCallbackProc);
  300. }
  301. curl_easy_setopt(handle, CURLOPT_WRITEDATA, coTask);
  302. curl_easy_setopt(handle, CURLOPT_NOPROGRESS, true);
  303. // curl_easy_setopt(handle, CURLOPT_XFERINFOFUNCTION, DownloaderCURL::Impl::_progressCallbackProc);
  304. // curl_easy_setopt(handle, CURLOPT_XFERINFODATA, coTask);
  305. curl_easy_setopt(handle, CURLOPT_FAILONERROR, true);
  306. curl_easy_setopt(handle, CURLOPT_NOSIGNAL, 1L);
  307. if (forContent)
  308. {
  309. /** if server acceptRanges and local has part of file, we continue to download **/
  310. if (coTask->_acceptRanges && coTask->_totalBytesReceived > 0)
  311. {
  312. curl_easy_setopt(handle, CURLOPT_RESUME_FROM_LARGE,(curl_off_t)coTask->_totalBytesReceived);
  313. }
  314. }
  315. else
  316. {
  317. // get header options
  318. curl_easy_setopt(handle, CURLOPT_HEADER, 1);
  319. curl_easy_setopt(handle, CURLOPT_NOBODY, 1);
  320. }
  321. // if (!sProxy.empty())
  322. // {
  323. // curl_easy_setopt(curl, CURLOPT_PROXY, sProxy.c_str());
  324. // }
  325. if (hints.timeoutInSeconds)
  326. {
  327. curl_easy_setopt(handle, CURLOPT_CONNECTTIMEOUT, hints.timeoutInSeconds);
  328. }
  329. static const long LOW_SPEED_LIMIT = 1;
  330. static const long LOW_SPEED_TIME = 5;
  331. curl_easy_setopt(handle, CURLOPT_LOW_SPEED_LIMIT, LOW_SPEED_LIMIT);
  332. curl_easy_setopt(handle, CURLOPT_LOW_SPEED_TIME, LOW_SPEED_TIME);
  333. static const int MAX_REDIRS = 2;
  334. if (MAX_REDIRS)
  335. {
  336. curl_easy_setopt(handle, CURLOPT_FOLLOWLOCATION, true);
  337. curl_easy_setopt(handle, CURLOPT_MAXREDIRS, MAX_REDIRS);
  338. }
  339. }
  340. // get header info, if success set handle to content download state
  341. bool _getHeaderInfoProc(CURL *handle, TaskWrapper& wrapper)
  342. {
  343. DownloadTaskCURL& coTask = *wrapper.second;
  344. CURLcode rc = CURLE_OK;
  345. do
  346. {
  347. long httpResponseCode = 0;
  348. rc = curl_easy_getinfo(handle, CURLINFO_RESPONSE_CODE, &httpResponseCode);
  349. if (CURLE_OK != rc)
  350. {
  351. break;
  352. }
  353. if (200 != httpResponseCode)
  354. {
  355. char buf[256] = {0};
  356. sprintf(buf
  357. , "When request url(%s) header info, return unexcept http response code(%ld)"
  358. , wrapper.first->requestURL.c_str()
  359. , httpResponseCode);
  360. coTask.setErrorProc(DownloadTask::ERROR_IMPL_INTERNAL, CURLE_OK, buf);
  361. }
  362. // curl_easy_getinfo(handle, CURLINFO_EFFECTIVE_URL, &effectiveUrl);
  363. // curl_easy_getinfo(handle, CURLINFO_CONTENT_TYPE, &contentType);
  364. double contentLen = 0;
  365. rc = curl_easy_getinfo(handle, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &contentLen);
  366. if (CURLE_OK != rc)
  367. {
  368. break;
  369. }
  370. bool acceptRanges = (string::npos != coTask._header.find("Accept-Ranges")) ? true : false;
  371. // get current file size
  372. int64_t fileSize = 0;
  373. if (acceptRanges && coTask._tempFileName.length())
  374. {
  375. fileSize = FileUtils::getInstance()->getFileSize(coTask._tempFileName);
  376. }
  377. // set header info to coTask
  378. lock_guard<mutex> lock(coTask._mutex);
  379. coTask._totalBytesExpected = (int64_t)contentLen;
  380. coTask._acceptRanges = acceptRanges;
  381. if (acceptRanges && fileSize > 0)
  382. {
  383. coTask._totalBytesReceived = fileSize;
  384. }
  385. coTask._headerAchieved = true;
  386. } while (0);
  387. if (CURLE_OK != rc)
  388. {
  389. coTask.setErrorProc(DownloadTask::ERROR_IMPL_INTERNAL, rc, curl_easy_strerror(rc));
  390. }
  391. return coTask._headerAchieved;
  392. }
  393. void _threadProc()
  394. {
  395. DLLOG("++++DownloaderCURL::Impl::_threadProc begin %p", this);
  396. // the holder prevent DownloaderCURL::Impl class instance be destruct in main thread
  397. auto holder = this->shared_from_this();
  398. auto thisThreadId = this_thread::get_id();
  399. uint32_t countOfMaxProcessingTasks = this->hints.countOfMaxProcessingTasks;
  400. // init curl content
  401. CURLM* curlmHandle = curl_multi_init();
  402. unordered_map<CURL*, TaskWrapper> coTaskMap;
  403. int runningHandles = 0;
  404. CURLMcode mcode = CURLM_OK;
  405. int rc = 0; // select return code
  406. do
  407. {
  408. // check the thread should exit or not
  409. {
  410. lock_guard<mutex> lock(_threadMutex);
  411. // if the Impl stoped, this->_thread.reset will be called, thus _thread.get_id() not equal with thisThreadId
  412. if (thisThreadId != this->_thread.get_id())
  413. {
  414. break;
  415. }
  416. }
  417. if (runningHandles)
  418. {
  419. // get timeout setting from multi-handle
  420. long timeoutMS = -1;
  421. curl_multi_timeout(curlmHandle, &timeoutMS);
  422. if(timeoutMS < 0)
  423. {
  424. timeoutMS = 1000;
  425. }
  426. /* get file descriptors from the transfers */
  427. fd_set fdread;
  428. fd_set fdwrite;
  429. fd_set fdexcep;
  430. int maxfd = -1;
  431. FD_ZERO(&fdread);
  432. FD_ZERO(&fdwrite);
  433. FD_ZERO(&fdexcep);
  434. mcode = curl_multi_fdset(curlmHandle, &fdread, &fdwrite, &fdexcep, &maxfd);
  435. if (CURLM_OK != mcode)
  436. {
  437. break;
  438. }
  439. // do wait action
  440. if(maxfd == -1)
  441. {
  442. this_thread::sleep_for(chrono::milliseconds(timeoutMS));
  443. rc = 0;
  444. }
  445. else
  446. {
  447. struct timeval timeout;
  448. timeout.tv_sec = timeoutMS / 1000;
  449. timeout.tv_usec = (timeoutMS % 1000) * 1000;
  450. rc = select(maxfd+1, &fdread, &fdwrite, &fdexcep, &timeout);
  451. }
  452. if (rc < 0)
  453. {
  454. DLLOG(" _threadProc: select return unexpect code: %d", rc);
  455. }
  456. }
  457. if (coTaskMap.size())
  458. {
  459. mcode = CURLM_CALL_MULTI_PERFORM;
  460. while(CURLM_CALL_MULTI_PERFORM == mcode)
  461. {
  462. mcode = curl_multi_perform(curlmHandle, &runningHandles);
  463. }
  464. if (CURLM_OK != mcode)
  465. {
  466. break;
  467. }
  468. struct CURLMsg *m;
  469. do {
  470. int msgq = 0;
  471. m = curl_multi_info_read(curlmHandle, &msgq);
  472. if(m && (m->msg == CURLMSG_DONE))
  473. {
  474. CURL *curlHandle = m->easy_handle;
  475. CURLcode errCode = m->data.result;
  476. TaskWrapper wrapper = coTaskMap[curlHandle];
  477. // remove from multi-handle
  478. curl_multi_remove_handle(curlmHandle, curlHandle);
  479. bool reinited = false;
  480. do
  481. {
  482. if (CURLE_OK != errCode)
  483. {
  484. wrapper.second->setErrorProc(DownloadTask::ERROR_IMPL_INTERNAL, errCode, curl_easy_strerror(errCode));
  485. break;
  486. }
  487. // if the task is content download task, cleanup the handle
  488. if (wrapper.second->_headerAchieved)
  489. {
  490. break;
  491. }
  492. // the task is get header task
  493. // first, we get info from response
  494. if (false == _getHeaderInfoProc(curlHandle, wrapper))
  495. {
  496. // the error info has been set in _getHeaderInfoProc
  497. break;
  498. }
  499. // after get header info success
  500. // wrapper.second->_totalBytesReceived inited by local file size
  501. // if the local file size equal with the content size from header, the file has downloaded finish
  502. if (wrapper.second->_totalBytesReceived &&
  503. wrapper.second->_totalBytesReceived == wrapper.second->_totalBytesExpected)
  504. {
  505. // the file has download complete
  506. // break to move this task to finish queue
  507. break;
  508. }
  509. // reinit curl handle for download content
  510. curl_easy_reset(curlHandle);
  511. _initCurlHandleProc(curlHandle, wrapper, true);
  512. mcode = curl_multi_add_handle(curlmHandle, curlHandle);
  513. if (CURLM_OK != mcode)
  514. {
  515. wrapper.second->setErrorProc(DownloadTask::ERROR_IMPL_INTERNAL, mcode, curl_multi_strerror(mcode));
  516. break;
  517. }
  518. reinited = true;
  519. } while (0);
  520. if (reinited)
  521. {
  522. continue;
  523. }
  524. curl_easy_cleanup(curlHandle);
  525. DLLOG(" _threadProc task clean cur handle :%p with errCode:%d", curlHandle, errCode);
  526. // remove from coTaskMap
  527. coTaskMap.erase(curlHandle);
  528. // remove from _processSet
  529. {
  530. lock_guard<mutex> lock(_processMutex);
  531. if (_processSet.end() != _processSet.find(wrapper)) {
  532. _processSet.erase(wrapper);
  533. }
  534. }
  535. // add to finishedQueue
  536. {
  537. lock_guard<mutex> lock(_finishedMutex);
  538. _finishedQueue.push_back(wrapper);
  539. }
  540. }
  541. } while(m);
  542. }
  543. // process tasks in _requestList
  544. auto size = coTaskMap.size();
  545. while (0 == countOfMaxProcessingTasks || size < countOfMaxProcessingTasks)
  546. {
  547. // get task wrapper from request queue
  548. TaskWrapper wrapper;
  549. {
  550. lock_guard<mutex> lock(_requestMutex);
  551. if (_requestQueue.size())
  552. {
  553. wrapper = _requestQueue.front();
  554. _requestQueue.pop_front();
  555. }
  556. }
  557. // if request queue is empty, the wrapper.first is nullptr
  558. if (! wrapper.first)
  559. {
  560. break;
  561. }
  562. wrapper.second->initProc();
  563. // create curl handle from task and add into curl multi handle
  564. CURL* curlHandle = curl_easy_init();
  565. if (nullptr == curlHandle)
  566. {
  567. wrapper.second->setErrorProc(DownloadTask::ERROR_IMPL_INTERNAL, 0, "Alloc curl handle failed.");
  568. lock_guard<mutex> lock(_finishedMutex);
  569. _finishedQueue.push_back(wrapper);
  570. continue;
  571. }
  572. // init curl handle for get header info
  573. _initCurlHandleProc(curlHandle, wrapper);
  574. // add curl handle to process list
  575. mcode = curl_multi_add_handle(curlmHandle, curlHandle);
  576. if (CURLM_OK != mcode)
  577. {
  578. wrapper.second->setErrorProc(DownloadTask::ERROR_IMPL_INTERNAL, mcode, curl_multi_strerror(mcode));
  579. lock_guard<mutex> lock(_finishedMutex);
  580. _finishedQueue.push_back(wrapper);
  581. continue;
  582. }
  583. DLLOG(" _threadProc task create curl handle:%p", curlHandle);
  584. coTaskMap[curlHandle] = wrapper;
  585. lock_guard<mutex> lock(_processMutex);
  586. _processSet.insert(wrapper);
  587. }
  588. } while (coTaskMap.size());
  589. curl_multi_cleanup(curlmHandle);
  590. this->stop();
  591. DLLOG("----DownloaderCURL::Impl::_threadProc end");
  592. }
  593. thread _thread;
  594. deque<TaskWrapper> _requestQueue;
  595. set<TaskWrapper> _processSet;
  596. deque<TaskWrapper> _finishedQueue;
  597. mutex _threadMutex;
  598. mutex _requestMutex;
  599. mutex _processMutex;
  600. mutex _finishedMutex;
  601. };
  602. ////////////////////////////////////////////////////////////////////////////////
  603. // Implementation DownloaderCURL
  604. DownloaderCURL::DownloaderCURL(const DownloaderHints& hints)
  605. : _impl(std::make_shared<Impl>())
  606. , _currTask(nullptr)
  607. {
  608. DLLOG("Construct DownloaderCURL %p", this);
  609. _impl->hints = hints;
  610. _scheduler = Director::getInstance()->getScheduler();
  611. _scheduler->retain();
  612. _transferDataToBuffer = [this](void *buf, int64_t len)->int64_t
  613. {
  614. DownloadTaskCURL& coTask = *_currTask;
  615. int64_t dataLen = coTask._buf.size();
  616. if (len < dataLen)
  617. {
  618. return 0;
  619. }
  620. memcpy(buf, coTask._buf.data(), dataLen);
  621. coTask._buf.resize(0);
  622. return dataLen;
  623. };
  624. char key[128];
  625. sprintf(key, "DownloaderCURL(%p)", this);
  626. _schedulerKey = key;
  627. _scheduler->schedule(bind(&DownloaderCURL::_onSchedule, this, placeholders::_1),
  628. this,
  629. 0.1f,
  630. true,
  631. _schedulerKey);
  632. }
  633. DownloaderCURL::~DownloaderCURL()
  634. {
  635. _scheduler->unschedule(_schedulerKey, this);
  636. _scheduler->release();
  637. _impl->stop();
  638. DLLOG("Destruct DownloaderCURL %p", this);
  639. }
  640. IDownloadTask *DownloaderCURL::createCoTask(std::shared_ptr<const DownloadTask>& task)
  641. {
  642. DownloadTaskCURL *coTask = new (std::nothrow) DownloadTaskCURL;
  643. coTask->init(task->storagePath, _impl->hints.tempFileNameSuffix);
  644. DLLOG(" DownloaderCURL: createTask: Id(%d)", coTask->serialId);
  645. _impl->addTask(task, coTask);
  646. _impl->run();
  647. _scheduler->resumeTarget(this);
  648. return coTask;
  649. }
  650. void DownloaderCURL::_onSchedule(float)
  651. {
  652. vector<TaskWrapper> tasks;
  653. // update processing tasks
  654. _impl->getProcessTasks(tasks);
  655. for (auto& wrapper : tasks)
  656. {
  657. const DownloadTask& task = *wrapper.first;
  658. DownloadTaskCURL& coTask = *wrapper.second;
  659. lock_guard<mutex> lock(coTask._mutex);
  660. if (coTask._bytesReceived)
  661. {
  662. _currTask = &coTask;
  663. onTaskProgress(task,
  664. coTask._bytesReceived,
  665. coTask._totalBytesReceived,
  666. coTask._totalBytesExpected,
  667. _transferDataToBuffer);
  668. _currTask = nullptr;
  669. coTask._bytesReceived = 0;
  670. }
  671. }
  672. tasks.resize(0);
  673. // update finished tasks
  674. _impl->getFinishedTasks(tasks);
  675. if (_impl->stoped())
  676. {
  677. _scheduler->pauseTarget(this);
  678. }
  679. for (auto& wrapper : tasks)
  680. {
  681. const DownloadTask& task = *wrapper.first;
  682. DownloadTaskCURL& coTask = *wrapper.second;
  683. // if there is bytesReceived, call progress update first
  684. if (coTask._bytesReceived)
  685. {
  686. _currTask = &coTask;
  687. onTaskProgress(task,
  688. coTask._bytesReceived,
  689. coTask._totalBytesReceived,
  690. coTask._totalBytesExpected,
  691. _transferDataToBuffer);
  692. coTask._bytesReceived = 0;
  693. _currTask = nullptr;
  694. }
  695. // if file task, close file handle and rename file if needed
  696. if (coTask._fp)
  697. {
  698. fclose(coTask._fp);
  699. coTask._fp = nullptr;
  700. do
  701. {
  702. if (0 == coTask._fileName.length())
  703. {
  704. break;
  705. }
  706. auto util = FileUtils::getInstance();
  707. // if file already exist, remove it
  708. if (util->isFileExist(coTask._fileName))
  709. {
  710. if (false == util->removeFile(coTask._fileName))
  711. {
  712. coTask._errCode = DownloadTask::ERROR_FILE_OP_FAILED;
  713. coTask._errCodeInternal = 0;
  714. coTask._errDescription = "Can't remove old file: ";
  715. coTask._errDescription.append(coTask._fileName);
  716. break;
  717. }
  718. }
  719. // rename file
  720. if (util->renameFile(coTask._tempFileName, coTask._fileName))
  721. {
  722. // success, remove storage from set
  723. DownloadTaskCURL::_sStoragePathSet.erase(coTask._tempFileName);
  724. break;
  725. }
  726. // failed
  727. coTask._errCode = DownloadTask::ERROR_FILE_OP_FAILED;
  728. coTask._errCodeInternal = 0;
  729. coTask._errDescription = "Can't renamefile from: ";
  730. coTask._errDescription.append(coTask._tempFileName);
  731. coTask._errDescription.append(" to: ");
  732. coTask._errDescription.append(coTask._fileName);
  733. } while (0);
  734. }
  735. // needn't lock coTask here, because tasks has removed form _impl
  736. onTaskFinish(task, coTask._errCode, coTask._errCodeInternal, coTask._errDescription, coTask._buf);
  737. DLLOG(" DownloaderCURL: finish Task: Id(%d)", coTask.serialId);
  738. }
  739. }
  740. }} // namespace cocos2d::network