Init commit

Signed-off-by: haowei.yao <haowei.yao@alibaba-inc.com>
This commit is contained in:
haowei.yao
2017-12-27 10:03:32 +08:00
commit f6db1a27e4
112 changed files with 7050 additions and 0 deletions

44
core/src/AlibabaCloud.cc Normal file
View File

@@ -0,0 +1,44 @@
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/core/AlibabaCloud.h>
#include "Executor.h"
static AlibabaCloud::Executor * executor = nullptr;
void AlibabaCloud::InitializeSdk()
{
if (IsSdkInitialized())
return;
executor = new Executor;
executor->start();
}
bool AlibabaCloud::IsSdkInitialized()
{
return executor != nullptr;
}
void AlibabaCloud::ShutdownSdk()
{
if (!IsSdkInitialized())
return;
executor->shutdown();
delete executor;
executor = nullptr;
}

View File

@@ -0,0 +1,44 @@
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/core/AsyncCallerContext.h>
#include "Utils.h"
using namespace AlibabaCloud;
AsyncCallerContext::AsyncCallerContext() :
uuid_(GenerateUuid())
{
}
AsyncCallerContext::AsyncCallerContext(const std::string &uuid) :
uuid_(uuid)
{
}
AsyncCallerContext::~AsyncCallerContext()
{
}
std::string AsyncCallerContext::uuid()const
{
return uuid_;
}
void AsyncCallerContext::setUuid(const std::string &uuid)
{
uuid_ = uuid;
}

View File

@@ -0,0 +1,61 @@
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/core/ClientConfiguration.h>
using namespace AlibabaCloud;
ClientConfiguration::ClientConfiguration(const std::string &regionId,
const NetworkProxy &proxy):
regionId_(regionId),
proxy_(proxy),
endpoint_()
{
}
ClientConfiguration::~ClientConfiguration()
{
}
std::string ClientConfiguration::endpoint() const
{
return endpoint_;
}
NetworkProxy ClientConfiguration::proxy()const
{
return proxy_;
}
std::string ClientConfiguration::regionId()const
{
return regionId_;
}
void ClientConfiguration::setEndpoint(const std::string & endpoint)
{
endpoint_ = endpoint;
}
void ClientConfiguration::setProxy(const NetworkProxy &proxy)
{
proxy_ = proxy;
}
void ClientConfiguration::setRegionId(const std::string &regionId)
{
regionId_ = regionId;
}

313
core/src/CommonClient.cc Normal file
View File

