axmol/cocos/network/HttpClient.cpp

483 lines
16 KiB
C++
Raw Normal View History

/****************************************************************************
Copyright (c) 2012 greathqy
Copyright (c) 2012 cocos2d-x.org
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
Copyright (c) 2021 Bytedance Inc.
2021-06-25 08:18:32 +08:00
https://adxe.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "network/HttpClient.h"
#include <errno.h>
#include "base/ccUtils.h"
2014-04-30 08:37:36 +08:00
#include "base/CCDirector.h"
Squashed commit of the following: commit a794d107ad85667e3d754f0b6251fc864dfbf288 Author: Ricardo Quesada <ricardoquesada@gmail.com> Date: Fri May 16 14:33:49 2014 -0700 Yeah... everything compiles on win32 and wp8 commit 4740be6e4a0d16f742c27996e7ab2c100adc76af Author: Ricardo Quesada <ricardoquesada@gmail.com> Date: Fri May 16 13:58:38 2014 -0700 CCIME moved to base and compiles on Android commit ff3e1bf1eb27a01019f4e1b56d1aebbe2d385f72 Author: Ricardo Quesada <ricardoquesada@gmail.com> Date: Fri May 16 13:02:57 2014 -0700 compiles Ok for Windows Phone 8 commit 8160a4eb2ecdc61b5bd1cf56b90d2da6f11e3ebd Author: Ricardo Quesada <ricardoquesada@gmail.com> Date: Fri May 16 12:25:31 2014 -0700 fixes for Windows Phone 8 commit 418197649efc93032aee0adc205e502101cdb53d Author: Ricardo Quesada <ricardoquesada@gmail.com> Date: Fri May 16 11:15:13 2014 -0700 Compiles on Win32 commit 08813ed7cf8ac1079ffadeb1ce78ea9e833e1a33 Author: Ricardo Quesada <ricardoquesada@gmail.com> Date: Fri May 16 10:08:31 2014 -0700 Compiles on linux! commit 118896521e5b335a5257090b6863f1fb2a2002fe Author: Ricardo Quesada <ricardoquesada@gmail.com> Date: Fri May 16 09:30:42 2014 -0700 moves cocos/2d/platform -> cocos/platform commit 4fe9319d7717b0c1bccb2db0156eeb86255a89e0 Merge: bd68ec2 511295e Author: Ricardo Quesada <ricardoquesada@gmail.com> Date: Fri May 16 08:24:41 2014 -0700 Merge remote-tracking branch 'cocos2d/v3' into files commit bd68ec2f0e3a826d8b2f4b60564ba65ce766bc56 Author: Ricardo Quesada <ricardoquesada@gmail.com> Date: Thu May 15 19:36:23 2014 -0700 files in the correct directory
2014-05-17 05:36:00 +08:00
#include "platform/CCFileUtils.h"
#include "yasio/yasio.hpp"
#include "yasio/obstream.hpp"
using namespace yasio;
2014-01-02 16:25:35 +08:00
NS_CC_BEGIN
namespace network {
static HttpClient* _httpClient = nullptr; // pointer to singleton
template <typename _Cont, typename _Fty>
static void __clearQueueUnsafe(_Cont& queue, _Fty pred) {
for (auto it = queue.unsafe_begin(); it != queue.unsafe_end();) {
if (!pred || pred((*it))) {
2020-10-05 02:40:38 +08:00
(*it)->release();
it = queue.unsafe_erase(it);
} else {
2020-10-05 02:40:38 +08:00
++it;
}
}
}
// HttpClient implementation
HttpClient* HttpClient::getInstance() {
if (_httpClient == nullptr) {
_httpClient = new (std::nothrow) HttpClient();
}
return _httpClient;
}
void HttpClient::destroyInstance() {
if (nullptr == _httpClient) {
CCLOG("HttpClient singleton is nullptr");
return;
}
CCLOG("HttpClient::destroyInstance begin");
delete _httpClient;
_httpClient = nullptr;
CCLOG("HttpClient::destroyInstance() finished!");
}
void HttpClient::enableCookies(const char* cookieFile) {
2020-10-08 00:00:14 +08:00
std::lock_guard<std::recursive_mutex> lock(_cookieFileMutex);
if (cookieFile) {
_cookieFilename = cookieFile;
} else {
_cookieFilename = (FileUtils::getInstance()->getNativeWritableAbsolutePath() + "cookieFile.txt");
}
2021-07-19 12:26:25 +08:00
if (!_cookie)
_cookie = new HttpCookie();
_cookie->setCookieFileName(_cookieFilename);
_cookie->readFile();
}
void HttpClient::setSSLVerification(const std::string& caFile) {
2020-10-08 00:00:14 +08:00
std::lock_guard<std::recursive_mutex> lock(_sslCaFileMutex);
_sslCaFilename = caFile;
_service->set_option(yasio::YOPT_S_SSL_CACERT, _sslCaFilename.c_str());
2014-09-13 18:54:29 +08:00
}
HttpClient::HttpClient()
: _isInited(false)
, _dispatchOnWorkThread(false)
, _timeoutForConnect(30)
, _timeoutForRead(60)
, _cookie(nullptr)
, _clearResponsePredicate(nullptr)
{
CCLOG("In the constructor of HttpClient!");
_scheduler = Director::getInstance()->getScheduler();
_service = new yasio::io_service(HttpClient::MAX_CHANNELS);
_service->set_option(yasio::YOPT_S_DEFERRED_EVENT, 0);
_service->set_option(yasio::YOPT_S_DNS_QUERIES_TIMEOUT, 3);
_service->set_option(yasio::YOPT_S_DNS_QUERIES_TRIES, 1);
_service->start([=](yasio::event_ptr&& e) { handleNetworkEvent(e.get()); });
for (int i = 0; i < HttpClient::MAX_CHANNELS; ++i) {
_availChannelQueue.unsafe_push_back(i);
}
2021-07-19 13:43:59 +08:00
_scheduler->schedule([=](float) { dispatchResponseCallbacks(); }, this, 0, false, "#");
_isInited = true;
}
HttpClient::~HttpClient() {
2021-07-19 13:43:59 +08:00
_scheduler->unscheduleAllForTarget(this);
clearPendingResponseQueue();
clearFinishedResponseQueue();
2021-07-19 12:26:25 +08:00
if (_cookie) {
_cookie->writeFile();
delete _cookie;
}
delete _service;
CCLOG("HttpClient destructor");
}
2021-07-19 13:43:59 +08:00
void HttpClient::setDispatchOnWorkThread(bool bVal)
{
_scheduler->unscheduleAllForTarget(this);
_dispatchOnWorkThread = bVal;
if(!bVal)
_scheduler->schedule([=](float) { dispatchResponseCallbacks(); }, this, 0, false, "#");
}
void HttpClient::handleNetworkStatusChanged()
{
_service->set_option(YOPT_S_DNS_DIRTY, 1);
}
2021-09-05 22:18:42 +08:00
yasio::io_service* HttpClient::getInternalService()
{
return _service;
}
bool HttpClient::send(HttpRequest* request) {
if (!request)
return false;
auto response = new HttpResponse(request);
processResponse(response, request->getUrl());
response->release();
return true;
}
HttpResponse* HttpClient::sendSync(HttpRequest* request) {
request->setSync(true);
if (this->send(request))
return request->wait();
return nullptr;
}
int HttpClient::tryTakeAvailChannel() {
auto lck = _availChannelQueue.get_lock();
if (!_availChannelQueue.empty()) {
int channel = _availChannelQueue.front();
_availChannelQueue.pop_front();
return channel;
2014-05-21 10:44:07 +08:00
}
return -1;
2014-05-20 20:08:26 +08:00
}
void HttpClient::processResponse(HttpResponse* response, const std::string& url) {
auto channelIndex = tryTakeAvailChannel();
response->retain();
if (channelIndex != -1) {
if (response->prepareForProcess(url)) {
response->_responseHeaders.clear(); // redirect needs clear old response headers
auto& requestUri = response->getRequestUri();
auto channelHandle = _service->channel_at(channelIndex);
channelHandle->ud_.ptr = response;
_service->set_option(
YOPT_C_REMOTE_ENDPOINT, channelIndex, requestUri.getHost().c_str(), (int) requestUri.getPort());
if (requestUri.isSecure())
_service->open(channelIndex, YCK_SSL_CLIENT);
else
_service->open(channelIndex, YCK_TCP_CLIENT);
} else {
finishResponse(response);
}
} else {
2021-07-19 13:43:59 +08:00
_pendingResponseQueue.push_back(response);
}
}
void HttpClient::handleNetworkEvent(yasio::io_event* event) {
int channelIndex = event->cindex();
auto channel = _service->channel_at(event->cindex());
HttpResponse* response = (HttpResponse*) channel->ud_.ptr;
if (!response)
return;
bool responseFinished = response->isFinished();
switch (event->kind()) {
case YEK_ON_PACKET:
if (!responseFinished)
response->handleInput(event->packet());
2021-06-25 18:29:16 +08:00
if (response->isFinished()) {
response->updateInternalCode(yasio::errc::eof);
_service->close(event->cindex());
2021-06-25 18:29:16 +08:00
}
break;
case YEK_ON_OPEN:
if (event->status() == 0) {
obstream obs;
2021-06-25 08:18:32 +08:00
bool usePostData = false;
auto request = response->getHttpRequest();
switch (request->getRequestType()) {
case HttpRequest::Type::GET:
obs.write_bytes("GET");
break;
case HttpRequest::Type::POST:
obs.write_bytes("POST");
usePostData = true;
break;
case HttpRequest::Type::DELETE:
obs.write_bytes("DELETE");
break;
case HttpRequest::Type::PUT:
obs.write_bytes("PUT");
usePostData = true;
break;
default:
obs.write_bytes("GET");
break;
}
obs.write_bytes(" ");
auto& uri = response->getRequestUri();
obs.write_bytes(uri.getPath());
if (!usePostData) {
auto& query = uri.getQuery();
if (!query.empty()) {
obs.write_byte('?');
obs.write_bytes(query);
}
}
obs.write_bytes(" HTTP/1.1\r\n");
obs.write_bytes("Host: ");
obs.write_bytes(uri.getHost());
obs.write_bytes("\r\n");
// process custom headers
struct HeaderFlag {
enum {
UESR_AGENT = 1,
CONTENT_TYPE = 1 << 1,
ACCEPT = 1 << 2,
};
};
int headerFlags = 0;
auto& headers = request->getHeaders();
if (!headers.empty()) {
using namespace cxx17; // for string_view literal
for (auto& header : headers) {
obs.write_bytes(header);
obs.write_bytes("\r\n");
2021-07-05 20:42:22 +08:00
if (cxx20::ic::starts_with(cxx17::string_view{header}, "User-Agent:"_sv))
headerFlags |= HeaderFlag::UESR_AGENT;
2021-07-05 20:42:22 +08:00
else if (cxx20::ic::starts_with(cxx17::string_view{header}, "Content-Type:"_sv))
headerFlags |= HeaderFlag::CONTENT_TYPE;
else if (cxx20::ic::starts_with(cxx17::string_view{header}, "Accept:"_sv))
headerFlags |= HeaderFlag::ACCEPT;
}
}
if (_cookie) {
2021-07-19 12:26:25 +08:00
auto cookies = _cookie->checkAndGetFormatedMatchCookies(uri);
if (!cookies.empty())
{
obs.write_bytes("Cookie: ");
obs.write_bytes(cookies);
}
}
if (!(headerFlags & HeaderFlag::UESR_AGENT))
obs.write_bytes("User-Agent: yasio-http\r\n");
if (!(headerFlags & HeaderFlag::ACCEPT))
obs.write_bytes("Accept: */*;q=0.8\r\n");
if (usePostData) {
if (!(headerFlags & HeaderFlag::CONTENT_TYPE))
obs.write_bytes("Content-Type: application/x-www-form-urlencoded;charset=UTF-8\r\n");
char strContentLength[128] = {0};
auto requestData = request->getRequestData();
auto requestDataSize = request->getRequestDataSize();
sprintf(strContentLength, "Content-Length: %d\r\n\r\n", static_cast<int>(requestDataSize));
obs.write_bytes(strContentLength);
if (requestData && requestDataSize > 0)
obs.write_bytes(cxx17::string_view{requestData, static_cast<size_t>(requestDataSize)});
} else {
obs.write_bytes("\r\n");
}
_service->write(event->transport(), std::move(obs.buffer()));
auto& timerForRead = channel->get_user_timer();
timerForRead.cancel(*_service);
timerForRead.expires_from_now(std::chrono::seconds(this->_timeoutForRead));
timerForRead.async_wait(*_service, [=](io_service& s) {
2021-06-25 18:29:16 +08:00
response->updateInternalCode(yasio::errc::read_timeout);
s.close(channelIndex); // timeout
return true;
});
} else {
2021-06-25 18:29:16 +08:00
handleNetworkEOF(response, channel, event->status());
}
break;
case YEK_ON_CLOSE:
2021-06-25 18:29:16 +08:00
handleNetworkEOF(response, channel, event->status());
break;
}
}
2021-06-25 18:29:16 +08:00
void HttpClient::handleNetworkEOF(HttpResponse* response, yasio::io_channel* channel, int internalErrorCode) {
channel->get_user_timer().cancel(*_service);
2021-06-25 18:29:16 +08:00
response->updateInternalCode(internalErrorCode);
auto responseCode = response->getResponseCode();
switch (responseCode) {
case 301:
case 302:
case 307:
if (response->increaseRedirectCount() < HttpClient::MAX_REDIRECT_COUNT) {
auto iter = response->_responseHeaders.find("location");
if (iter != response->_responseHeaders.end()) {
if (responseCode == 302)
response->getHttpRequest()->setRequestType(HttpRequest::Type::GET);
CCLOG("Process url redirect (%d): %s", responseCode, iter->second.c_str());
_availChannelQueue.push_front(channel->index());
processResponse(response, iter->second);
response->release();
return;
}
}
}
finishResponse(response);
// recycle channel
channel->ud_.ptr = nullptr;
_availChannelQueue.push_front(channel->index());
// try process pending response
2021-07-19 13:43:59 +08:00
auto lck = _pendingResponseQueue.get_lock();
if (!_pendingResponseQueue.unsafe_empty())
{
auto pendingResponse = _pendingResponseQueue.unsafe_front();
_pendingResponseQueue.unsafe_pop_front();
lck.unlock();
processResponse(pendingResponse, pendingResponse->getHttpRequest()->getUrl());
pendingResponse->release();
}
}
2021-07-19 13:43:59 +08:00
// Poll and notify main thread if responses exists in queue
void HttpClient::dispatchResponseCallbacks()
{
if (_finishedResponseQueue.unsafe_empty())
return;
2021-07-19 14:49:38 +08:00
auto CC_UNUSED lck = _finishedResponseQueue.get_lock();
2021-07-19 13:43:59 +08:00
if (!_finishedResponseQueue.unsafe_empty())
{
HttpResponse* response = _finishedResponseQueue.front();
_finishedResponseQueue.pop_front();
invokeResposneCallbackAndRelease(response);
}
}
void HttpClient::finishResponse(HttpResponse* response) {
auto request = response->getHttpRequest();
auto syncState = request->getSyncState();
2021-07-19 12:26:25 +08:00
if (_cookie) {
auto cookieRange = response->getResponseHeaders().equal_range("set-cookie");
for (auto cookieIt = cookieRange.first; cookieIt != cookieRange.second; ++cookieIt)
_cookie->updateOrAddCookie(cookieIt->second, response->_requestUri);
}
if (!syncState) {
if (_dispatchOnWorkThread || std::this_thread::get_id() == Director::getInstance()->getCocos2dThreadId())
2021-07-19 13:43:59 +08:00
invokeResposneCallbackAndRelease(response);
else
2021-07-19 13:43:59 +08:00
_finishedResponseQueue.push_back(response);
} else {
syncState->set_value(response);
}
}
2021-07-19 13:43:59 +08:00
void HttpClient::invokeResposneCallbackAndRelease(HttpResponse* response)
{
HttpRequest* request = response->getHttpRequest();
const ccHttpRequestCallback& callback = request->getCallback();
Ref* pTarget = request->getTarget();
SEL_HttpResponse pSelector = request->getSelector();
if (callback != nullptr)
callback(this, response);
else if (pTarget && pSelector)
(pTarget->*pSelector)(this, response);
response->release();
}
void HttpClient::clearResponseQueue() {
2021-07-19 13:43:59 +08:00
clearPendingResponseQueue();
clearFinishedResponseQueue();
}
void HttpClient::clearPendingResponseQueue()
{
2021-07-19 14:49:38 +08:00
auto CC_UNUSED lck = _pendingResponseQueue.get_lock();
2021-07-19 13:43:59 +08:00
__clearQueueUnsafe(_pendingResponseQueue, ClearResponsePredicate{});
}
void HttpClient::clearFinishedResponseQueue() {
2021-07-19 14:49:38 +08:00
auto CC_UNUSED lck = _finishedResponseQueue.get_lock();
2021-07-19 13:43:59 +08:00
__clearQueueUnsafe(_finishedResponseQueue, ClearResponsePredicate{});
}
void HttpClient::setTimeoutForConnect(int value) {
2020-10-08 00:00:14 +08:00
std::lock_guard<std::recursive_mutex> lock(_timeoutForConnectMutex);
_timeoutForConnect = value;
_service->set_option(YOPT_S_CONNECT_TIMEOUT, value);
}
int HttpClient::getTimeoutForConnect() {
2020-10-08 00:00:14 +08:00
std::lock_guard<std::recursive_mutex> lock(_timeoutForConnectMutex);
return _timeoutForConnect;
}
void HttpClient::setTimeoutForRead(int value) {
2020-10-08 00:00:14 +08:00
std::lock_guard<std::recursive_mutex> lock(_timeoutForReadMutex);
_timeoutForRead = value;
}
int HttpClient::getTimeoutForRead() {
2020-10-08 00:00:14 +08:00
std::lock_guard<std::recursive_mutex> lock(_timeoutForReadMutex);
return _timeoutForRead;
}
const std::string& HttpClient::getCookieFilename() {
2020-10-08 00:00:14 +08:00
std::lock_guard<std::recursive_mutex> lock(_cookieFileMutex);
return _cookieFilename;
}
const std::string& HttpClient::getSSLVerification() {
2020-10-08 00:00:14 +08:00
std::lock_guard<std::recursive_mutex> lock(_sslCaFileMutex);
return _sslCaFilename;
}
} // namespace network
2014-01-02 16:25:35 +08:00
NS_CC_END