HttpClient-apple.mm 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  1. /****************************************************************************
  2. Copyright (c) 2012 greathqy
  3. Copyright (c) 2012 cocos2d-x.org
  4. Copyright (c) 2013-2016 Chukong Technologies Inc.
  5. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
  6. http://www.cocos2d-x.org
  7. Permission is hereby granted, free of charge, to any person obtaining a copy
  8. of this software and associated documentation files (the "Software"), to deal
  9. in the Software without restriction, including without limitation the rights
  10. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. copies of the Software, and to permit persons to whom the Software is
  12. furnished to do so, subject to the following conditions:
  13. The above copyright notice and this permission notice shall be included in
  14. all copies or substantial portions of the Software.
  15. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. THE SOFTWARE.
  22. ****************************************************************************/
  23. #include "network/HttpClient.h"
  24. #include <queue>
  25. #include <errno.h>
  26. #import "network/HttpAsynConnection-apple.h"
  27. #include "network/HttpCookie.h"
  28. #include "platform/CCFileUtils.h"
  29. #include "platform/CCApplication.h"
  30. NS_CC_BEGIN
  31. namespace network {
  32. static HttpClient *_httpClient = nullptr; // pointer to singleton
  33. static int processTask(HttpClient* client, HttpRequest *request, NSString *requestType, void *stream, long *errorCode, void *headerStream, char *errorBuffer);
  34. // Worker thread
  35. void HttpClient::networkThread()
  36. {
  37. increaseThreadCount();
  38. while (true) @autoreleasepool {
  39. HttpRequest *request;
  40. // step 1: send http request if the requestQueue isn't empty
  41. {
  42. std::lock_guard<std::mutex> lock(_requestQueueMutex);
  43. while (_requestQueue.empty()) {
  44. _sleepCondition.wait(_requestQueueMutex);
  45. }
  46. request = _requestQueue.at(0);
  47. _requestQueue.erase(0);
  48. }
  49. if (request == _requestSentinel) {
  50. break;
  51. }
  52. // Create a HttpResponse object, the default setting is http access failed
  53. HttpResponse *response = new (std::nothrow) HttpResponse(request);
  54. processResponse(response, _responseMessage);
  55. // add response packet into queue
  56. _responseQueueMutex.lock();
  57. _responseQueue.pushBack(response);
  58. _responseQueueMutex.unlock();
  59. _schedulerMutex.lock();
  60. if (auto sche = _scheduler.lock())
  61. {
  62. sche->performFunctionInCocosThread(CC_CALLBACK_0(HttpClient::dispatchResponseCallbacks, this));
  63. }
  64. _schedulerMutex.unlock();
  65. }
  66. // cleanup: if worker thread received quit signal, clean up un-completed request queue
  67. _requestQueueMutex.lock();
  68. _requestQueue.clear();
  69. _requestQueueMutex.unlock();
  70. _responseQueueMutex.lock();
  71. _responseQueue.clear();
  72. _responseQueueMutex.unlock();
  73. decreaseThreadCountAndMayDeleteThis();
  74. }
  75. // Worker thread
  76. void HttpClient::networkThreadAlone(HttpRequest* request, HttpResponse* response)
  77. {
  78. increaseThreadCount();
  79. char responseMessage[RESPONSE_BUFFER_SIZE] = { 0 };
  80. processResponse(response, responseMessage);
  81. _schedulerMutex.lock();
  82. if (auto sche = _scheduler.lock())
  83. {
  84. sche->performFunctionInCocosThread([this, response, request]{
  85. const ccHttpRequestCallback& callback = request->getResponseCallback();
  86. if (callback != nullptr)
  87. {
  88. callback(this, response);
  89. }
  90. response->release();
  91. // do not release in other thread
  92. request->release();
  93. });
  94. }
  95. _schedulerMutex.unlock();
  96. decreaseThreadCountAndMayDeleteThis();
  97. }
  98. //Process Request
  99. static int processTask(HttpClient* client, HttpRequest* request, NSString* requestType, void* stream, long* responseCode, void* headerStream, char* errorBuffer)
  100. {
  101. if (nullptr == client)
  102. {
  103. strcpy(errorBuffer, "client object is invalid");
  104. return 0;
  105. }
  106. //create request with url
  107. NSString* urlstring = [NSString stringWithUTF8String:request->getUrl()];
  108. NSURL *url = [NSURL URLWithString:urlstring];
  109. NSMutableURLRequest *nsrequest = [NSMutableURLRequest requestWithURL:url
  110. cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
  111. timeoutInterval:request->getTimeout()];
  112. //set request type
  113. [nsrequest setHTTPMethod:requestType];
  114. /* get custom header data (if set) */
  115. std::vector<std::string> headers=request->getHeaders();
  116. if(!headers.empty())
  117. {
  118. /* append custom headers one by one */
  119. for (auto& header : headers)
  120. {
  121. unsigned long i = header.find(':', 0);
  122. unsigned long length = header.size();
  123. std::string field = header.substr(0, i);
  124. std::string value = header.substr(i+1, length-i);
  125. NSString *headerField = [NSString stringWithUTF8String:field.c_str()];
  126. NSString *headerValue = [NSString stringWithUTF8String:value.c_str()];
  127. [nsrequest setValue:headerValue forHTTPHeaderField:headerField];
  128. }
  129. }
  130. //if request type is post or put,set header and data
  131. if([requestType isEqual: @"POST"] || [requestType isEqual: @"PUT"])
  132. {
  133. char* requestDataBuffer = request->getRequestData();
  134. if (nullptr != requestDataBuffer && 0 != request->getRequestDataSize())
  135. {
  136. NSData *postData = [NSData dataWithBytes:requestDataBuffer length:request->getRequestDataSize()];
  137. [nsrequest setHTTPBody:postData];
  138. }
  139. }
  140. //read cookie properties from file and set cookie
  141. std::string cookieFilename = client->getCookieFilename();
  142. if(!cookieFilename.empty() && nullptr != client->getCookie())
  143. {
  144. const CookiesInfo* cookieInfo = client->getCookie()->getMatchCookie(request->getUrl());
  145. if(cookieInfo != nullptr)
  146. {
  147. NSString *domain = [NSString stringWithCString:cookieInfo->domain.c_str() encoding:[NSString defaultCStringEncoding]];
  148. NSString *path = [NSString stringWithCString:cookieInfo->path.c_str() encoding:[NSString defaultCStringEncoding]];
  149. NSString *value = [NSString stringWithCString:cookieInfo->value.c_str() encoding:[NSString defaultCStringEncoding]];
  150. NSString *name = [NSString stringWithCString:cookieInfo->name.c_str() encoding:[NSString defaultCStringEncoding]];
  151. // create the properties for a cookie
  152. NSDictionary *properties = [NSDictionary dictionaryWithObjectsAndKeys: name,NSHTTPCookieName,
  153. value, NSHTTPCookieValue, path, NSHTTPCookiePath,
  154. domain, NSHTTPCookieDomain,
  155. nil];
  156. // create the cookie from the properties
  157. NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:properties];
  158. // add the cookie to the cookie storage
  159. [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
  160. }
  161. }
  162. HttpAsynConnection *httpAsynConn = [[HttpAsynConnection new] autorelease];
  163. httpAsynConn.srcURL = urlstring;
  164. httpAsynConn.sslFile = nil;
  165. std::string sslCaFileName = client->getSSLVerification();
  166. if(!sslCaFileName.empty())
  167. {
  168. long len = sslCaFileName.length();
  169. long pos = sslCaFileName.rfind('.', len-1);
  170. httpAsynConn.sslFile = [NSString stringWithUTF8String:sslCaFileName.substr(0, pos).c_str()];
  171. }
  172. [httpAsynConn startRequest:nsrequest];
  173. while( httpAsynConn.finish != true)
  174. {
  175. [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
  176. }
  177. //if http connection return error
  178. if (httpAsynConn.connError != nil)
  179. {
  180. NSString* errorString = [httpAsynConn.connError localizedDescription];
  181. strcpy(errorBuffer, [errorString UTF8String]);
  182. return 0;
  183. }
  184. //if http response got error, just log the error
  185. if (httpAsynConn.responseError != nil)
  186. {
  187. NSString* errorString = [httpAsynConn.responseError localizedDescription];
  188. strcpy(errorBuffer, [errorString UTF8String]);
  189. }
  190. *responseCode = httpAsynConn.responseCode;
  191. //add cookie to cookies vector
  192. if(!cookieFilename.empty())
  193. {
  194. NSArray *cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:httpAsynConn.responseHeader forURL:url];
  195. for (NSHTTPCookie *cookie in cookies)
  196. {
  197. //NSLog(@"Cookie: %@", cookie);
  198. NSString *domain = cookie.domain;
  199. //BOOL session = cookie.sessionOnly;
  200. NSString *path = cookie.path;
  201. BOOL secure = cookie.isSecure;
  202. NSDate *date = cookie.expiresDate;
  203. NSString *name = cookie.name;
  204. NSString *value = cookie.value;
  205. CookiesInfo cookieInfo;
  206. cookieInfo.domain = [domain cStringUsingEncoding: NSUTF8StringEncoding];
  207. cookieInfo.path = [path cStringUsingEncoding: NSUTF8StringEncoding];
  208. cookieInfo.secure = (secure == YES) ? true : false;
  209. cookieInfo.expires = [[NSString stringWithFormat:@"%ld", (long)[date timeIntervalSince1970]] cStringUsingEncoding: NSUTF8StringEncoding];
  210. cookieInfo.name = [name cStringUsingEncoding: NSUTF8StringEncoding];
  211. cookieInfo.value = [value cStringUsingEncoding: NSUTF8StringEncoding];
  212. cookieInfo.tailmatch = true;
  213. client->getCookie()->updateOrAddCookie(&cookieInfo);
  214. }
  215. }
  216. //handle response header
  217. NSMutableString *header = [NSMutableString string];
  218. [header appendFormat:@"HTTP/1.1 %ld %@\n", (long)httpAsynConn.responseCode, httpAsynConn.statusString];
  219. for (id key in httpAsynConn.responseHeader)
  220. {
  221. [header appendFormat:@"%@: %@\n", key, [httpAsynConn.responseHeader objectForKey:key]];
  222. }
  223. if (header.length > 0)
  224. {
  225. NSRange range = NSMakeRange(header.length-1, 1);
  226. [header deleteCharactersInRange:range];
  227. }
  228. NSData *headerData = [header dataUsingEncoding:NSUTF8StringEncoding];
  229. std::vector<char> *headerBuffer = (std::vector<char>*)headerStream;
  230. const void* headerptr = [headerData bytes];
  231. long headerlen = [headerData length];
  232. headerBuffer->insert(headerBuffer->end(), (char*)headerptr, (char*)headerptr+headerlen);
  233. //handle response data
  234. std::vector<char> *recvBuffer = (std::vector<char>*)stream;
  235. const void* ptr = [httpAsynConn.responseData bytes];
  236. long len = [httpAsynConn.responseData length];
  237. recvBuffer->insert(recvBuffer->end(), (char*)ptr, (char*)ptr+len);
  238. return 1;
  239. }
  240. // HttpClient implementation
  241. HttpClient* HttpClient::getInstance()
  242. {
  243. if (_httpClient == nullptr)
  244. {
  245. _httpClient = new (std::nothrow) HttpClient();
  246. }
  247. return _httpClient;
  248. }
  249. void HttpClient::destroyInstance()
  250. {
  251. if (nullptr == _httpClient)
  252. {
  253. CCLOG("HttpClient singleton is nullptr");
  254. return;
  255. }
  256. CCLOG("HttpClient::destroyInstance begin");
  257. auto thiz = _httpClient;
  258. _httpClient = nullptr;
  259. if(auto sche = thiz->_scheduler.lock())
  260. {
  261. sche->unscheduleAllForTarget(thiz);
  262. }
  263. thiz->_schedulerMutex.lock();
  264. thiz->_scheduler.reset();
  265. thiz->_schedulerMutex.unlock();
  266. thiz->_requestQueueMutex.lock();
  267. thiz->_requestQueue.pushBack(thiz->_requestSentinel);
  268. thiz->_requestQueueMutex.unlock();
  269. thiz->_sleepCondition.notify_one();
  270. thiz->decreaseThreadCountAndMayDeleteThis();
  271. CCLOG("HttpClient::destroyInstance() finished!");
  272. }
  273. void HttpClient::enableCookies(const char* cookieFile)
  274. {
  275. _cookieFileMutex.lock();
  276. if (cookieFile)
  277. {
  278. _cookieFilename = std::string(cookieFile);
  279. _cookieFilename = FileUtils::getInstance()->fullPathForFilename(_cookieFilename);
  280. }
  281. else
  282. {
  283. _cookieFilename = (FileUtils::getInstance()->getWritablePath() + "cookieFile.txt");
  284. }
  285. _cookieFileMutex.unlock();
  286. if (nullptr == _cookie)
  287. {
  288. _cookie = new(std::nothrow)HttpCookie;
  289. }
  290. _cookie->setCookieFileName(_cookieFilename);
  291. _cookie->readFile();
  292. }
  293. void HttpClient::setSSLVerification(const std::string& caFile)
  294. {
  295. std::lock_guard<std::mutex> lock(_sslCaFileMutex);
  296. _sslCaFilename = caFile;
  297. }
  298. HttpClient::HttpClient()
  299. : _isInited(false)
  300. , _timeoutForConnect(30)
  301. , _timeoutForRead(60)
  302. , _threadCount(0)
  303. , _cookie(nullptr)
  304. , _requestSentinel(new HttpRequest())
  305. {
  306. CCLOG("In the constructor of HttpClient!");
  307. memset(_responseMessage, 0, sizeof(char) * RESPONSE_BUFFER_SIZE);
  308. _scheduler = Application::getInstance()->getScheduler();
  309. increaseThreadCount();
  310. }
  311. HttpClient::~HttpClient()
  312. {
  313. CC_SAFE_RELEASE(_requestSentinel);
  314. if (!_cookieFilename.empty() && nullptr != _cookie)
  315. {
  316. _cookie->writeFile();
  317. CC_SAFE_DELETE(_cookie);
  318. }
  319. CCLOG("HttpClient destructor");
  320. }
  321. //Lazy create semaphore & mutex & thread
  322. bool HttpClient::lazyInitThreadSemaphore()
  323. {
  324. if (_isInited)
  325. {
  326. return true;
  327. }
  328. else
  329. {
  330. auto t = std::thread(CC_CALLBACK_0(HttpClient::networkThread, this));
  331. t.detach();
  332. _isInited = true;
  333. }
  334. return true;
  335. }
  336. //Add a get task to queue
  337. void HttpClient::send(HttpRequest* request)
  338. {
  339. if (false == lazyInitThreadSemaphore())
  340. {
  341. return;
  342. }
  343. if (!request)
  344. {
  345. return;
  346. }
  347. request->retain();
  348. _requestQueueMutex.lock();
  349. _requestQueue.pushBack(request);
  350. _requestQueueMutex.unlock();
  351. // Notify thread start to work
  352. _sleepCondition.notify_one();
  353. }
  354. void HttpClient::sendImmediate(HttpRequest* request)
  355. {
  356. if(!request)
  357. {
  358. return;
  359. }
  360. request->retain();
  361. // Create a HttpResponse object, the default setting is http access failed
  362. HttpResponse *response = new (std::nothrow) HttpResponse(request);
  363. auto t = std::thread(&HttpClient::networkThreadAlone, this, request, response);
  364. t.detach();
  365. }
  366. // Poll and notify main thread if responses exists in queue
  367. void HttpClient::dispatchResponseCallbacks()
  368. {
  369. // log("CCHttpClient::dispatchResponseCallbacks is running");
  370. //occurs when cocos thread fires but the network thread has already quited
  371. HttpResponse* response = nullptr;
  372. _responseQueueMutex.lock();
  373. if (!_responseQueue.empty())
  374. {
  375. response = _responseQueue.at(0);
  376. _responseQueue.erase(0);
  377. }
  378. _responseQueueMutex.unlock();
  379. if (response)
  380. {
  381. HttpRequest *request = response->getHttpRequest();
  382. const ccHttpRequestCallback& callback = request->getResponseCallback();
  383. if (callback != nullptr)
  384. {
  385. callback(this, response);
  386. }
  387. response->release();
  388. // do not release in other thread
  389. request->release();
  390. }
  391. }
  392. // Process Response
  393. void HttpClient::processResponse(HttpResponse* response, char* responseMessage)
  394. {
  395. auto request = response->getHttpRequest();
  396. long responseCode = -1;
  397. int retValue = 0;
  398. NSString* requestType = nil;
  399. // Process the request -> get response packet
  400. switch (request->getRequestType())
  401. {
  402. case HttpRequest::Type::GET: // HTTP GET
  403. requestType = @"GET";
  404. break;
  405. case HttpRequest::Type::POST: // HTTP POST
  406. requestType = @"POST";
  407. break;
  408. case HttpRequest::Type::PUT:
  409. requestType = @"PUT";
  410. break;
  411. case HttpRequest::Type::DELETE:
  412. requestType = @"DELETE";
  413. break;
  414. default:
  415. CCASSERT(false, "CCHttpClient: unknown request type, only GET,POST,PUT or DELETE is supported");
  416. break;
  417. }
  418. retValue = processTask(this,
  419. request,
  420. requestType,
  421. response->getResponseData(),
  422. &responseCode,
  423. response->getResponseHeader(),
  424. responseMessage);
  425. // write data to HttpResponse
  426. response->setResponseCode(responseCode);
  427. if (retValue != 0)
  428. {
  429. response->setSucceed(true);
  430. }
  431. else
  432. {
  433. response->setSucceed(false);
  434. response->setErrorBuffer(responseMessage);
  435. }
  436. }
  437. void HttpClient::increaseThreadCount()
  438. {
  439. _threadCountMutex.lock();
  440. ++_threadCount;
  441. _threadCountMutex.unlock();
  442. }
  443. void HttpClient::decreaseThreadCountAndMayDeleteThis()
  444. {
  445. bool needDeleteThis = false;
  446. _threadCountMutex.lock();
  447. --_threadCount;
  448. if (0 == _threadCount)
  449. {
  450. needDeleteThis = true;
  451. }
  452. _threadCountMutex.unlock();
  453. if (needDeleteThis)
  454. {
  455. delete this;
  456. }
  457. }
  458. void HttpClient::setTimeoutForConnect(int value)
  459. {
  460. std::lock_guard<std::mutex> lock(_timeoutForConnectMutex);
  461. _timeoutForConnect = value;
  462. }
  463. int HttpClient::getTimeoutForConnect()
  464. {
  465. std::lock_guard<std::mutex> lock(_timeoutForConnectMutex);
  466. return _timeoutForConnect;
  467. }
  468. void HttpClient::setTimeoutForRead(int value)
  469. {
  470. std::lock_guard<std::mutex> lock(_timeoutForReadMutex);
  471. _timeoutForRead = value;
  472. }
  473. int HttpClient::getTimeoutForRead()
  474. {
  475. std::lock_guard<std::mutex> lock(_timeoutForReadMutex);
  476. return _timeoutForRead;
  477. }
  478. const std::string& HttpClient::getCookieFilename()
  479. {
  480. std::lock_guard<std::mutex> lock(_cookieFileMutex);
  481. return _cookieFilename;
  482. }
  483. const std::string& HttpClient::getSSLVerification()
  484. {
  485. std::lock_guard<std::mutex> lock(_sslCaFileMutex);
  486. return _sslCaFilename;
  487. }
  488. }
  489. NS_CC_END