@@ -0,0 +1,313 @@
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/core/CommonClient.h>
#include <ctime>
#include <iomanip>
#include <sstream>
#include <alibabacloud/core/location/LocationClient.h>
#include <alibabacloud/core/SimpleCredentialsProvider.h>
#include "Utils.h"
using namespace AlibabaCloud;
using namespace Location;
namespace
{
#if defined(WIN32) && defined(_MSC_VER)
# define strcasecmp _stricmp
# define strncasecmp _strnicmp
#else
# include <strings.h>
#endif
}
CommonClient::CommonClient(const Credentials &credentials, const ClientConfiguration &configuration) :
CoreClient(configuration),
credentialsProvider_(std::make_shared<SimpleCredentialsProvider>(credentials))
{
auto locationClient = std::make_shared<LocationClient>(credentials, configuration);
endpointProvider_ = std::make_shared<EndpointProvider>(locationClient, configuration.regionId(), "ecs");
}
CommonClient::CommonClient(const std::shared_ptr<CredentialsProvider>& credentialsProvider, const ClientConfiguration & configuration) :
CoreClient(configuration),
signer_(std::make_shared<HmacSha1Signer>())
{
credentialsProvider_ = credentialsProvider;
auto locationClient = std::make_shared<LocationClient>(credentialsProvider, configuration);
endpointProvider_ = std::make_shared<EndpointProvider>(locationClient, configuration.regionId(), "ecs");
}
CommonClient::CommonClient(const std::string & accessKeyId, const std::string & accessKeySecret, const ClientConfiguration & configuration) :
CoreClient(configuration),
signer_(std::make_shared<HmacSha1Signer>())
{
credentialsProvider_ = std::make_shared<SimpleCredentialsProvider>(accessKeyId, accessKeySecret);
auto locationClient = std::make_shared<LocationClient>(accessKeyId, accessKeySecret, configuration);
endpointProvider_ = std::make_shared<EndpointProvider>(locationClient, configuration.regionId(), "ecs");
}
CommonClient::~CommonClient()
{
}
CommonClient::JsonOutcome CommonClient::makeRequest(const std::string &endpoint, const CommonRequest &msg, HttpRequest::Method method)const
{
auto outcome = AttemptRequest(endpoint, msg, method);
if (outcome.isSuccess())
return JsonOutcome(std::string(outcome.result().body(),
outcome.result().bodySize()));
else
return JsonOutcome(outcome.error());
}
CommonClient::CommonResponseOutcome CommonClient::commonResponse(const CommonRequest & request) const
{
auto outcome = makeRequest(request.domain(), request, request.httpMethod());
if (outcome.isSuccess())
return CommonResponseOutcome(CommonResponse(outcome.result()));
else
return CommonResponseOutcome(Error(outcome.error()));
}
void CommonClient::commonResponseAsync(const CommonRequest & request, const CommonResponseAsyncHandler & handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, commonResponse(request), context);
};
asyncExecute(new Runnable(fn));
}
CommonClient::CommonResponseOutcomeCallable CommonClient::commonResponseCallable(const CommonRequest & request) const
{
auto task = std::make_shared<std::packaged_task<CommonResponseOutcome()>>(
[this, request]()
{
return this->commonResponse(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CoreClient::EndpointOutcome CommonClient::endpoint() const
{
return EndpointOutcome();
}
HttpRequest CommonClient::buildHttpRequest(const std::string & endpoint, const ServiceRequest & msg, HttpRequest::Method method) const
{
return buildHttpRequest(endpoint, dynamic_cast<const CommonRequest& >(msg), method);
}
HttpRequest CommonClient::buildHttpRequest(const std::string & endpoint, const CommonRequest &msg, HttpRequest::Method method) const
{
if (msg.uriPattern().empty() ||
(strcasecmp(msg.uriPattern().c_str(),"rpc") == 0))
return buildRpcHttpRequest(endpoint, msg, method);
else
return buildRoaHttpRequest(endpoint, msg, method);
}
std::string CommonClient::canonicalizedHeaders(const HttpMessage::HeaderCollection &headers)const
{
std::map <std::string, std::string> materials;
for (const auto &p : headers)
{
std::string key = p.first;
std::transform(key.begin(), key.end(), key.begin(), ::tolower);
if (key.find("x-acs-") != 0)
continue;
std::string value = p.second;
StringReplace(value, "\t", " ");
StringReplace(value, "\n", " ");
StringReplace(value, "\r", " ");
StringReplace(value, "\f", " ");
materials[key] = value;
}
if (materials.empty())
return std::string();
std::stringstream ss;
for (const auto &p : materials)
ss << p.first << ":" << p.second << "\n";
return ss.str();
}
HttpRequest CommonClient::buildRoaHttpRequest(const std::string & endpoint, const CommonRequest &msg, HttpRequest::Method method) const
{
const Credentials credentials = credentialsProvider_->getCredentials();
Url url;
url.setScheme("https");
url.setHost(endpoint);
url.setPath(msg.resourcePath());
auto params = msg.headerParameters();
std::map <std::string, std::string> queryParams;
for (const auto &p : params) {
if (!p.second.empty())
queryParams[p.first] = p.second;
}
if (!queryParams.empty()) {
std::stringstream queryString;
for (const auto &p : queryParams)
{
if (p.second.empty())
queryString << "&" << p.first;
else
queryString << "&" << p.first << "=" << p.second;
}
url.setQuery(queryString.str().substr(1));
}
HttpRequest request(url);
request.setMethod(method);
request.setHeader("Accept", "application/json");
if (msg.hasContent()) {
std::stringstream ss;
ss << msg.contentSize();
request.setHeader("Content-Length", ss.str());
request.setHeader("Content-Type", "application/octet-stream");
request.setHeader("Content-MD5", ComputeContentMD5(msg.content(), msg.contentSize()));
}
std::time_t t = std::time(nullptr);
std::stringstream date;
#if defined(__GNUG__) && __GNUC__ < 5
char tmbuff[26];
strftime(tmbuff, 26, "%a, %d %b %Y %T", std::gmtime(&t));
date << tmbuff << " GMT";
#else
date << std::put_time(std::gmtime(&t), "%a, %d %b %Y %T GMT");
#endif
request.setHeader("Date", date.str());
request.setHeader("Host", url.host());
request.setHeader("x-sdk-client", std::string("CPP/").append(ALIBABACLOUD_VERSION_STR));
request.setHeader("x-acs-region-id", configuration().regionId());
request.setHeader("x-acs-security-token", credentials.sessionToken());
request.setHeader("x-acs-signature-method", signer_->name());
request.setHeader("x-acs-signature-nonce", GenerateUuid());
request.setHeader("x-acs-signature-version", signer_->version());
request.setHeader("x-acs-version", msg.version());
std::stringstream plaintext;
plaintext << HttpMethodToString(method) << "\n"
<< request.header("Accept") << "\n"
<< request.header("Content-MD5") << "\n"
<< request.header("Content-Type") << "\n"
<< request.header("Date") << "\n"
<< canonicalizedHeaders(request.headers());
if (!url.hasQuery())
plaintext << url.path();
else
plaintext << url.path() << "?" << url.query();
std::stringstream sign;
sign << "acs "
<< credentials.accessKeyId()
<< ":"
<< signer_->generate(plaintext.str(), credentials.accessKeySecret());
request.setHeader("Authorization", sign.str());
return request;
}
std::string CommonClient::canonicalizedQuery(const std::map<std::string, std::string>& params) const
{
if (params.empty())
return std::string();
std::stringstream ss;
for (const auto &p : params)
{
std::string key = UrlEncode(p.first);
StringReplace(key, "+", "%20");
StringReplace(key, "*", "%2A");
StringReplace(key, "%7E", "~");
std::string value = UrlEncode(p.second);
StringReplace(value, "+", "%20");
StringReplace(value, "*", "%2A");
StringReplace(value, "%7E", "~");
ss << "&" << key << "=" << value;
}
return ss.str().substr(1);
}
HttpRequest CommonClient::buildRpcHttpRequest(const std::string & endpoint, const CommonRequest &msg, HttpRequest::Method method) const
{
const Credentials credentials = credentialsProvider_->getCredentials();
Url url;
url.setScheme("https");
url.setHost(endpoint);
url.setPath(msg.resourcePath());
auto params = msg.queryParameters();
std::map <std::string, std::string> queryParams;
for (const auto &p : params) {
if (!p.second.empty())
queryParams[p.first] = p.second;
}
queryParams["AccessKeyId"] = credentials.accessKeyId();
queryParams["Format"] = "JSON";
queryParams["RegionId"] = configuration().regionId();
queryParams["SecurityToken"] = credentials.sessionToken();
queryParams["SignatureMethod"] = signer_->name();
queryParams["SignatureNonce"] = GenerateUuid();
queryParams["SignatureVersion"] = signer_->version();
std::time_t t = std::time(nullptr);
std::stringstream ss;
#if defined(__GNUG__) && __GNUC__ < 5
char tmbuff[26];
strftime(tmbuff, 26, "%FT%TZ", std::gmtime(&t));
ss << tmbuff;
#else
ss << std::put_time(std::gmtime(&t), "%FT%TZ");
#endif
queryParams["Timestamp"] = ss.str();
queryParams["Version"] = msg.version();
std::stringstream plaintext;
plaintext << HttpMethodToString(method)
<< "&"
<< UrlEncode(url.path())
<< "&"
<< UrlEncode(canonicalizedQuery(queryParams));
queryParams["Signature"] = signer_->generate(plaintext.str(), credentials.accessKeySecret() + "&");
std::stringstream queryString;
for (const auto &p : queryParams)
queryString << "&" << p.first << "=" << UrlEncode(p.second);
url.setQuery(queryString.str().substr(1));
HttpRequest request(url);
request.setMethod(method);
request.setHeader("Host", url.host());
request.setHeader("x-sdk-client", std::string("CPP/").append(ALIBABACLOUD_VERSION_STR));
return request;
}

93
core/src/CommonRequest.cc Normal file
View File

@@ -0,0 +1,93 @@
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/core/CommonRequest.h>
using namespace AlibabaCloud;
CommonRequest::CommonRequest():
ServiceRequest("",""),
domain_(),
queryParams_(),
httpMethod_(HttpRequest::Get),
uriPattern_("rpc")
{
}
CommonRequest::~CommonRequest()
{}
std::string CommonRequest::domain()const
{
return domain_;
}
void CommonRequest::setDomain(const std::string &domain)
{
domain_ = domain;
}
std::string CommonRequest::uriPattern() const
{
return uriPattern_;
}
void CommonRequest::setUriPattern(const std::string & uriPattern)
{
uriPattern_ = uriPattern;
}
void CommonRequest::setHttpMethod(HttpRequest::Method method)
{
httpMethod_ = method;
}
HttpRequest::Method CommonRequest::httpMethod() const
{
return httpMethod_;
}
CommonRequest::ParameterValueType CommonRequest::queryParameter(const ParameterNameType &name)const
{
return queryParams_.at(name);
}
CommonRequest::ParameterCollection CommonRequest::queryParameters() const
{
return queryParams_;
}
void CommonRequest::setQueryParameter(const ParameterNameType &name, const ParameterValueType &value)
{
queryParams_[name] = value;
}
CommonRequest::ParameterValueType CommonRequest::headerParameter(const ParameterNameType &name)const
{
return headerParams_.at(name);
}
CommonRequest::ParameterCollection CommonRequest::headerParameters() const
{
return headerParams_;
}
void CommonRequest::setHeaderParameter(const ParameterNameType &name, const ParameterValueType &value)
{
headerParams_[name] = value;
}

View File

@@ -0,0 +1,38 @@
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/core/CommonResponse.h>
using namespace AlibabaCloud;
CommonResponse::CommonResponse() :
payload_()
{
}
CommonResponse::CommonResponse(const std::string &payload) :
payload_(payload)
{
}
CommonResponse::~CommonResponse()
{
}
std::string CommonResponse::payload() const
{
return payload_;
}

25
core/src/Config.h.in Normal file
View File

@@ -0,0 +1,25 @@
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ALIBABACLOUD_CORE_CONFIG_H_
#define ALIBABACLOUD_CORE_CONFIG_H_
// version = (major << 16) + (minor << 8) + patch
#define ALIBABACLOUD_VERSION ((@PROJECT_VERSION_MAJOR@ << 16) + (@PROJECT_VERSION_MINOR@ << 8) + @PROJECT_VERSION_PATCH@)
#define ALIBABACLOUD_VERSION_STR "@PROJECT_VERSION_MAJOR@.@PROJECT_VERSION_MINOR@.@PROJECT_VERSION_PATCH@"
#endif // !ALIBABACLOUD_CORE_CONFIG_H_

82
core/src/CoreClient.cc Normal file
View File

@@ -0,0 +1,82 @@
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/core/CoreClient.h>
#include <json/json.h>
#include <alibabacloud/core/Signer.h>
#include "CurlHttpClient.h"
#include "Executor.h"
/*!
* \class AlibabaCloud::CoreClient CoreClient.h <alibabacloud/core/CoreClient.h>
*
*/
using namespace AlibabaCloud;
CoreClient::CoreClient(const ClientConfiguration &configuration) :
configuration_(configuration),
httpClient_(new CurlHttpClient)
{
httpClient_->setProxy(configuration.proxy());
}
CoreClient::~CoreClient()
{
delete httpClient_;
}
ClientConfiguration CoreClient::configuration()const
{
return configuration_;
}
void CoreClient::asyncExecute(Runnable * r)const
{
Executor::instance()->execute(r);
}
HttpClient::HttpResponseOutcome CoreClient::AttemptRequest(const std::string & endpoint, const ServiceRequest & request, HttpRequest::Method method) const
{
auto r = buildHttpRequest(endpoint, request, method);
auto outcome = httpClient_->makeRequest(r);
if (!outcome.isSuccess())
return outcome;
if(hasResponseError(outcome.result()))
return HttpClient::HttpResponseOutcome(buildCoreError(outcome.result()));
else
return outcome;
}
Error CoreClient::buildCoreError(const HttpResponse &response)const
{
Json::Reader reader;
Json::Value value;
if (!reader.parse(std::string(response.body(), response.bodySize()), value))
return Error("InvalidResponse", "");
Error error;
error.setErrorCode(value["Code"].asString());
error.setErrorMessage(value["Message"].asString());
error.setHost(value["HostId"].asString());
error.setRequestId(value["RequestId"].asString());
return error;
}
bool CoreClient::hasResponseError(const HttpResponse &response)const
{
return response.statusCode() < 200 || response.statusCode() > 299;
}

62
core/src/Credentials.cc Executable file
View File

@@ -0,0 +1,62 @@
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/core/Credentials.h>
using namespace AlibabaCloud;
Credentials::Credentials(const std::string &accessKeyId,
const std::string &accessKeySecret,
const std::string &sessionToken) :
accessKeyId_(accessKeyId),
accessKeySecret_(accessKeySecret),
sessionToken_(sessionToken)
{
}
Credentials::~Credentials()
{
}
std::string Credentials::accessKeyId () const
{
return accessKeyId_;
}
std::string Credentials::accessKeySecret () const
{
return accessKeySecret_;
}
void Credentials::setAccessKeyId(const std::string &accessKeyId)
{
accessKeyId_ = accessKeyId;
}
void Credentials::setAccessKeySecret(const std::string &accessKeySecret)
{
accessKeySecret_ = accessKeySecret;
}
void Credentials::setSessionToken (const std::string &sessionToken)
{
sessionToken_ = sessionToken;
}
std::string Credentials::sessionToken () const
{
return sessionToken_;
}

View File

@@ -0,0 +1,17 @@
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/core/CredentialsProvider.h>

134
core/src/CurlHttpClient.cc Normal file
View File

@@ -0,0 +1,134 @@
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "CurlHttpClient.h"
#include <cassert>
#include <sstream>
#include <vector>
using namespace AlibabaCloud;
namespace
{
size_t recvBody(char *ptr, size_t size, size_t nmemb, void *userdata)
{
HttpResponse *response = static_cast<HttpResponse*>(userdata);
response->setBody(ptr, nmemb);
return nmemb * size;
}
size_t recvHeaders(char *buffer, size_t size, size_t nitems, void *userdata)
{
HttpResponse *response = static_cast<HttpResponse*>(userdata);
std::string line(buffer);
auto pos = line.find(':');
if (pos != line.npos)
{
std::string name = line.substr(0, pos);
std::string value = line.substr(pos + 2);
size_t p = 0;
if ((p = value.rfind('\r')) != value.npos)
value[p] = '\0';
response->setHeader(name, value);
}
return nitems * size;
}
void setCUrlProxy(CURL *curlHandle, const NetworkProxy &proxy)
{
if (proxy.type() == NetworkProxy::Type::None)
return;
long type;
switch (proxy.type())
{
case NetworkProxy::Type::Socks5:
type = CURLPROXY_SOCKS5;
break;
case NetworkProxy::Type::Http:
default:
type = CURLPROXY_HTTP;
break;
}
curl_easy_setopt(curlHandle, CURLOPT_PROXYTYPE, type);
std::ostringstream out;
out << proxy.hostName() << ":" << proxy.port();
curl_easy_setopt(curlHandle, CURLOPT_PROXY, out.str().c_str());
if (!proxy.user().empty()) {
out.clear();
out << proxy.user() << ":" << proxy.password();
curl_easy_setopt(curlHandle, CURLOPT_PROXYUSERPWD, out.str().c_str());
}
}
}
CurlHttpClient::CurlHttpClient() :
HttpClient(),
curlHandle_(curl_easy_init())
{
}
CurlHttpClient::~CurlHttpClient()
{
curl_easy_cleanup(curlHandle_);
}
HttpClient::HttpResponseOutcome CurlHttpClient::makeRequest(const HttpRequest &request)
{
curl_easy_reset(curlHandle_);
HttpResponse response(request);
std::string url = request.url().toString();
switch (request.method())
{
case HttpRequest::Method::Get:
break;
case HttpRequest::Method::Put:
curl_easy_setopt(curlHandle_, CURLOPT_UPLOAD, 1L);
break;
default:
break;
}
curl_easy_setopt(curlHandle_, CURLOPT_URL, url.c_str());
curl_easy_setopt(curlHandle_, CURLOPT_SSL_VERIFYPEER, 1L);
curl_easy_setopt(curlHandle_, CURLOPT_SSL_VERIFYHOST, 2L);
curl_easy_setopt(curlHandle_, CURLOPT_HEADERDATA, &response);
curl_easy_setopt(curlHandle_, CURLOPT_HEADERFUNCTION, recvHeaders);
curl_slist *list = nullptr;
auto headers = request.headers();
for (const auto &p : headers)
{
std::string str = p.first;
str.append(": ").append(p.second);
list = curl_slist_append(list, str.c_str());
}
curl_easy_setopt(curlHandle_, CURLOPT_HTTPHEADER, list);
curl_easy_setopt(curlHandle_, CURLOPT_WRITEDATA, &response);
curl_easy_setopt(curlHandle_, CURLOPT_WRITEFUNCTION, recvBody);
setCUrlProxy(curlHandle_, proxy());
CURLcode res = curl_easy_perform(curlHandle_);
if (res == CURLE_OK) {
long response_code;
curl_easy_getinfo(curlHandle_, CURLINFO_RESPONSE_CODE, &response_code);
response.setStatusCode(response_code);
return HttpResponseOutcome(response);
}
return HttpResponseOutcome(Error("NetworkError", ""));
}

37
core/src/CurlHttpClient.h Normal file
View File

@@ -0,0 +1,37 @@
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ALIBABACLOUD_CORE_CURLHTTPCLIENT_H_
#define ALIBABACLOUD_CORE_CURLHTTPCLIENT_H_
#include <alibabacloud/core/HttpClient.h>
#include <curl/curl.h>
namespace AlibabaCloud
{
class CurlHttpClient : public HttpClient
{
public:
CurlHttpClient();
~CurlHttpClient();
virtual HttpResponseOutcome makeRequest(const HttpRequest &request) override;
private:
CURL *curlHandle_;
};
}
#endif // !ALIBABACLOUD_CORE_CURLHTTPCLIENT_H_

View File

@@ -0,0 +1,41 @@
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/core/EcsInstanceProfileConfigLoader.h>
#include "EcsMetadataClient.h"
using namespace AlibabaCloud;
EcsInstanceProfileConfigLoader::EcsInstanceProfileConfigLoader() :
metadataClient_(std::make_shared<EcsMetadataClient>())
{
}
EcsInstanceProfileConfigLoader::EcsInstanceProfileConfigLoader(const std::shared_ptr<EcsMetadataClient>& client) :
metadataClient_(client)
{
}
EcsInstanceProfileConfigLoader::~EcsInstanceProfileConfigLoader()
{
}
bool EcsInstanceProfileConfigLoader::loadInternal()
{
//TODO(fenglc): load form remote server
return false;
}

View File

@@ -0,0 +1,27 @@
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "EcsMetadataClient.h"
using namespace AlibabaCloud;
EcsMetadataClient::EcsMetadataClient()
{
}
EcsMetadataClient::~EcsMetadataClient()
{
}

View File

@@ -0,0 +1,32 @@
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ALIBABACLOUD_CORE_ECSMETADATACLIENT_H_
#define ALIBABACLOUD_CORE_ECSMETADATACLIENT_H_
namespace AlibabaCloud
{
class EcsMetadataClient
{
public:
EcsMetadataClient();
~EcsMetadataClient();
private:
};
}
#endif // !ALIBABACLOUD_CORE_ECSMETADATACLIENT_H_

View File

@@ -0,0 +1,77 @@
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/core/EndpointProvider.h>
#include <iomanip>
#include <sstream>
using namespace AlibabaCloud;
using namespace AlibabaCloud::Location;
EndpointProvider::EndpointProvider(const std::shared_ptr<Location::LocationClient>& locationClient, const std::string regionId, const std::string serviceCode, int durationSeconds) :
locationClient_(locationClient),
regionId_(regionId),
serviceCode_(serviceCode),
durationSeconds_(durationSeconds),
cachedMutex_(),
cachedEndpoint_(),
expiry_()
{
}
EndpointProvider::~EndpointProvider()
{
}
bool EndpointProvider::checkExpiry()const
{
auto now = std::chrono::system_clock::now();
auto diff = std::chrono::duration_cast<std::chrono::seconds>(now - expiry_).count();
return (diff > 0 - 60);
}
std::string EndpointProvider::getEndpoint()
{
loadEndpoint();
std::lock_guard<std::mutex> locker(cachedMutex_);
return cachedEndpoint_;
}
void EndpointProvider::loadEndpoint()
{
if (checkExpiry())
{
std::lock_guard<std::mutex> locker(cachedMutex_);
if (checkExpiry())
{
Model::DescribeEndpointsRequest request;
request.setId(regionId_);
request.setServiceCode(serviceCode_);
request.setType("openAPI");
auto outcome = locationClient_->describeEndpoints(request);
if (outcome.isSuccess())
{
auto all = outcome.result().endpoints();
if (all.size() > 0)
cachedEndpoint_ = all.front().endpoint;
std::time_t t = std::time(nullptr) + durationSeconds_;
expiry_ = std::chrono::system_clock::from_time_t(t);
}
}
}
}

36
core/src/Error.cc Normal file
View File

@@ -0,0 +1,36 @@
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/core/Error.h>
using namespace AlibabaCloud;
Error::Error(std::string code, const std::string message) :
errorCode_(code),
message_(message),
host_(),
requestId_()
{
}
std::string Error::errorCode()const { return errorCode_; }
std::string Error::errorMessage() const { return message_; }
std::string Error::host() const { return host_; }
std::string Error::requestId() const { return requestId_; }
void Error::setErrorCode(const std::string &code) { errorCode_ = code; }
void Error::setErrorMessage(const std::string& message) { message_ = message; }
void Error::setHost(const std::string& host) { host_ = host; }
void Error::setRequestId(const std::string& request) { requestId_ = request; }

124
core/src/Executor.cc Normal file
View File

@@ -0,0 +1,124 @@
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "Executor.h"
#include <alibabacloud/core/Runnable.h>
using namespace AlibabaCloud;
Executor *Executor::self_ = nullptr;
Executor::Executor() :
cvMutex_(),
shutdown_(true),
tasksQueue_(),
tasksQueueMutex_(),
thread_()
{
self_ = this;
}
Executor::~Executor()
{
self_ = nullptr;
shutdown();
}
Executor * Executor::instance()
{
return self_;
}
bool Executor::start()
{
if (!isShutdown())
return true;
auto threadMain = [this]()
{
while (!shutdown_)
{
while (!tasksQueue_.empty())
{
Runnable *task = nullptr;
{
std::lock_guard<std::mutex> lock(tasksQueueMutex_);
if (!tasksQueue_.empty())
{
task = tasksQueue_.front();
tasksQueue_.pop();
}
}
if (task) {
task->run();
delete task;
}
}
if (!shutdown_) {
std::unique_lock<std::mutex> lk(cvMutex_);
cv_.wait(lk);
}
}
};
shutdown_ = false;
thread_ = std::thread(threadMain);
return true;
}
bool Executor::isShutdown()const
{
return shutdown_;
}
void Executor::execute(Runnable* task)
{
if (isShutdown())
return;
std::lock_guard<std::mutex> locker(tasksQueueMutex_);
tasksQueue_.push(task);
wakeUp();
}
void Executor::wakeUp()
{
std::unique_lock<std::mutex> lk(cvMutex_);
cv_.notify_one();
}
void Executor::shutdown()
{
if (isShutdown())
return;
{
std::lock_guard<std::mutex> locker(tasksQueueMutex_);
while (tasksQueue_.size() > 0) {
auto task = tasksQueue_.front();
delete task;
tasksQueue_.pop();
}
}
shutdown_ = true;
wakeUp();
if (thread_.joinable())
thread_.join();
}

53
core/src/Executor.h Normal file
View File

@@ -0,0 +1,53 @@
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ALIBABACLOUD_CORE_EXECUTOR_H_
#define ALIBABACLOUD_CORE_EXECUTOR_H_
#include <atomic>
#include <condition_variable>
#include <queue>
#include <vector>
#include <thread>
#include <mutex>
namespace AlibabaCloud
{
class Runnable;
class Executor
{
public:
Executor();
~Executor();
static Executor * instance();
void execute(Runnable* task);
bool isShutdown()const;
bool start();
void shutdown();
void wakeUp();
private:
static Executor *self_;
std::atomic<bool> shutdown_;
std::queue<Runnable*> tasksQueue_;
std::mutex tasksQueueMutex_;
std::thread thread_;
std::condition_variable cv_;
std::mutex cvMutex_;
};
}
#endif // !ALIBABACLOUD_CORE_EXECUTOR_H_

View File

@@ -0,0 +1,99 @@
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/core/HmacSha1Signer.h>
#ifdef _WIN32
#include <windows.h>
#include <wincrypt.h>
#else
#include <openssl/hmac.h>
#endif
using namespace AlibabaCloud;
HmacSha1Signer::HmacSha1Signer() :
Signer(HmacSha1, "HMAC-SHA1", "1.0")
{
}
HmacSha1Signer::~HmacSha1Signer()
{
}
std::string HmacSha1Signer::generate(const std::string & src, const std::string & secret) const
{
if (src.empty())
return std::string();
#ifdef _WIN32
typedef struct _my_blob {
BLOBHEADER hdr;
DWORD dwKeySize;
BYTE rgbKeyData[];
}my_blob;
DWORD kbLen = sizeof(my_blob) + secret.size();
my_blob * kb = (my_blob *)LocalAlloc(LPTR, kbLen);
kb->hdr.bType = PLAINTEXTKEYBLOB;
kb->hdr.bVersion = CUR_BLOB_VERSION;
kb->hdr.reserved = 0;
kb->hdr.aiKeyAlg = CALG_RC2;
kb->dwKeySize = secret.size();
memcpy(&kb->rgbKeyData, secret.c_str(), secret.size());
HCRYPTPROV hProv = 0;
HCRYPTKEY hKey = 0;
HCRYPTHASH hHmacHash = 0;
BYTE pbHash[32];
DWORD dwDataLen = 32;
HMAC_INFO HmacInfo;
ZeroMemory(&HmacInfo, sizeof(HmacInfo));
HmacInfo.HashAlgid = CALG_SHA1;
CryptAcquireContext(&hProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_NEWKEYSET);
CryptImportKey(hProv, (BYTE*)kb, kbLen, 0, CRYPT_IPSEC_HMAC_KEY, &hKey);
CryptCreateHash(hProv, CALG_HMAC, hKey, 0, &hHmacHash);
CryptSetHashParam(hHmacHash, HP_HMAC_INFO, (BYTE*)&HmacInfo, 0);
CryptHashData(hHmacHash, (BYTE*)(src.c_str()), src.size(), 0);
CryptGetHashParam(hHmacHash, HP_HASHVAL, pbHash, &dwDataLen, 0);
LocalFree(kb);
CryptDestroyHash(hHmacHash);
CryptDestroyKey(hKey);
CryptReleaseContext(hProv, 0);
DWORD dlen = 0;
CryptBinaryToString(pbHash, dwDataLen, CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF, NULL, &dlen);
char* dest = new char[dlen];
CryptBinaryToString(pbHash, dwDataLen, CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF, dest, &dlen);
std::string ret = std::string(dest, dlen);
delete dest;
return ret;
#else
unsigned char md[EVP_MAX_BLOCK_LENGTH];
unsigned int mdLen = EVP_MAX_BLOCK_LENGTH;
if (HMAC(EVP_sha1(), secret.c_str(), secret.size(),
reinterpret_cast<const unsigned char*>(src.c_str()), src.size(),
md, &mdLen) == nullptr)
return std::string();
char encodedData[100];
EVP_EncodeBlock(reinterpret_cast<unsigned char*>(encodedData), md, mdLen);
return encodedData;
#endif
}

41
core/src/HttpClient.cc Normal file
View File

@@ -0,0 +1,41 @@
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/core/HttpClient.h>
#include <cassert>
#include <vector>
#include <sstream>
using namespace AlibabaCloud;
HttpClient::HttpClient() :
proxy_()
{
}
HttpClient::~HttpClient()
{
}
NetworkProxy HttpClient::proxy()const
{
return proxy_;
}
void HttpClient::setProxy(const NetworkProxy &proxy)
{
proxy_ = proxy;
}

173
core/src/HttpMessage.cc Normal file
View File

@@ -0,0 +1,173 @@
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/core/HttpMessage.h>
#include <algorithm>
using namespace AlibabaCloud;
namespace
{
#if defined(WIN32) && defined(_MSC_VER)
# define strcasecmp _stricmp
# define strncasecmp _strnicmp
#else
# include <strings.h>
#endif
std::string KnownHeaderMapper[]
{
"Accept",
"Accept-Charset",
"Accept-Encoding",
"Accept-Language",
"Authorization",
"Connection",
"Content-Length",
"Content-MD5",
"Content-Type",
"Date",
"Host",
"Server",
"User-Agent"
};
}
HttpMessage::HttpMessage() :
body_(nullptr),
bodySize_(0),
headers_()
{
}
HttpMessage::HttpMessage(const HttpMessage &other) :
body_(nullptr),
bodySize_(other.bodySize_),
headers_(other.headers_)
{
setBody(other.body_, other.bodySize_);
}
HttpMessage::HttpMessage(HttpMessage &&other)
{
*this = std::move(other);
}
HttpMessage& HttpMessage::operator=(const HttpMessage &other)
{
if (this != &other) {
body_ = nullptr;
bodySize_ = 0;
headers_ = other.headers_;
setBody(other.body_, other.bodySize_);
}
return *this;
}
HttpMessage& HttpMessage::operator=(HttpMessage &&other)
{
if (this != &other)
*this = std::move(other);
return *this;
}
void HttpMessage::addHeader(const HeaderNameType & name, const HeaderValueType & value)
{
setHeader(name, value);
}
void HttpMessage::addHeader(KnownHeader header, const HeaderValueType & value)
{
setHeader(header, value);
}
HttpMessage::HeaderValueType HttpMessage::header(const HeaderNameType & name) const
{
auto it = headers_.find(name);
if (it != headers_.end())
return it->second;
else
return std::string();
}
HttpMessage::HeaderCollection HttpMessage::headers() const
{
return headers_;
}
void HttpMessage::removeHeader(const HeaderNameType & name)
{
headers_.erase(name);
}
void HttpMessage::removeHeader(KnownHeader header)
{
removeHeader(KnownHeaderMapper[header]);
}
void HttpMessage::setHeader(const HeaderNameType & name, const HeaderValueType & value)
{
headers_[name] = value;
}
void HttpMessage::setHeader(KnownHeader header, const std::string & value)
{
setHeader(KnownHeaderMapper[header], value);
}
HttpMessage::~HttpMessage()
{
setBody(nullptr, 0);
}
const char* HttpMessage::body()const
{
return body_;
}
size_t HttpMessage::bodySize()const
{
return bodySize_;
}
bool HttpMessage::hasBody() const
{
return (bodySize_ != 0);
}
HttpMessage::HeaderValueType HttpMessage::header(KnownHeader header)const
{
return this->header(KnownHeaderMapper[header]);
}
void HttpMessage::setBody(const char *data, size_t size)
{
if (body_)
delete body_;
body_ = nullptr;
bodySize_ = 0;
if (size) {
bodySize_ = size;
body_ = new char[size];
std::copy(data, data + size, body_);
}
}
bool HttpMessage::nocaseLess::operator()(const std::string & s1,
const std::string & s2) const
{
return strcasecmp(s1.c_str(), s2.c_str()) < 0;
}

51
core/src/HttpRequest.cc Normal file
View File

@@ -0,0 +1,51 @@
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/core/HttpRequest.h>
using namespace AlibabaCloud;
HttpRequest::HttpRequest(const Url &url, Method method) :
HttpMessage(),
url_(url),
method_(method)
{
}
HttpRequest::~HttpRequest()
{
}
HttpRequest::Method HttpRequest::method() const
{
return method_;
}
void HttpRequest::setMethod(Method method)
{
method_ = method;
}
void HttpRequest::setUrl(const Url &url)
{
url_ = url;
}
Url HttpRequest::url()const
{
return url_;
}

57
core/src/HttpResponse.cc Normal file
View File

@@ -0,0 +1,57 @@
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/core/HttpResponse.h>
namespace
{
#define INVALID_STATUS_CODE -1
}
using namespace AlibabaCloud;
HttpResponse::HttpResponse() :
HttpMessage(),
request_(),
statusCode_(INVALID_STATUS_CODE)
{
}
HttpResponse::HttpResponse(const HttpRequest & request) :
HttpMessage(),
request_(request),
statusCode_(INVALID_STATUS_CODE)
{
}
HttpResponse::~HttpResponse()
{
}
HttpRequest HttpResponse::request() const
{
return request_;
}
void HttpResponse::setStatusCode(int code)
{
statusCode_ = code;
}
int HttpResponse::statusCode() const
{
return statusCode_;
}

View File

@@ -0,0 +1,65 @@
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/core/InstanceProfileConfigLoader.h>
using namespace AlibabaCloud;
InstanceProfileConfigLoader::InstanceProfileConfigLoader()
{
}
InstanceProfileConfigLoader::~InstanceProfileConfigLoader()
{
}
std::map<std::string, Profile> InstanceProfileConfigLoader::allProfiles() const
{
return profiles_;
}
std::chrono::system_clock::time_point InstanceProfileConfigLoader::lastLoadTime() const
{
return lastLoadTime_;
}
bool InstanceProfileConfigLoader::persistInternal(const std::map<std::string, Profile>&)
{
return false;
}
bool InstanceProfileConfigLoader::load()
{
if (loadInternal())
{
lastLoadTime_ = std::chrono::system_clock::now();
return true;
}
return false;
}
bool InstanceProfileConfigLoader::persistProfiles(const std::map<std::string, Profile>& profiles)
{
if (persistInternal(profiles))
{
profiles_ = profiles;
lastLoadTime_ = std::chrono::system_clock::now();
return true;
}
return false;
}

View File

@@ -0,0 +1,28 @@
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/core/InstanceProfileCredentials.h>
using namespace AlibabaCloud;
InstanceProfileCredentials::InstanceProfileCredentials() :
BasicSessionCredentials(Credentials::InstanceProfile)
{
}
InstanceProfileCredentials::~InstanceProfileCredentials()
{
}

View File

@@ -0,0 +1,78 @@
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/core/InstanceProfileCredentialsProvider.h>
#include <alibabacloud/core/EcsInstanceProfileConfigLoader.h>
#include <alibabacloud/core/Profile.h>
#include <chrono>
#include <iomanip>
#include <chrono>
#include <mutex>
using namespace AlibabaCloud;
namespace
{
const char* const INSTANCE_PROFILE_KEY = "InstanceProfile";
}
InstanceProfileCredentialsProvider::InstanceProfileCredentialsProvider(size_t refreshRateMs) :
metadataConfigLoader_(std::make_shared<EcsInstanceProfileConfigLoader>()),
loadFrequencyMs_(refreshRateMs),
lastLoaded_()
{
}
InstanceProfileCredentialsProvider::InstanceProfileCredentialsProvider(const std::shared_ptr<EcsInstanceProfileConfigLoader>& loader, size_t refreshRateMs) :
metadataConfigLoader_(loader),
loadFrequencyMs_(refreshRateMs),
lastLoaded_()
{
}
Credentials InstanceProfileCredentialsProvider::getCredentials()
{
refreshIfExpired();
auto profileIter = metadataConfigLoader_->allProfiles().find(INSTANCE_PROFILE_KEY);
if (profileIter != metadataConfigLoader_->allProfiles().end())
{
return profileIter->second.credentials();
}
return Credentials("","");
}
bool InstanceProfileCredentialsProvider::isTimeToRefresh(long reloadFrequency)
{
auto now = std::chrono::system_clock::now();
auto diff = std::chrono::duration_cast<std::chrono::seconds>(now - lastLoaded_).count();
if(diff > reloadFrequency)
{
lastLoaded_ = now;
return true;
}
return false;
}
void InstanceProfileCredentialsProvider::refreshIfExpired()
{
std::lock_guard<std::mutex> locker(m_reloadMutex);
if (isTimeToRefresh(loadFrequencyMs_))
metadataConfigLoader_->load();
}

86
core/src/NetworkProxy.cc Normal file
View File

@@ -0,0 +1,86 @@
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/core/NetworkProxy.h>
using namespace AlibabaCloud;
NetworkProxy::NetworkProxy(Type type,
const std::string &hostName,
uint16_t port,
const std::string &user,
const std::string &password)
: hostName_(hostName),
password_(password),
port_(port),
type_(type),
user_(user)
{
}
NetworkProxy::~NetworkProxy()
{
}
std::string NetworkProxy::hostName() const
{
return hostName_;
}
std::string NetworkProxy::password() const
{
return password_;
}
uint16_t NetworkProxy::port() const
{
return port_;
}
void NetworkProxy::setHostName(const std::string &hostName)
{
hostName_ = hostName;
}
void NetworkProxy::setPassword(const std::string &password)
{
password_ = password;
}
void NetworkProxy::setPort(uint16_t port)
{
port_ = port;
}
void NetworkProxy::setType(NetworkProxy::Type type)
{
type_ = type;
}
void NetworkProxy::setUser(const std::string &user)
{
user_ = user;
}
NetworkProxy::Type NetworkProxy::type() const
{
return type_;
}
std::string NetworkProxy::user() const
{
return user_;
}

17
core/src/Outcome.cc Normal file
View File

@@ -0,0 +1,17 @@
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/core/Outcome.h>

61
core/src/Profile.cc Normal file
View File

@@ -0,0 +1,61 @@
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/core/Profile.h>
using namespace AlibabaCloud;
std::string Profile::name() const
{ return name_; }
void Profile::setName(const std::string& value)
{ name_ = value; }
Credentials Profile::credentials() const
{ return credentials_; }
void Profile::setCredentials(const Credentials& value)
{ credentials_ = value; }
std::string Profile::region() const
{ return region_; }
void Profile::setRegion(const std::string& value)
{ region_ = value; }
std::string Profile::roleArn() const
{ return roleArn_; }
void Profile::setRoleArn(const std::string& value)
{ roleArn_ = value; }
std::string Profile::sourceProfile() const
{ return sourceProfile_; }
void Profile::setSourceProfile(const std::string& value)
{ sourceProfile_ = value; }
void Profile::setAllKeyValPairs(const std::map<std::string, std::string>& map)
{
allKeyValPairs_ = map;
}
std::string Profile::value(const std::string& key)
{
auto iter = allKeyValPairs_.find(key);
if (iter == allKeyValPairs_.end()) return "";
return iter->second;
}

View File

@@ -0,0 +1,179 @@
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/core/RoaServiceClient.h>
#include <algorithm>
#include <iomanip>
#include <sstream>
#include <alibabacloud/core/HmacSha1Signer.h>
//#include <alibabacloud/core/RoaErrorMarshaller.h>
#include "Utils.h"
using namespace AlibabaCloud;
RoaServiceClient::RoaServiceClient(const std::shared_ptr<CredentialsProvider> &credentialsProvider,
const ClientConfiguration &configuration,
const std::shared_ptr<Signer> &signer) :
CoreClient(configuration),
credentialsProvider_(credentialsProvider),
signer_(signer)
{
}
RoaServiceClient::~RoaServiceClient()
{
}
std::string RoaServiceClient::canonicalizedResource(const std::string &path, std::map <std::string, std::string> &params)const
{
if (params.empty())
return path;
std::stringstream ss;
for (const auto &p : params)
{
if (p.second.empty())
ss << "&" << p.first;
else
ss << "&" << p.first << "=" << p.second;
}
std::string str = path;
str.append("?").append(ss.str().substr(1));
return str;
}
std::string RoaServiceClient::canonicalizedHeaders(const HttpMessage::HeaderCollection &headers)const
{
std::map <std::string, std::string> materials;
for (const auto &p : headers)
{
std::string key = p.first;
std::transform(key.begin(), key.end(), key.begin(), ::tolower);
if (key.find("x-acs-") != 0)
continue;
std::string value = p.second;
StringReplace(value, "\t", " ");
StringReplace(value, "\n", " ");
StringReplace(value, "\r", " ");
StringReplace(value, "\f", " ");
materials[key] = value;
}
if (materials.empty())
return std::string();
std::stringstream ss;
for (const auto &p : materials)
ss << p.first << ":" << p.second << "\n";
return ss.str();
}
RoaServiceClient::JsonOutcome RoaServiceClient::makeRequest(const std::string &endpoint, const RoaServiceRequest &msg, HttpRequest::Method method)const
{
auto outcome = AttemptRequest(endpoint, msg, method);
if (outcome.isSuccess())
return JsonOutcome(std::string(outcome.result().body(),
outcome.result().bodySize()));
else
return JsonOutcome(outcome.error());
}
HttpRequest RoaServiceClient::buildHttpRequest(const std::string & endpoint, const ServiceRequest &msg, HttpRequest::Method method)const
{
return buildHttpRequest(endpoint, dynamic_cast<const RoaServiceRequest& >(msg), method);
}
HttpRequest RoaServiceClient::buildHttpRequest(const std::string & endpoint, const RoaServiceRequest &msg, HttpRequest::Method method) const
{
const Credentials credentials = credentialsProvider_->getCredentials();
Url url;
url.setScheme("https");
url.setHost(endpoint);
url.setPath(msg.resourcePath());
auto params = msg.parameters();
std::map <std::string, std::string> queryParams;
for (const auto &p : params){
if (!p.second.empty())
queryParams[p.first] = p.second;
}
if (!queryParams.empty()) {
std::stringstream queryString;
for (const auto &p : queryParams)
{
if (p.second.empty())
queryString << "&" << p.first;
else
queryString << "&" << p.first << "=" << p.second;
}
url.setQuery(queryString.str().substr(1));
}
HttpRequest request(url);
request.setMethod(method);
request.setHeader("Accept", "application/json");
if (msg.hasContent()) {
std::stringstream ss;
ss << msg.contentSize();
request.setHeader("Content-Length", ss.str());
request.setHeader("Content-Type", "application/octet-stream");
request.setHeader("Content-MD5", ComputeContentMD5(msg.content(),msg.contentSize()));
}
std::time_t t = std::time(nullptr);
std::stringstream date;
#if defined(__GNUG__) && __GNUC__ < 5
char tmbuff[26];
strftime(tmbuff, 26, "%a, %d %b %Y %T", std::gmtime(&t));
date << tmbuff << " GMT";
#else
date << std::put_time(std::gmtime(&t), "%a, %d %b %Y %T GMT");
#endif
request.setHeader("Date", date.str());
request.setHeader("Host", url.host());
request.setHeader("x-sdk-client", std::string("CPP/").append(ALIBABACLOUD_VERSION_STR));
request.setHeader("x-acs-region-id", configuration().regionId());
request.setHeader("x-acs-security-token", credentials.sessionToken());
request.setHeader("x-acs-signature-method", signer_->name());
request.setHeader("x-acs-signature-nonce", GenerateUuid());
request.setHeader("x-acs-signature-version", signer_->version());
request.setHeader("x-acs-version", msg.version());
std::stringstream plaintext;
plaintext << HttpMethodToString(method) << "\n"
<< request.header("Accept") << "\n"
<< request.header("Content-MD5") << "\n"
<< request.header("Content-Type") << "\n"
<< request.header("Date") << "\n"
<< canonicalizedHeaders(request.headers());
if (!url.hasQuery())
plaintext << url.path();
else
plaintext << url.path() << "?" << url.query();
std::stringstream sign;
sign << "acs "
<< credentials.accessKeyId()
<< ":"
<< signer_->generate(plaintext.str(), credentials.accessKeySecret());
request.setHeader("Authorization", sign.str());
return request;
}

View File

@@ -0,0 +1,32 @@
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/core/RoaServiceRequest.h>
#include <algorithm>
#include <iomanip>
#include <sstream>
#include "Utils.h"
using namespace AlibabaCloud;
RoaServiceRequest::RoaServiceRequest(const std::string & product, const std::string & version) :
ServiceRequest(product, version)
{
}
RoaServiceRequest::~RoaServiceRequest()
{
}

View File

@@ -0,0 +1,130 @@
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/core/RpcServiceClient.h>
#include <algorithm>
#include <iomanip>
#include <sstream>
#include <alibabacloud/core/HmacSha1Signer.h>
#include "Utils.h"
//#include <alibabacloud/core/RpcErrorMarshaller.h>
using namespace AlibabaCloud;
RpcServiceClient::RpcServiceClient(const std::shared_ptr<CredentialsProvider> &credentialsProvider,
const ClientConfiguration &configuration,
const std::shared_ptr<Signer> &signer) :
CoreClient(configuration),
credentialsProvider_(credentialsProvider),
signer_(signer)
{
}
RpcServiceClient::~RpcServiceClient()
{
}
std::string RpcServiceClient::canonicalizedQuery(const std::map<std::string, std::string>& params) const
{
if (params.empty())
return std::string();
std::stringstream ss;
for (const auto &p : params)
{
std::string key = UrlEncode(p.first);
StringReplace(key, "+", "%20");
StringReplace(key, "*", "%2A");
StringReplace(key, "%7E", "~");
std::string value = UrlEncode(p.second);
StringReplace(value, "+", "%20");
StringReplace(value, "*", "%2A");
StringReplace(value, "%7E", "~");
ss << "&" << key << "=" << value;
}
return ss.str().substr(1);
}
RpcServiceClient::JsonOutcome RpcServiceClient::makeRequest(const std::string &endpoint, const RpcServiceRequest &msg, HttpRequest::Method method)const
{
auto outcome = AttemptRequest(endpoint, msg, method);
if (outcome.isSuccess())
return JsonOutcome(std::string(outcome.result().body(),
outcome.result().bodySize()));
else
return JsonOutcome(outcome.error());
}
HttpRequest RpcServiceClient::buildHttpRequest(const std::string & endpoint, const ServiceRequest &msg, HttpRequest::Method method )const
{
return buildHttpRequest(endpoint, dynamic_cast<const RpcServiceRequest& >(msg), method);
}
HttpRequest RpcServiceClient::buildHttpRequest(const std::string & endpoint, const RpcServiceRequest &msg, HttpRequest::Method method) const
{
const Credentials credentials = credentialsProvider_->getCredentials();
Url url;
url.setScheme("https");
url.setHost(endpoint);
url.setPath(msg.resourcePath());
auto params = msg.parameters();
std::map <std::string, std::string> queryParams;
for (const auto &p : params) {
if (!p.second.empty())
queryParams[p.first] = p.second;
}
queryParams["AccessKeyId"] = credentials.accessKeyId();
queryParams["Format"] = "JSON";
queryParams["RegionId"] = configuration().regionId();
queryParams["SecurityToken"] = credentials.sessionToken();
queryParams["SignatureMethod"] = signer_->name();
queryParams["SignatureNonce"] = GenerateUuid();
queryParams["SignatureVersion"] = signer_->version();
std::time_t t = std::time(nullptr);
std::stringstream ss;
#if defined(__GNUG__) && __GNUC__ < 5
char tmbuff[26];
strftime(tmbuff, 26, "%FT%TZ" , std::gmtime(&t));
ss << tmbuff;
#else
ss << std::put_time(std::gmtime(&t), "%FT%TZ");
#endif
queryParams["Timestamp"] = ss.str();
queryParams["Version"] = msg.version();
std::stringstream plaintext;
plaintext << HttpMethodToString(method)
<< "&"
<< UrlEncode(url.path())
<< "&"
<< UrlEncode(canonicalizedQuery(queryParams));
queryParams["Signature"] = signer_->generate(plaintext.str(), credentials.accessKeySecret() + "&");
std::stringstream queryString;
for (const auto &p : queryParams)
queryString << "&" << p.first << "=" << UrlEncode(p.second);
url.setQuery(queryString.str().substr(1));
HttpRequest request(url);
request.setMethod(method);
request.setHeader("Host", url.host());
request.setHeader("x-sdk-client", std::string("CPP/").append(ALIBABACLOUD_VERSION_STR));
return request;
}

View File

@@ -0,0 +1,40 @@
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/core/RpcServiceRequest.h>
using namespace AlibabaCloud;
RpcServiceRequest::RpcServiceRequest(const std::string & product, const std::string & version, const std::string & action) :
ServiceRequest(product, version)
{
setActionName(action);
}
RpcServiceRequest::~RpcServiceRequest()
{
}
std::string RpcServiceRequest::actionName()const
{
return parameter("Action");
}
void RpcServiceRequest::setActionName(const std::string & name)
{
setParameter("Action", name);
}

29
core/src/Runnable.cc Normal file
View File

@@ -0,0 +1,29 @@
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/core/Runnable.h>
using namespace AlibabaCloud;
Runnable::Runnable(const std::function<void()> f) :
f_(f)
{
}
void Runnable::run() const
{
f_();
}

157
core/src/ServiceRequest.cc Normal file
View File

@@ -0,0 +1,157 @@
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/core/ServiceRequest.h>
using namespace AlibabaCloud;
ServiceRequest::ServiceRequest(const std::string &product, const std::string &version) :
content_(nullptr),
contentSize_(0),
params_(),
product_(product),
resourcePath_("/"),
version_(version)
{
}
ServiceRequest::ServiceRequest(const ServiceRequest &other) :
content_(nullptr),
contentSize_(other.contentSize_),
params_(other.params_),
product_(other.product_),
resourcePath_(other.resourcePath_),
version_(other.version_)
{
setContent(other.content_, other.contentSize_);
}
ServiceRequest::ServiceRequest(ServiceRequest &&other)
{
*this = std::move(other);
}
ServiceRequest& ServiceRequest::operator=(const ServiceRequest &other)
{
if (this != &other) {
content_ = nullptr;
contentSize_ = 0;
params_ = other.params_;
setContent(other.content_, other.contentSize_);
}
return *this;
}
ServiceRequest& ServiceRequest::operator=(ServiceRequest &&other)
{
if (this != &other)
*this = std::move(other);
return *this;
}
ServiceRequest::~ServiceRequest()
{
if (content_)
delete content_;
}
const char * ServiceRequest::content() const
{
return content_;
}
size_t ServiceRequest::contentSize() const
{
return contentSize_;
}
bool ServiceRequest::hasContent() const
{
return (contentSize_ != 0);
}
void ServiceRequest::setContent(const char * data, size_t size)
{
if (content_)
delete content_;
content_ = nullptr;
contentSize_ = 0;
if (size) {
contentSize_ = size;
content_ = new char[size];
std::copy(data, data + size, content_);
}
}
void ServiceRequest::addParameter(const ParameterNameType & name, const ParameterValueType & value)
{
setParameter(name, value);
}
ServiceRequest::ParameterValueType ServiceRequest::parameter(const ParameterNameType &name)const
{
return params_.at(name);
}
ServiceRequest::ParameterCollection ServiceRequest::parameters() const
{
return params_;
}
void ServiceRequest::removeParameter(const ParameterNameType & name)
{
params_.erase(name);
}
void ServiceRequest::setParameter(const ParameterNameType &name, const ParameterValueType &value)
{
params_[name] = value;
}
void ServiceRequest::setParameters(const ParameterCollection & params)
{
params_ = params;
}
std::string ServiceRequest::version()const
{
return version_;
}
void ServiceRequest::setVersion(const std::string &version)
{
version_ = version;
}
std::string ServiceRequest::product() const
{
return product_;
}
void ServiceRequest::setProduct(const std::string & product)
{
product_ = product;
}
std::string ServiceRequest::resourcePath() const
{
return resourcePath_;
}
void ServiceRequest::setResourcePath(const std::string & path)
{
resourcePath_ = path;
}

38
core/src/ServiceResult.cc Normal file
View File

@@ -0,0 +1,38 @@
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/core/ServiceResult.h>
using namespace AlibabaCloud;
ServiceResult::ServiceResult() :
requestId_()
{
}
ServiceResult::~ServiceResult()
{
}
std::string ServiceResult::requestId() const
{
return requestId_;
}
void ServiceResult::setRequestId(const std::string & requestId)
{
requestId_ = requestId;
}

45
core/src/Signer.cc Normal file
View File

@@ -0,0 +1,45 @@
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/core/Signer.h>
using namespace AlibabaCloud;
Signer::Signer(Type type, const std::string & name, const std::string & version) :
type_(type),
name_(name),
version_(version)
{
}
Signer::~Signer()
{
}
std::string Signer::name() const
{
return name_;
}
Signer::Type Signer::type() const
{
return type_;
}
std::string Signer::version() const
{
return version_;
}

View File

@@ -0,0 +1,40 @@
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/core/SimpleCredentialsProvider.h>
using namespace AlibabaCloud;
SimpleCredentialsProvider::SimpleCredentialsProvider(const Credentials &credentials):
CredentialsProvider(),
credentials_(credentials)
{
}
SimpleCredentialsProvider::SimpleCredentialsProvider(const std::string & accessKeyId, const std::string & accessKeySecret) :
CredentialsProvider(),
credentials_(accessKeyId, accessKeySecret)
{
}
SimpleCredentialsProvider::~SimpleCredentialsProvider()
{
}
Credentials SimpleCredentialsProvider::getCredentials()
{
return credentials_;
}

View File

@@ -0,0 +1,88 @@
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/core/StsAssumeRoleCredentialsProvider.h>
#include <iomanip>
#include <sstream>
using namespace AlibabaCloud;
using namespace AlibabaCloud::Sts;
StsAssumeRoleCredentialsProvider::StsAssumeRoleCredentialsProvider(const std::shared_ptr<StsClient>& stsClient, const std::string & roleArn, const std::string & roleSessionName, const std::string & policy, int durationSeconds) :
CredentialsProvider(),
stsClient_(stsClient),
roleArn_(roleArn),
roleSessionName_(roleSessionName),
policy_(policy),
durationSeconds_(durationSeconds),
cachedMutex_(),
cachedCredentials_("", ""),
expiry_()
{
}
StsAssumeRoleCredentialsProvider::~StsAssumeRoleCredentialsProvider()
{
}
Credentials StsAssumeRoleCredentialsProvider::getCredentials()
{
loadCredentials();
std::lock_guard<std::mutex> locker(cachedMutex_);
return cachedCredentials_;
}
bool StsAssumeRoleCredentialsProvider::checkExpiry()const
{
auto now = std::chrono::system_clock::now();
auto diff = std::chrono::duration_cast<std::chrono::seconds>(now - expiry_).count();
return (diff > 0 - 60);
}
void StsAssumeRoleCredentialsProvider::loadCredentials()
{
if (checkExpiry())
{
std::lock_guard<std::mutex> locker(cachedMutex_);
if (checkExpiry())
{
Model::AssumeRoleRequest request;
request.setRoleArn(roleArn_);
request.setRoleSessionName(roleSessionName_);
request.setPolicy(policy_);
request.setDurationSeconds(durationSeconds_);
auto assumeRoleOutcome = stsClient_->assumeRole(request);
if (assumeRoleOutcome.isSuccess())
{
const auto stsCredentials = assumeRoleOutcome.result().credentials();
cachedCredentials_ = Credentials(stsCredentials.accessKeyId,
stsCredentials.accessKeySecret,
stsCredentials.securityToken);
std::tm tm = {};
#if defined(__GNUG__) && __GNUC__ < 5
strptime(stsCredentials.expiration.c_str(), "%Y-%m-%dT%H:%M:%SZ", &tm);
#else
std::stringstream ss(stsCredentials.expiration);
ss >> std::get_time(&tm, "%Y-%m-%dT%H:%M:%SZ");
#endif
expiry_ = std::chrono::system_clock::from_time_t(std::mktime(&tm));
}
}
}
}

344
core/src/Url.cc Normal file
View File

@@ -0,0 +1,344 @@
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/core/Url.h>
#include <algorithm>
#include <sstream>
using namespace AlibabaCloud;
namespace
{
#define INVALID_PORT -1
}
Url::Url(const std::string & url) :
scheme_(),
userName_(),
password_(),
host_(),
path_(),
port_(INVALID_PORT),
query_(),
fragment_()
{
if(!url.empty())
fromString(url);
}
Url::~Url()
{
}
bool Url::operator==(const Url &url) const
{
return scheme_ == url.scheme_
&& userName_ == url.userName_
&& password_ == url.password_
&& host_ == url.host_
&& path_ == url.path_
&& port_ == url.port_
&& query_ == url.query_
&& fragment_ == url.fragment_;
}
bool Url::operator!=(const Url &url) const
{
return !(*this == url);
}
std::string Url::authority() const
{
if (!isValid())
return std::string();
std::ostringstream out;
std::string str = userInfo();
if (!str.empty())
out << str << "@";
out << host_;
if (port_ != INVALID_PORT)
out << ":" << port_;
return out.str();
}
void Url::clear()
{
scheme_.clear();
userName_.clear();
password_.clear();
host_.clear();
path_.clear();
port_ = INVALID_PORT;
query_.clear();
fragment_.clear();
}
std::string Url::fragment() const
{
return fragment_;
}
void Url::fromString(const std::string & url)
{
clear();
if (url.empty())
return;
std::string str = url;
std::string::size_type pos = 0;
std::string authority, fragment, path, query, scheme;
pos = str.find("://");
if (pos != str.npos) {
scheme = str.substr(0, pos);
str.erase(0, pos + 3);
}
pos = str.find('#');
if (pos != str.npos) {
fragment = str.substr(pos + 1);
str.erase(pos);
}
pos = str.find('?');
if (pos != str.npos) {
query = str.substr(pos + 1);
str.erase(pos);
}
pos = str.find('/');
if (pos != str.npos) {
path = str.substr(pos);
str.erase(pos);
}
else
path = "/";
authority = str;
setScheme(scheme);
setAuthority(authority);
setPath(path);
setQuery(query);
setFragment(fragment);
}
bool Url::hasFragment() const
{
return !fragment_.empty();
}
bool Url::hasQuery() const
{
return !query_.empty();
}
std::string Url::host() const
{
return host_;
}
bool Url::isEmpty() const
{
return scheme_.empty()
&& userName_.empty()
&& password_.empty()
&& host_.empty()
&& path_.empty()
&& (port_ == INVALID_PORT)
&& query_.empty()
&& fragment_.empty();
}
bool Url::isValid() const
{
if (isEmpty())
return false;
if (host_.empty())
return false;
bool valid = true;
if (userName_.empty())
valid = password_.empty();
return valid;
}
int Url::port() const
{
return port_;
}
std::string Url::password() const
{
return password_;
}
std::string Url::path() const
{
return path_;
}
std::string Url::query() const
{
return query_;
}
std::string Url::scheme() const
{
return scheme_;
}
void Url::setAuthority(const std::string & authority)
{
if (authority.empty()) {
setUserInfo("");
setHost("");
setPort(INVALID_PORT);
return;
}
std::string userinfo, host, port;
std::string::size_type pos = 0, prevpos = 0;
pos = authority.find('@');
if (pos != authority.npos) {
userinfo = authority.substr(0, pos);
prevpos = pos + 1;
}
else {
pos = 0;
}
pos = authority.find(':', prevpos);
if (pos == authority.npos)
host = authority.substr(prevpos);
else {
host = authority.substr(prevpos, pos - prevpos);
port = authority.substr(pos + 1);
}
setUserInfo(userinfo);
setHost(host);
setPort(!port.empty() ? atoi(port.c_str()): INVALID_PORT);
}
void Url::setFragment(const std::string & fragment)
{
fragment_ = fragment;
}
void Url::setHost(const std::string & host)
{
if(host.empty()){
host_.clear();
return;
}
host_ = host;
std::transform(host_.begin(), host_.end(), host_.begin(), ::tolower);
}
void Url::setPassword(const std::string & password)
{
password_ = password;
}
void Url::setPath(const std::string & path)
{
path_ = path;
}
void Url::setPort(int port)
{
port_ = port;
}
void Url::setQuery(const std::string & query)
{
query_ = query;
}
void Url::setScheme(const std::string & scheme)
{
if(scheme.empty()){
scheme_.clear();
return;
}
scheme_ = scheme;
std::transform(scheme_.begin(), scheme_.end(), scheme_.begin(), ::tolower);
}
void Url::setUserInfo(const std::string & userInfo)
{
if (userInfo.empty()) {
userName_.clear();
password_.clear();
return;
}
auto pos = userInfo.find(':');
if (pos == userInfo.npos)
userName_ = userInfo;
else {
userName_ = userInfo.substr(0, pos);
password_ = userInfo.substr(pos + 1);
}
}
void Url::setUserName(const std::string & userName)
{
userName_ = userName;
}
std::string Url::toString() const
{
if (!isValid())
return std::string();
std::ostringstream out;
if (!scheme_.empty())
out << scheme_ << "://";
std::string str = authority();
if (!str.empty())
out << authority();
if (path_.empty())
out << "/";
else
out << path_;
if (hasQuery())
out << "?" << query_;
if (hasFragment())
out << "#" << fragment_;
return out.str();
}
std::string Url::userInfo() const
{
if (!isValid())
return std::string();
std::ostringstream out;
out << userName_;
if (!password_.empty())
out << ":" << password_;
return out.str();
}
std::string Url::userName() const
{
return userName_;
}

142
core/src/Utils.cc Normal file
View File

@@ -0,0 +1,142 @@
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "Utils.h"
#include <curl/curl.h>
#ifdef _WIN32
#include <Windows.h>
#else
#include <openssl/hmac.h>
#include <openssl/md5.h>
#include <uuid/uuid.h>
#endif
std::string AlibabaCloud::GenerateUuid()
{
#ifdef _WIN32
char *data;
UUID uuidhandle;
UuidCreate(&uuidhandle);
UuidToString(&uuidhandle, (RPC_CSTR*)&data);
std::string uuid(data);
RpcStringFree((RPC_CSTR*)&data);
return uuid;
#else
uuid_t uu;
uuid_generate(uu);
char buf[36];
uuid_unparse(uu, buf);
return buf;
#endif
}
std::string AlibabaCloud::UrlEncode(const std::string & src)
{
CURL *curl = curl_easy_init();
char *output = curl_easy_escape(curl, src.c_str(), src.size());
std::string result(output);
curl_free(output);
return result;
}
std::string AlibabaCloud::UrlDecode(const std::string & src)
{
CURL *curl = curl_easy_init();
int outlength = 0;
char *output = curl_easy_unescape(curl, src.c_str(), src.size(), &outlength);
std::string result(output, outlength);
curl_free(output);
return result;
}
std::string AlibabaCloud::ComputeContentMD5(const char * data, size_t size)
{
#ifdef _WIN32
HCRYPTPROV hProv = 0;
HCRYPTHASH hHash = 0;
BYTE pbHash[16];
DWORD dwDataLen = 16;
CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);
CryptCreateHash(hProv, CALG_MD5, 0, 0, &hHash);
CryptHashData(hHash, (BYTE*)(data), size, 0);
CryptGetHashParam(hHash, HP_HASHVAL, pbHash, &dwDataLen, 0);
CryptDestroyHash(hHash);
CryptReleaseContext(hProv, 0);
DWORD dlen = 0;
CryptBinaryToString(pbHash, dwDataLen, CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF, NULL, &dlen);
char* dest = new char[dlen];
CryptBinaryToString(pbHash, dwDataLen, CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF, dest, &dlen);
std::string ret = std::string(dest, dlen);
delete dest;
return ret;
#else
unsigned char md[MD5_DIGEST_LENGTH];
MD5(reinterpret_cast<const unsigned char*>(data), size, (unsigned char*)&md);
char encodedData[100];
EVP_EncodeBlock(reinterpret_cast<unsigned char*>(encodedData), md, MD5_DIGEST_LENGTH);
return encodedData;
#endif
}
void AlibabaCloud::StringReplace(std::string & src, const std::string & s1, const std::string & s2)
{
std::string::size_type pos =0;
while ((pos = src.find(s1, pos)) != std::string::npos)
{
src.replace(pos, s1.length(), s2);
pos += s2.length();
}
}
std::string AlibabaCloud::HttpMethodToString(HttpRequest::Method method)
{
switch (method)
{
case HttpRequest::Method::Head:
return "HEAD";
break;
case HttpRequest::Method::Post:
return "POST";
break;
case HttpRequest::Method::Put:
return "PUT";
break;
case HttpRequest::Method::Delete:
return "DELETE";
break;
case HttpRequest::Method::Connect:
return "CONNECT";
break;
case HttpRequest::Method::Options:
return "OPTIONS";
break;
case HttpRequest::Method::Patch:
return "PATCH";
break;
case HttpRequest::Method::Trace:
return "TRACE";
break;
case HttpRequest::Method::Get:
default:
return "GET";
break;
}
}

32
core/src/Utils.h Normal file
View File

@@ -0,0 +1,32 @@
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ALIBABACLOUD_CORE_UTILS_H_
#define ALIBABACLOUD_CORE_UTILS_H_
#include <string>
#include <alibabacloud/core/HttpRequest.h>
namespace AlibabaCloud
{
std::string ComputeContentMD5(const char *data, size_t size);
std::string GenerateUuid();
std::string HttpMethodToString(HttpRequest::Method method);
void StringReplace(std::string &src, const std::string &s1, const std::string &s2);
std::string UrlEncode(const std::string &src);
std::string UrlDecode(const std::string &src);
}
#endif

View File

@@ -0,0 +1,79 @@
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/core/location/LocationClient.h>
#include <alibabacloud/core/SimpleCredentialsProvider.h>
using namespace AlibabaCloud;
using namespace AlibabaCloud::Location;
LocationClient::LocationClient(const Credentials &credentials, const ClientConfiguration &configuration) :
RpcServiceClient(std::make_shared<SimpleCredentialsProvider>(credentials), configuration)
{
}
LocationClient::LocationClient(const std::shared_ptr<CredentialsProvider>& credentialsProvider, const ClientConfiguration & configuration) :
RpcServiceClient(credentialsProvider, configuration)
{
}
LocationClient::LocationClient(const std::string & accessKeyId, const std::string & accessKeySecret, const ClientConfiguration & configuration) :
RpcServiceClient(std::make_shared<SimpleCredentialsProvider>(accessKeyId, accessKeySecret), configuration)
{
}
LocationClient::~LocationClient()
{}
CoreClient::EndpointOutcome LocationClient::endpoint()const
{
return CoreClient::EndpointOutcome("location.aliyuncs.com");
}
LocationClient::DescribeEndpointsOutcome LocationClient::describeEndpoints(const Model::DescribeEndpointsRequest &request) const
{
auto endpointOutcome = endpoint();
if (!endpointOutcome.isSuccess())
return DescribeEndpointsOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribeEndpointsOutcome(Model::DescribeEndpointsResult(outcome.result()));
else
return DescribeEndpointsOutcome(outcome.error());
}
void LocationClient::describeEndpointsAsync(const Model::DescribeEndpointsRequest& request, const DescribeEndpointsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
std::async(std::launch::async,
[this, request, handler, context]()
{
handler(this, request, describeEndpoints(request), context);
});
}
LocationClient::DescribeEndpointsOutcomeCallable LocationClient::describeEndpointsCallable(const Model::DescribeEndpointsRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribeEndpointsOutcome()>>(
[this, request]()
{
return this->describeEndpoints(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}

View File

@@ -0,0 +1,26 @@
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/core/location/LocationRequest.h>
using namespace AlibabaCloud::Location;
LocationRequest::LocationRequest(const std::string & action) :
RpcServiceRequest("location", "2015-06-12", action)
{ }
LocationRequest::~LocationRequest()
{ }

View File

@@ -0,0 +1,58 @@
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/core/location/model/DescribeEndpointsRequest.h>
using namespace AlibabaCloud::Location;
using namespace AlibabaCloud::Location::Model;
DescribeEndpointsRequest::DescribeEndpointsRequest() :
LocationRequest("DescribeEndpoints")
{}
DescribeEndpointsRequest::~DescribeEndpointsRequest()
{}
std::string DescribeEndpointsRequest::serviceCode()const
{
return parameter("ServiceCode");
}
void DescribeEndpointsRequest::setServiceCode(const std::string & serviceCode)
{
setParameter("ServiceCode", serviceCode);
}
std::string DescribeEndpointsRequest::id()const
{
return parameter("Id");
}
void DescribeEndpointsRequest::setId(const std::string & id)
{
setParameter("Id", id);
}
std::string DescribeEndpointsRequest::type()const
{
return parameter("Type");
}
void DescribeEndpointsRequest::setType(const std::string & type)
{
setParameter("Type", type);
}

View File

@@ -0,0 +1,83 @@
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/core/location/model/DescribeEndpointsResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Location;
using namespace AlibabaCloud::Location::Model;
DescribeEndpointsResult::DescribeEndpointsResult() :
ServiceResult()
{
}
DescribeEndpointsResult::DescribeEndpointsResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
DescribeEndpointsResult::~DescribeEndpointsResult()
{}
void DescribeEndpointsResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
success_ = value["Success"].asBool();
auto allEndpoints = value["Endpoints"]["Endpoint"];
for (const auto &item : allEndpoints)
{
Endpoint region;
region.endpoint = item["Endpoint"].asString();
region.id = item["Id"].asString();
region.namespace_ = item["Namespace"].asString();
region.serivceCode = item["SerivceCode"].asString();
region.type = item["Type"].asString();
auto allProtocols = item["Protocols"]["Protocols"];
for (const auto &item : allProtocols)
{
region.protocols.push_back(item.asString());
}
endpoints_.push_back(region);
}
}
std::vector<DescribeEndpointsResult::Endpoint> DescribeEndpointsResult::endpoints()const
{
return endpoints_;
}
void DescribeEndpointsResult::setEndpoints(const std::vector<Endpoint> & endpoints)
{
endpoints_ = endpoints;
}
bool DescribeEndpointsResult::success()const
{
return success_;
}
void DescribeEndpointsResult::setSuccess(const bool & success)
{
success_ = success;
}

118
core/src/sts/StsClient.cc Normal file
View File

@@ -0,0 +1,118 @@
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/core/sts/StsClient.h>
#include <alibabacloud/core/SimpleCredentialsProvider.h>
using namespace AlibabaCloud;
using namespace AlibabaCloud::Sts;
using namespace AlibabaCloud::Sts::Model;
StsClient::StsClient(const Credentials &credentials, const ClientConfiguration &configuration) :
RpcServiceClient(std::make_shared<SimpleCredentialsProvider>(credentials), configuration)
{
}
StsClient::StsClient(const std::shared_ptr<CredentialsProvider>& credentialsProvider, const ClientConfiguration & configuration) :
RpcServiceClient(credentialsProvider, configuration)
{
}
StsClient::StsClient(const std::string & accessKeyId, const std::string & accessKeySecret, const ClientConfiguration & configuration) :
RpcServiceClient(std::make_shared<SimpleCredentialsProvider>(accessKeyId, accessKeySecret), configuration)
{
}
StsClient::~StsClient()
{
}
CoreClient::EndpointOutcome StsClient::endpoint()const
{
return CoreClient::EndpointOutcome("sts.aliyuncs.com");
}
StsClient::AssumeRoleOutcome StsClient::assumeRole(const Model::AssumeRoleRequest &request)const
{
auto endpointOutcome = endpoint();
if (!endpointOutcome.isSuccess())
return AssumeRoleOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return AssumeRoleOutcome(AssumeRoleResult(outcome.result()));
else
return AssumeRoleOutcome(Error(outcome.error()));
}
void StsClient::assumeRoleAsync(const Model::AssumeRoleRequest & request, const AssumeRoleAsyncHandler & handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, assumeRole(request), context);
};
asyncExecute(new Runnable(fn));
}
StsClient::AssumeRoleOutcomeCallable StsClient::assumeRoleCallable(const Model::AssumeRoleRequest & request) const
{
auto task = std::make_shared<std::packaged_task<AssumeRoleOutcome()>>(
[this, request]()
{
return this->assumeRole(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
StsClient::GetCallerIdentityOutcome StsClient::getCallerIdentity(const GetCallerIdentityRequest &request) const
{
auto endpointOutcome = endpoint();
if (!endpointOutcome.isSuccess())
return GetCallerIdentityOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return GetCallerIdentityOutcome(GetCallerIdentityResult(outcome.result()));
else
return GetCallerIdentityOutcome(Error(outcome.error()));
}
void StsClient::getCallerIdentityAsync(const GetCallerIdentityRequest& request, const GetCallerIdentityAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, getCallerIdentity(request), context);
};
asyncExecute(new Runnable(fn));
}
StsClient::GetCallerIdentityOutcomeCallable StsClient::getCallerIdentityCallable(const GetCallerIdentityRequest &request) const
{
auto task = std::make_shared<std::packaged_task<GetCallerIdentityOutcome()>>(
[this, request]()
{
return this->getCallerIdentity(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}

View File

@@ -0,0 +1,29 @@
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/core/sts/StsRequest.h>
using namespace AlibabaCloud;
using namespace AlibabaCloud::Sts;
StsRequest::StsRequest(const std::string & action) :
RpcServiceRequest("sts", "2015-04-01", action)
{
}
StsRequest::~StsRequest()
{
}

View File

@@ -0,0 +1,73 @@
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/core/sts/model/AssumeRoleRequest.h>
using namespace AlibabaCloud;
using namespace AlibabaCloud::Sts;
using namespace AlibabaCloud::Sts::Model;
AssumeRoleRequest::AssumeRoleRequest() :
StsRequest("AssumeRole")
{
setRoleArn("");
setRoleSessionName("");
setDurationSeconds(3600);
}
AssumeRoleRequest::~AssumeRoleRequest()
{
}
int AssumeRoleRequest::durationSeconds() const
{
return std::stoi(parameter("DurationSeconds"));
}
std::string AssumeRoleRequest::policy() const
{
return parameter("Policy");
}
std::string AssumeRoleRequest::roleArn() const
{
return parameter("RoleArn");
}
std::string AssumeRoleRequest::roleSessionName() const
{
return parameter("RoleSessionName");
}
void AssumeRoleRequest::setDurationSeconds(int durationSeconds)
{
setParameter("DurationSeconds", std::to_string(durationSeconds));
}
void AssumeRoleRequest::setPolicy(const std::string & policy)
{
setParameter("Policy", policy);
}
void AssumeRoleRequest::setRoleArn(const std::string & roleArn)
{
setParameter("RoleArn", roleArn);
}
void AssumeRoleRequest::setRoleSessionName(const std::string & roleSessionName)
{
setParameter("RoleSessionName", roleSessionName);
}

View File

@@ -0,0 +1,69 @@
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/core/sts/model/AssumeRoleResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Sts;
using namespace AlibabaCloud::Sts::Model;
AssumeRoleResult::AssumeRoleResult() :
ServiceResult(),
assumedRoleUser_(),
credentials_()
{
}
AssumeRoleResult::AssumeRoleResult(const std::string & payload) :
ServiceResult(),
assumedRoleUser_(),
credentials_()
{
parse(payload);
}
AssumeRoleResult::~AssumeRoleResult()
{
}
AssumeRoleResult::AssumedRoleUser AssumeRoleResult::assumedRoleUser() const
{
return assumedRoleUser_;
}
AssumeRoleResult::Credentials AssumeRoleResult::credentials() const
{
return credentials_;
}
void AssumeRoleResult::parse(const std::string & payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto assumedRoleUserNode = value["AssumedRoleUser"];
assumedRoleUser_.assumedRoleId = assumedRoleUserNode["AssumedRoleId"].asString();
assumedRoleUser_.arn = assumedRoleUserNode["Arn"].asString();
auto credentialsNode = value["Credentials"];
credentials_.accessKeyId = credentialsNode["AccessKeyId"].asString();
credentials_.accessKeySecret = credentialsNode["AccessKeySecret"].asString();
credentials_.expiration = credentialsNode["Expiration"].asString();
credentials_.securityToken = credentialsNode["SecurityToken"].asString();
}

View File

@@ -0,0 +1,30 @@
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/core/sts/model/GetCallerIdentityRequest.h>
using namespace AlibabaCloud;
using namespace AlibabaCloud::Sts;
using namespace AlibabaCloud::Sts::Model;
GetCallerIdentityRequest::GetCallerIdentityRequest() :
StsRequest("GetCallerIdentity")
{
}
GetCallerIdentityRequest::~GetCallerIdentityRequest()
{
}

View File

@@ -0,0 +1,71 @@
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/core/sts/model/GetCallerIdentityResult.h>
#include <json/json.h>
using namespace AlibabaCloud;
using namespace AlibabaCloud::Sts;
using namespace AlibabaCloud::Sts::Model;
GetCallerIdentityResult::GetCallerIdentityResult() :
ServiceResult(),
accountId_(),
arn_(),
userId_()
{
}
GetCallerIdentityResult::GetCallerIdentityResult(const std::string & payload) :
ServiceResult(),
accountId_(),
arn_(),
userId_()
{
parse(payload);
}
GetCallerIdentityResult::~GetCallerIdentityResult()
{
}
std::string GetCallerIdentityResult::accountId()
{
return accountId_;
}
std::string GetCallerIdentityResult::arn() const
{
return arn_;
}
std::string GetCallerIdentityResult::userId() const
{
return userId_;
}
void GetCallerIdentityResult::parse(const std::string & payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
accountId_ = value["AccountId"].asString();
arn_ = value["Arn"].asString();
userId_ = value["UserId"].asString();
}