HttpClient-apple.mm 18 KB

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