CCDownloader-curl.cpp 31 KB

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