code stringlengths 1 1.05M | repo_name stringlengths 6 83 | path stringlengths 3 242 | language stringclasses 222 values | license stringclasses 20 values | size int64 1 1.05M |
|---|---|---|---|---|---|
/*
* 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.
*/
#pragma once
#include <memory>
#include <iostream>
#include <alibabacloud/oss/Export.h>
#include <alibabacloud/oss/OssResult.h>
#include <vector>
namespace AlibabaCloud
{
namespace OSS
{
class MultipartUpload
{
public:
MultipartUpload() = default;
public:
std::string Key;
std::string UploadId;
std::string Initiated;
};
using MultipartUploadList = std::vector<MultipartUpload>;
class ALIBABACLOUD_OSS_EXPORT ListMultipartUploadsResult : public OssResult
{
public:
ListMultipartUploadsResult();
ListMultipartUploadsResult(const std::string& data);
ListMultipartUploadsResult(const std::shared_ptr<std::iostream>& data);
ListMultipartUploadsResult& operator=(const std::string& data);
const std::string& Bucket() const { return bucket_; }
const std::string& KeyMarker() const { return keyMarker_; }
const std::string& UploadIdMarker() const { return uploadIdMarker_; }
const std::string& EncodingType() const { return encodingType_; }
const std::string& NextKeyMarker() const { return nextKeyMarker_; }
const std::string& NextUploadIdMarker() const { return nextUploadIdMarker_; }
uint32_t MaxUploads() const { return maxUploads_; }
bool IsTruncated() const { return isTruncated_; }
const CommonPrefixeList& CommonPrefixes() const { return commonPrefixes_; }
const AlibabaCloud::OSS::MultipartUploadList& MultipartUploadList() const { return multipartUploadList_; }
private:
std::string bucket_;
std::string keyMarker_;
std::string uploadIdMarker_;
std::string encodingType_;
std::string nextKeyMarker_;
std::string nextUploadIdMarker_;
uint32_t maxUploads_;
bool isTruncated_;
CommonPrefixeList commonPrefixes_;
AlibabaCloud::OSS::MultipartUploadList multipartUploadList_;
};
}
}
| YifuLiu/AliOS-Things | components/oss/include/alibabacloud/oss/model/ListMultipartUploadsResult.h | C++ | apache-2.0 | 2,580 |
/*
* 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.
*/
#pragma once
#include <alibabacloud/oss/Export.h>
#include <alibabacloud/oss/OssRequest.h>
namespace AlibabaCloud
{
namespace OSS
{
class ALIBABACLOUD_OSS_EXPORT ListObjectVersionsRequest : public OssBucketRequest
{
public:
ListObjectVersionsRequest(const std::string& bucket):
OssBucketRequest(bucket),
delimiterIsSet_(false),
keyMarkerIsSet_(false),
maxKeysIsSet_(false),
prefixIsSet_(false),
encodingTypeIsSet_(false),
versionIdMarkerIsSet_(false)
{
}
void setDelimiter(const std::string& delimiter) { delimiter_ = delimiter; delimiterIsSet_ = true; }
void setKeyMarker(const std::string& marker) { keyMarker_ = marker; keyMarkerIsSet_ = true;}
void setMaxKeys(int maxKeys) {maxKeys_ = maxKeys; maxKeysIsSet_ = true;}
void setPrefix(const std::string& prefix) { prefix_ = prefix; prefixIsSet_ = true; }
void setEncodingType(const std::string& type) { encodingType_ = type; encodingTypeIsSet_ = true; }
void setVersionIdMarker(const std::string& marker) { versionIdMarker_ = marker; versionIdMarkerIsSet_ = true; }
protected:
virtual ParameterCollection specialParameters() const
{
ParameterCollection params;
params["versions"] = "";
if (delimiterIsSet_) params["delimiter"] = delimiter_;
if (keyMarkerIsSet_) params["key-marker"] = keyMarker_;
if (maxKeysIsSet_) params["max-keys"] = std::to_string(maxKeys_);
if (prefixIsSet_) params["prefix"] = prefix_;
if (encodingTypeIsSet_) params["encoding-type"] = encodingType_;
if (versionIdMarkerIsSet_) params["version-id-marker"] = versionIdMarker_;
return params;
}
private:
std::string delimiter_;
bool delimiterIsSet_;
std::string keyMarker_;
bool keyMarkerIsSet_;
int maxKeys_;
bool maxKeysIsSet_;
std::string prefix_;
bool prefixIsSet_;
std::string encodingType_;
bool encodingTypeIsSet_;
std::string versionIdMarker_;
bool versionIdMarkerIsSet_;
};
}
}
| YifuLiu/AliOS-Things | components/oss/include/alibabacloud/oss/model/ListObjectVersionsRequest.h | C++ | apache-2.0 | 2,925 |
/*
* 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.
*/
#pragma once
#include <alibabacloud/oss/model/Bucket.h>
#include <vector>
#include <memory>
#include <iostream>
#include <alibabacloud/oss/OssResult.h>
#include <alibabacloud/oss/model/Owner.h>
namespace AlibabaCloud
{
namespace OSS
{
class ListObjectVersionsResult;
class ALIBABACLOUD_OSS_EXPORT ObjectVersionSummary
{
public:
ObjectVersionSummary() = default;
const std::string& Key() const { return key_; }
const std::string& VersionId() const { return versionid_; }
const std::string& ETag()const { return eTag_; }
const std::string& LastModified() const { return lastModified_; }
const std::string& StorageClass() const { return storageClass_; }
const std::string& Type() const { return type_; }
int64_t Size() const { return size_; }
bool IsLatest() const { return isLatest_; }
const AlibabaCloud::OSS::Owner& Owner() const { return owner_; }
private:
friend class ListObjectVersionsResult;
std::string key_;
std::string versionid_;
std::string eTag_;
std::string lastModified_;
std::string storageClass_;
std::string type_;
int64_t size_;
bool isLatest_;
AlibabaCloud::OSS::Owner owner_;
};
using ObjectVersionSummaryList = std::vector<ObjectVersionSummary>;
class ALIBABACLOUD_OSS_EXPORT DeleteMarkerSummary
{
public:
DeleteMarkerSummary() = default;
const std::string& Key() const { return key_; }
const std::string& VersionId() const { return versionid_; }
const std::string& LastModified() const { return lastModified_; }
bool IsLatest() const { return isLatest_; }
const AlibabaCloud::OSS::Owner& Owner() const { return owner_; }
private:
friend class ListObjectVersionsResult;
std::string key_;
std::string versionid_;
std::string lastModified_;
bool isLatest_;
AlibabaCloud::OSS::Owner owner_;
};
using DeleteMarkerSummaryList = std::vector<DeleteMarkerSummary>;
class ALIBABACLOUD_OSS_EXPORT ListObjectVersionsResult : public OssResult
{
public:
ListObjectVersionsResult();
ListObjectVersionsResult(const std::string& data);
ListObjectVersionsResult(const std::shared_ptr<std::iostream>& data);
ListObjectVersionsResult& operator=(const std::string& data);
const std::string& Name() const { return name_; }
const std::string& Prefix() const { return prefix_; }
const std::string& KeyMarker() const { return keyMarker_; }
const std::string& NextKeyMarker() const { return nextKeyMarker_; }
const std::string& VersionIdMarker() const { return versionIdMarker_; }
const std::string& NextVersionIdMarker() const { return nextVersionIdMarker_; }
const std::string& Delimiter() const { return delimiter_; }
const std::string& EncodingType() const { return encodingType_; }
int MaxKeys() const { return maxKeys_; }
bool IsTruncated() const { return isTruncated_; }
const CommonPrefixeList& CommonPrefixes() const { return commonPrefixes_; }
const ObjectVersionSummaryList& ObjectVersionSummarys() const { return objectVersionSummarys_; }
const DeleteMarkerSummaryList& DeleteMarkerSummarys() const { return deleteMarkerSummarys_; }
private:
std::string name_;
std::string prefix_;
std::string keyMarker_;
std::string nextKeyMarker_;
std::string versionIdMarker_;
std::string nextVersionIdMarker_;
std::string delimiter_;
std::string encodingType_;
bool isTruncated_;
int maxKeys_;
CommonPrefixeList commonPrefixes_;
ObjectVersionSummaryList objectVersionSummarys_;
DeleteMarkerSummaryList deleteMarkerSummarys_;
};
}
}
| YifuLiu/AliOS-Things | components/oss/include/alibabacloud/oss/model/ListObjectVersionsResult.h | C++ | apache-2.0 | 4,654 |
/*
* 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.
*/
#pragma once
#include <alibabacloud/oss/Export.h>
#include <alibabacloud/oss/OssRequest.h>
namespace AlibabaCloud
{
namespace OSS
{
class ALIBABACLOUD_OSS_EXPORT ListObjectsRequest: public OssBucketRequest
{
public:
ListObjectsRequest(const std::string& bucket):
OssBucketRequest(bucket),
delimiterIsSet_(false),
markerIsSet_(false),
maxKeysIsSet_(false),
prefixIsSet_(false),
encodingTypeIsSet_(false),
requestPayer_(RequestPayer::NotSet)
{
}
void setDelimiter(const std::string& delimiter) { delimiter_ = delimiter; delimiterIsSet_ = true; }
void setMarker(const std::string& marker) {marker_ = marker; markerIsSet_ = true;}
void setMaxKeys(int maxKeys) {maxKeys_ = maxKeys; maxKeysIsSet_ = true;}
void setPrefix(const std::string& prefix) { prefix_ = prefix; prefixIsSet_ = true; }
void setEncodingType(const std::string& type) { encodingType_ = type; encodingTypeIsSet_ = true; }
void setRequestPayer(RequestPayer value) { requestPayer_ = value; }
protected:
virtual ParameterCollection specialParameters() const;
virtual HeaderCollection specialHeaders() const;
private:
std::string delimiter_;
bool delimiterIsSet_;
std::string marker_;
bool markerIsSet_;
int maxKeys_;
bool maxKeysIsSet_;
std::string prefix_;
bool prefixIsSet_;
std::string encodingType_;
bool encodingTypeIsSet_;
RequestPayer requestPayer_;
};
}
}
| YifuLiu/AliOS-Things | components/oss/include/alibabacloud/oss/model/ListObjectsRequest.h | C++ | apache-2.0 | 2,244 |
/*
* 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.
*/
#pragma once
#include <alibabacloud/oss/model/Bucket.h>
#include <vector>
#include <memory>
#include <iostream>
#include <alibabacloud/oss/OssResult.h>
#include <alibabacloud/oss/model/Owner.h>
namespace AlibabaCloud
{
namespace OSS
{
class ListObjectsResult;
class ALIBABACLOUD_OSS_EXPORT ObjectSummary
{
public:
ObjectSummary() = default;
const std::string& Key() const { return key_; }
const std::string& ETag()const { return eTag_; }
int64_t Size() const { return size_; }
const std::string& LastModified() const { return lastModified_; }
const std::string& StorageClass() const { return storageClass_; }
const std::string& Type() const { return type_; }
const AlibabaCloud::OSS::Owner& Owner() const { return owner_; }
private:
friend class ListObjectsResult;
std::string key_;
std::string eTag_;
int64_t size_;
std::string lastModified_;
std::string storageClass_;
std::string type_;
AlibabaCloud::OSS::Owner owner_;
};
using ObjectSummaryList = std::vector<ObjectSummary>;
class ALIBABACLOUD_OSS_EXPORT ListObjectsResult : public OssResult
{
public:
ListObjectsResult();
ListObjectsResult(const std::string& data);
ListObjectsResult(const std::shared_ptr<std::iostream>& data);
ListObjectsResult& operator=(const std::string& data);
const std::string& Name() const { return name_; }
const std::string& Prefix() const { return prefix_; }
const std::string& Marker() const { return marker_; }
const std::string& NextMarker() const { return nextMarker_; }
const std::string& Delimiter() const { return delimiter_; }
const std::string& EncodingType() const { return encodingType_; }
int MaxKeys() const { return maxKeys_; }
bool IsTruncated() const { return isTruncated_; }
const CommonPrefixeList& CommonPrefixes() const { return commonPrefixes_; }
const ObjectSummaryList& ObjectSummarys() const { return objectSummarys_; }
private:
std::string name_;
std::string prefix_;
std::string marker_;
std::string delimiter_;
std::string nextMarker_;
std::string encodingType_;
bool isTruncated_;
int maxKeys_;
CommonPrefixeList commonPrefixes_;
ObjectSummaryList objectSummarys_;
};
}
}
| YifuLiu/AliOS-Things | components/oss/include/alibabacloud/oss/model/ListObjectsResult.h | C++ | apache-2.0 | 3,100 |
/*
* Copyright 2009-2018 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.
*/
#pragma once
#include <sstream>
#include <iostream>
#include <alibabacloud/oss/Export.h>
#include <alibabacloud/oss/OssRequest.h>
#include <alibabacloud/oss/Types.h>
namespace AlibabaCloud
{
namespace OSS
{
class ALIBABACLOUD_OSS_EXPORT ListPartsRequest: public OssObjectRequest
{
public:
ListPartsRequest(const std::string& bucket, const std::string& key);
ListPartsRequest(const std::string& bucket, const std::string& key,
const std::string& uploadId);
void setUploadId(const std::string& uploadId);
void setMaxParts(uint32_t maxParts);
void setPartNumberMarker(uint32_t partNumberMarker);
void setEncodingType(const std::string& encodingType);
protected:
virtual ParameterCollection specialParameters() const;
private:
std::string uploadId_;
uint32_t maxParts_;
bool maxPartsIsSet_;
uint32_t partNumberMarker_;
bool partNumberMarkerIsSet_;
std::string encodingType_;
bool encodingTypeIsSet_;
};
}
} | YifuLiu/AliOS-Things | components/oss/include/alibabacloud/oss/model/ListPartsRequest.h | C++ | apache-2.0 | 1,680 |
/*
* 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.
*/
#pragma once
#include <alibabacloud/oss/model/Bucket.h>
#include <vector>
#include <memory>
#include <iostream>
#include <alibabacloud/oss/Export.h>
#include <alibabacloud/oss/model/Owner.h>
#include <alibabacloud/oss/OssResult.h>
#include <alibabacloud/oss/model/Part.h>
namespace AlibabaCloud
{
namespace OSS
{
class ALIBABACLOUD_OSS_EXPORT ListPartsResult :public OssResult
{
public:
ListPartsResult();
ListPartsResult(const std::string& data);
ListPartsResult(const std::shared_ptr<std::iostream>& data);
ListPartsResult& operator=(const std::string& data);
const std::string& Bucket() const;
const std::string& Key() const;
const std::string& UploadId() const;
const std::string& EncodingType() const;
uint32_t MaxParts() const;
uint32_t PartNumberMarker() const;
uint32_t NextPartNumberMarker() const;
const AlibabaCloud::OSS::PartList& PartList()const;
bool IsTruncated() const;
private:
std::string uploadId_;
uint32_t maxParts_;
uint32_t partNumberMarker_;
uint32_t nextPartNumberMarker_;
std::string encodingType_;
std::string key_;
std::string bucket_;
bool isTruncated_;
AlibabaCloud::OSS::PartList partList_;
};
}
}
| YifuLiu/AliOS-Things | components/oss/include/alibabacloud/oss/model/ListPartsResult.h | C++ | apache-2.0 | 1,955 |
/*
* 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.
*/
#pragma once
#include <alibabacloud/oss/Export.h>
#include <alibabacloud/oss/Types.h>
#include <alibabacloud/oss/OssRequest.h>
#include <alibabacloud/oss/model/ObjectMetaData.h>
#include <iostream>
namespace AlibabaCloud
{
namespace OSS
{
class ALIBABACLOUD_OSS_EXPORT MultiCopyObjectRequest : public OssResumableBaseRequest
{
public:
MultiCopyObjectRequest(const std::string& bucket, const std::string& key,
const std::string& srcBucket, const std::string& srcKey);
MultiCopyObjectRequest(const std::string& bucket, const std::string& key,
const std::string& srcBucket, const std::string& srcKey,
const std::string& checkpointDir);
MultiCopyObjectRequest(const std::string& bucket, const std::string& key,
const std::string& srcBucket, const std::string& srcKey,
const std::string& checkpointDir, const ObjectMetaData& meta);
MultiCopyObjectRequest(const std::string& bucket, const std::string& key,
const std::string& srcBucket, const std::string& srcKey,
const std::string& checkpointDir, uint64_t partSize, uint32_t threadNum);
MultiCopyObjectRequest(const std::string& bucket, const std::string& key,
const std::string& srcBucket, const std::string& srcKey,
const std::string& checkpointDir, uint64_t partSize, uint32_t threadNum,
const ObjectMetaData& metaData);
MultiCopyObjectRequest(const std::string& bucket, const std::string& key,
const std::string& srcBucket, const std::string& srcKey,
const std::wstring& checkpointDir);
MultiCopyObjectRequest(const std::string& bucket, const std::string& key,
const std::string& srcBucket, const std::string& srcKey,
const std::wstring& checkpointDir, const ObjectMetaData& meta);
MultiCopyObjectRequest(const std::string& bucket, const std::string& key,
const std::string& srcBucket, const std::string& srcKey,
const std::wstring& checkpointDir, uint64_t partSize, uint32_t threadNum);
MultiCopyObjectRequest(const std::string& bucket, const std::string& key,
const std::string& srcBucket, const std::string& srcKey,
const std::wstring& checkpointDir, uint64_t partSize, uint32_t threadNum,
const ObjectMetaData& metaData);
const std::string& SrcBucket() const { return srcBucket_; }
const std::string& SrcKey() const { return srcKey_; }
const std::string& EncodingType() const { return encodingType_; }
const ObjectMetaData& MetaData() const { return metaData_; }
void setCopySource(const std::string& srcBucket, const std::string& srcObject);
void setSourceIfMatchEtag(const std::string& value);
void setSourceIfNotMatchEtag(const std::string& value);
void setSourceIfUnModifiedSince(const std::string& value);
void setSourceIfModifiedSince(const std::string& value);
void setMetadataDirective(const CopyActionList& action);
void setAcl(const CannedAccessControlList& acl);
void setEncodingType(const std::string& type) { encodingType_ = type; }
const std::string& SourceIfMatchEtag() const;
const std::string& SourceIfNotMatchEtag() const;
const std::string& SourceIfUnModifiedSince() const;
const std::string& SourceIfModifiedSince() const;
protected:
virtual int validate() const;
private:
std::string srcBucket_;
std::string srcKey_;
std::string encodingType_;
ObjectMetaData metaData_;
};
}
} | YifuLiu/AliOS-Things | components/oss/include/alibabacloud/oss/model/MultiCopyObjectRequest.h | C++ | apache-2.0 | 4,378 |
/*
* Copyright 2009-2018 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.
*/
#pragma once
#include <alibabacloud/oss/Export.h>
#include <alibabacloud/oss/Types.h>
#include <alibabacloud/oss/encryption/ContentCryptoMaterial.h>
namespace AlibabaCloud
{
namespace OSS
{
class ALIBABACLOUD_OSS_EXPORT MultipartUploadCryptoContext
{
public:
MultipartUploadCryptoContext():dataSize_(0), partSize_(0) {}
~MultipartUploadCryptoContext() {}
const ContentCryptoMaterial& ContentMaterial() const { return content_; }
const std::string& UploadId() const { return uploadId_; }
int64_t PartSize() const { return partSize_; }
int64_t DataSize() const { return dataSize_; }
void setContentMaterial(const ContentCryptoMaterial& content) { content_ = content; }
void setUploadId(const std::string& uploadId) { uploadId_ = uploadId; }
void setPartSize(int64_t size) { partSize_ = size; }
void setDataSize(int64_t size) { dataSize_ = size; }
private:
ContentCryptoMaterial content_;
int64_t dataSize_;
int64_t partSize_;
std::string uploadId_;
};
}
}
| YifuLiu/AliOS-Things | components/oss/include/alibabacloud/oss/model/MultipartUploadCryptoContext.h | C++ | apache-2.0 | 1,764 |
/*
* 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.
*/
#pragma once
#include <string>
#include <alibabacloud/oss/Export.h>
#include <alibabacloud/oss/Types.h>
namespace AlibabaCloud
{
namespace OSS
{
class ALIBABACLOUD_OSS_EXPORT ObjectCallbackBuilder
{
public:
enum Type
{
URL = 0,
JSON
};
ObjectCallbackBuilder(const std::string& url, const std::string& body);
ObjectCallbackBuilder(const std::string& url, const std::string& body,
const std::string& host, Type type);
const std::string& CallbackUrl() const { return callbackUrl_; }
const std::string& CallbackHost() const { return callbackHost_; }
const std::string& CallbackBody() const { return callbackBody_; }
Type CallbackBodyType() const { return callbackBodyType_; }
void setCallbackUrl(const std::string& url) { callbackUrl_ = url; }
void setCallbackHost(const std::string& host) { callbackHost_ = host; }
void setCallbackBody(const std::string& body) { callbackBody_ = body; }
void setCallbackBodyType(Type type) { callbackBodyType_ = type; }
std::string build();
private:
std::string callbackUrl_;
std::string callbackHost_;
std::string callbackBody_;
Type callbackBodyType_;
};
class ALIBABACLOUD_OSS_EXPORT ObjectCallbackVariableBuilder
{
public:
ObjectCallbackVariableBuilder() {};
const HeaderCollection& CallbackVariable() const { return callbackVariable_; }
bool addCallbackVariable(const std::string &key, const std::string& value);
std::string build();
private:
HeaderCollection callbackVariable_;
};
}
}
| YifuLiu/AliOS-Things | components/oss/include/alibabacloud/oss/model/ObjectCallbackBuilder.h | C++ | apache-2.0 | 2,311 |
/*
* 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.
*/
#pragma once
#include <string>
#include <alibabacloud/oss/Export.h>
#include <alibabacloud/oss/Types.h>
namespace AlibabaCloud
{
namespace OSS
{
class ALIBABACLOUD_OSS_EXPORT ObjectMetaData
{
public:
ObjectMetaData() = default;
ObjectMetaData(const HeaderCollection& data);
ObjectMetaData& operator=(const HeaderCollection& data);
const std::string& LastModified() const;
const std::string& ExpirationTime() const;
int64_t ContentLength() const ;
const std::string& ContentType() const;
const std::string& ContentEncoding() const;
const std::string& CacheControl() const;
const std::string& ContentDisposition() const;
const std::string& ETag() const;
const std::string& ContentMd5() const;
const std::string& ObjectType() const;
const std::string& VersionId() const;
uint64_t CRC64() const;
void setExpirationTime(const std::string& value);
void setContentLength(int64_t value);
void setContentType(const std::string& value);
void setContentEncoding(const std::string& value);
void setCacheControl(const std::string& value);
void setContentDisposition(const std::string& value);
void setETag(const std::string& value);
void setContentMd5(const std::string& value);
void setCrc64(uint64_t value);
void addHeader(const std::string& key, const std::string& value);
bool hasHeader(const std::string& key) const;
void removeHeader(const std::string& key);
MetaData& HttpMetaData();
const MetaData& HttpMetaData() const;
void addUserHeader(const std::string& key, const std::string& value);
bool hasUserHeader(const std::string& key) const;
void removeUserHeader(const std::string& key);
MetaData& UserMetaData();
const MetaData& UserMetaData() const;
HeaderCollection toHeaderCollection() const;
private:
MetaData userMetaData_;
MetaData metaData_;
};
}
}
| YifuLiu/AliOS-Things | components/oss/include/alibabacloud/oss/model/ObjectMetaData.h | C++ | apache-2.0 | 2,766 |
/*
* 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.
*/
#pragma once
#include <alibabacloud/oss/Export.h>
#include <alibabacloud/oss/OssRequest.h>
#include <alibabacloud/oss/Types.h>
namespace AlibabaCloud
{
namespace OSS
{
class SelectObjectRequest;
class ALIBABACLOUD_OSS_EXPORT OutputFormat
{
public:
virtual ~OutputFormat() {};
void setKeepAllColumns(bool keepAllColumns);
void setOutputRawData(bool outputRawData);
void setEnablePayloadCrc(bool enablePayloadCrc);
void setOutputHeader(bool outputHeader);
bool OutputRawData() const;
bool KeepAllColumns() const;
bool EnablePayloadCrc() const;
bool OutputHeader() const;
protected:
OutputFormat();
friend SelectObjectRequest;
virtual int validate() const;
virtual std::string toXML() const = 0;
virtual std::string Type() const = 0;
private:
bool keepAllColumns_;
bool outputRawData_;
bool enablePayloadCrc_;
bool outputHeader_;
};
class ALIBABACLOUD_OSS_EXPORT CSVOutputFormat : public OutputFormat
{
public:
CSVOutputFormat();
CSVOutputFormat(
const std::string& recordDelimiter,
const std::string& fieldDelimiter);
void setRecordDelimiter(const std::string& recordDelimiter);
void setFieldDelimiter(const std::string& fieldDelimiter);
const std::string& RecordDelimiter() const;
const std::string& FieldDelimiter() const;
protected:
virtual std::string toXML() const;
virtual std::string Type() const;
private:
std::string recordDelimiter_;
std::string fieldDelimiter_;
};
class ALIBABACLOUD_OSS_EXPORT JSONOutputFormat : public OutputFormat
{
public:
JSONOutputFormat();
JSONOutputFormat(const std::string& recordDelimiter);
void setRecordDelimiter(const std::string& recordDelimiter);
const std::string& RecordDelimiter() const;
protected:
virtual std::string toXML() const;
virtual std::string Type() const;
private:
std::string recordDelimiter_;
};
}
} | YifuLiu/AliOS-Things | components/oss/include/alibabacloud/oss/model/OutputFormat.h | C++ | apache-2.0 | 2,707 |
/*
* 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.
*/
#pragma once
#include <string>
#include <alibabacloud/oss/Export.h>
namespace AlibabaCloud
{
namespace OSS
{
class ALIBABACLOUD_OSS_EXPORT Owner
{
public:
Owner() = default;
Owner(const std::string& id, const std::string& name) :
id_(id),
displayName_(name)
{}
Owner(const Owner& rhs) :
id_(rhs.id_),
displayName_(rhs.displayName_)
{}
Owner(Owner&& lhs) :
id_(std::move(lhs.id_)),
displayName_(std::move(lhs.displayName_))
{}
Owner& operator=(const Owner& rhs)
{
id_ = rhs.id_;
displayName_ = rhs.displayName_;
return *this;
}
Owner& operator=(Owner&& lhs)
{
id_ = std::move(lhs.id_);
displayName_ = std::move(lhs.displayName_);
return *this;
}
const std::string& Id() const { return id_; }
const std::string& DisplayName() const { return displayName_; };
private:
std::string id_;
std::string displayName_;
};
}
}
| YifuLiu/AliOS-Things | components/oss/include/alibabacloud/oss/model/Owner.h | C++ | apache-2.0 | 1,745 |
/*
* 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.
*/
#pragma once
#include <alibabacloud/oss/Export.h>
#include <alibabacloud/oss/Types.h>
namespace AlibabaCloud
{
namespace OSS
{
class ListPartsResult;
class ResumableUploader;
class ResumableCopier;
class ALIBABACLOUD_OSS_EXPORT Part
{
public:
Part() :partNumber_(0), size_(0), cRC64_(0) {}
Part(int32_t partNumber, const std::string& eTag):partNumber_(partNumber), eTag_(eTag){}
int32_t PartNumber() const { return partNumber_; }
int64_t Size() const { return size_; }
uint64_t CRC64() const { return cRC64_; }
const std::string& LastModified() const { return lastModified_; }
const std::string& ETag() const { return eTag_; }
private:
friend class ListPartsResult;
friend class ResumableUploader;
friend class ResumableCopier;
int32_t partNumber_;
int64_t size_;
uint64_t cRC64_;
std::string lastModified_;
std::string eTag_;
};
using PartList = std::vector<Part>;
}
}
| YifuLiu/AliOS-Things | components/oss/include/alibabacloud/oss/model/Part.h | C++ | apache-2.0 | 1,654 |
/*
* 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.
*/
#pragma once
#include <alibabacloud/oss/Export.h>
#include <alibabacloud/oss/OssRequest.h>
#include <alibabacloud/oss/Types.h>
#include <alibabacloud/oss/model/ObjectMetaData.h>
#include <alibabacloud/oss/http/HttpType.h>
namespace AlibabaCloud
{
namespace OSS
{
class ALIBABACLOUD_OSS_EXPORT PostVodPlaylistRequest : public LiveChannelRequest
{
public:
PostVodPlaylistRequest(const std::string& bucket, const std::string& channelName,
const std::string& playList, uint64_t startTime, uint64_t endTime);
void setPlayList(const std::string& playList);
void setStartTime(uint64_t startTime);
void setEndTime(uint64_t endTime);
protected:
virtual ParameterCollection specialParameters() const;
virtual int validate() const;
private:
std::string playList_;
uint64_t startTime_;
uint64_t endTime_;
};
}
}
| YifuLiu/AliOS-Things | components/oss/include/alibabacloud/oss/model/PostVodPlaylistRequest.h | C++ | apache-2.0 | 1,540 |
/*
* 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.
*/
#pragma once
#include <alibabacloud/oss/Export.h>
#include <alibabacloud/oss/OssRequest.h>
#include <alibabacloud/oss/Types.h>
namespace AlibabaCloud
{
namespace OSS
{
class ALIBABACLOUD_OSS_EXPORT ProcessObjectRequest: public OssObjectRequest
{
public:
ProcessObjectRequest(const std::string& bucket, const std::string& key);
ProcessObjectRequest(const std::string& bucket, const std::string& key,
const std::string& process);
void setProcess(const std::string& process);
protected:
virtual ParameterCollection specialParameters() const;
virtual std::string payload() const;
private:
std::string process_;
};
}
} | YifuLiu/AliOS-Things | components/oss/include/alibabacloud/oss/model/ProcessObjectRequest.h | C++ | apache-2.0 | 1,328 |
/*
* 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.
*/
#pragma once
#include <alibabacloud/oss/Export.h>
#include <alibabacloud/oss/OssRequest.h>
#include <alibabacloud/oss/Types.h>
#include <alibabacloud/oss/model/ObjectMetaData.h>
#include <alibabacloud/oss/http/HttpType.h>
namespace AlibabaCloud
{
namespace OSS
{
class ALIBABACLOUD_OSS_EXPORT PutLiveChannelRequest : public LiveChannelRequest
{
public:
PutLiveChannelRequest(const std::string& bucket, const std::string& channelName,
const std::string& type);
void setChannelType(const std::string& type);
void setStatus(LiveChannelStatus status);
void setDescripition(const std::string& description);
void setPlayListName(const std::string& playListName);
void setRoleName(const std::string& roleName);
void setDestBucket(const std::string& destBucket);
void setNotifyTopic(const std::string& notifyTopic);
void setFragDuration(uint64_t fragDuration);
void setFragCount(uint64_t fragCount);
void setInterval(uint64_t interval);
protected:
virtual ParameterCollection specialParameters() const;
virtual std::string payload() const;
virtual int validate() const;
private:
std::string channelType_;
std::string description_;
std::string playListName_;
std::string roleName_;
std::string destBucket_;
std::string notifyTopic_;
LiveChannelStatus status_;
uint64_t fragDuration_;
uint64_t fragCount_;
uint64_t interval_;
bool snapshot_;
};
}
}
| YifuLiu/AliOS-Things | components/oss/include/alibabacloud/oss/model/PutLiveChannelRequest.h | C++ | apache-2.0 | 2,207 |
/*
* 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.
*/
#pragma once
#include <memory>
#include <iostream>
#include <alibabacloud/oss/OssResult.h>
#include <alibabacloud/oss/model/Owner.h>
#include <alibabacloud/oss/Types.h>
namespace AlibabaCloud
{
namespace OSS
{
class ALIBABACLOUD_OSS_EXPORT PutLiveChannelResult : public OssResult
{
public:
PutLiveChannelResult();
PutLiveChannelResult(const std::string& data);
PutLiveChannelResult(const std::shared_ptr<std::iostream>& data);
PutLiveChannelResult& operator=(const std::string& data);
const std::string& PublishUrl() const;
const std::string& PlayUrl() const;
private:
std::string publishUrl_;
std::string playUrl_;
};
}
}
| YifuLiu/AliOS-Things | components/oss/include/alibabacloud/oss/model/PutLiveChannelResult.h | C++ | apache-2.0 | 1,338 |
/*
* 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.
*/
#pragma once
#include <alibabacloud/oss/Export.h>
#include <alibabacloud/oss/OssRequest.h>
#include <alibabacloud/oss/Types.h>
#include <alibabacloud/oss/model/ObjectMetaData.h>
#include <alibabacloud/oss/http/HttpType.h>
namespace AlibabaCloud
{
namespace OSS
{
class ALIBABACLOUD_OSS_EXPORT PutLiveChannelStatusRequest : public LiveChannelRequest
{
public:
PutLiveChannelStatusRequest(const std::string& bucket, const std::string& channelName);
PutLiveChannelStatusRequest(const std::string& bucket, const std::string& channelName,
LiveChannelStatus status);
void setStatus(LiveChannelStatus status);
protected:
virtual ParameterCollection specialParameters() const;
virtual int validate() const;
private:
std::string channelName_;
LiveChannelStatus status_;
};
}
}
| YifuLiu/AliOS-Things | components/oss/include/alibabacloud/oss/model/PutLiveChannelStatusRequest.h | C++ | apache-2.0 | 1,493 |
/*
* 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.
*/
#pragma once
#include <alibabacloud/oss/Export.h>
#include <alibabacloud/oss/ServiceRequest.h>
#include <alibabacloud/oss/Types.h>
#include <alibabacloud/oss/model/ObjectMetaData.h>
#include <alibabacloud/oss/http/HttpType.h>
namespace AlibabaCloud
{
namespace OSS
{
class ALIBABACLOUD_OSS_EXPORT PutObjectByUrlRequest : public ServiceRequest
{
public:
PutObjectByUrlRequest(const std::string& url,
const std::shared_ptr<std::iostream>& content);
PutObjectByUrlRequest(const std::string& url,
const std::shared_ptr<std::iostream>& content,
const ObjectMetaData& metaData);
virtual HeaderCollection Headers() const;
virtual ParameterCollection Parameters() const;
virtual std::shared_ptr<std::iostream> Body() const;
private:
std::shared_ptr<std::iostream> content_;
ObjectMetaData metaData_;
};
}
}
| YifuLiu/AliOS-Things | components/oss/include/alibabacloud/oss/model/PutObjectByUrlRequest.h | C++ | apache-2.0 | 1,543 |
/*
* 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.
*/
#pragma once
#include <alibabacloud/oss/Export.h>
#include <alibabacloud/oss/OssRequest.h>
#include <alibabacloud/oss/Types.h>
#include <alibabacloud/oss/model/ObjectMetaData.h>
namespace AlibabaCloud
{
namespace OSS
{
class ALIBABACLOUD_OSS_EXPORT PutObjectRequest: public OssObjectRequest
{
public:
PutObjectRequest(const std::string& bucket, const std::string& key,
const std::shared_ptr<std::iostream>& content);
PutObjectRequest(const std::string& bucket, const std::string& key,
const std::shared_ptr<std::iostream>& content,
const ObjectMetaData& meta);
void setCacheControl(const std::string& value);
void setContentDisposition(const std::string& value);
void setContentEncoding(const std::string& value);
void setContentMd5(const std::string& value);
void setExpires(const std::string& value);
void setCallback(const std::string& callback, const std::string& callbackVar = "");
void setTrafficLimit(uint64_t value);
void setTagging(const std::string& value);
ObjectMetaData& MetaData();
virtual std::shared_ptr<std::iostream> Body() const;
protected:
virtual HeaderCollection specialHeaders() const;
virtual int validate() const;
private:
std::shared_ptr<std::iostream> content_;
ObjectMetaData metaData_;
};
}
}
| YifuLiu/AliOS-Things | components/oss/include/alibabacloud/oss/model/PutObjectRequest.h | C++ | apache-2.0 | 2,094 |
/*
* 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.
*/
#pragma once
#include <alibabacloud/oss/OssResult.h>
#include <alibabacloud/oss/Types.h>
namespace AlibabaCloud
{
namespace OSS
{
class ALIBABACLOUD_OSS_EXPORT PutObjectResult :public OssObjectResult
{
public:
PutObjectResult();
PutObjectResult(const HeaderCollection& header);
PutObjectResult(const HeaderCollection& header, const std::shared_ptr<std::iostream>& content);
PutObjectResult(const std::string eTag, const uint64_t crc64) :eTag_(eTag), crc64_(crc64) {}
const std::string& ETag() const;
uint64_t CRC64();
const std::shared_ptr<std::iostream>& Content() const;
private:
std::string eTag_;
uint64_t crc64_;
std::shared_ptr<std::iostream> content_;
};
}
}
| YifuLiu/AliOS-Things | components/oss/include/alibabacloud/oss/model/PutObjectResult.h | C++ | apache-2.0 | 1,437 |
/*
* 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.
*/
#pragma once
#include <string>
#include <alibabacloud/oss/Export.h>
namespace AlibabaCloud
{
namespace OSS
{
class ALIBABACLOUD_OSS_EXPORT QosConfiguration
{
public:
QosConfiguration():
totalUploadBandwidth_(-1), intranetUploadBandwidth_(-1),
extranetUploadBandwidth_(-1), totalDownloadBandwidth_(-1),
intranetDownloadBandwidth_(-1), extranetDownloadBandwidth_(-1),
totalQps_(-1), intranetQps_(-1), extranetQps_(-1)
{
}
int64_t TotalUploadBandwidth() const { return totalUploadBandwidth_; }
int64_t IntranetUploadBandwidth() const { return intranetUploadBandwidth_; }
int64_t ExtranetUploadBandwidth() const { return extranetUploadBandwidth_; }
int64_t TotalDownloadBandwidth() const { return totalDownloadBandwidth_; }
int64_t IntranetDownloadBandwidth() const { return intranetDownloadBandwidth_; }
int64_t ExtranetDownloadBandwidth() const { return extranetDownloadBandwidth_; }
int64_t TotalQps() const { return totalQps_; }
int64_t IntranetQps() const { return intranetQps_; }
int64_t ExtranetQps() const { return extranetQps_; }
void setTotalUploadBandwidth(int64_t value) { totalUploadBandwidth_ = value; }
void setIntranetUploadBandwidth(int64_t value) { intranetUploadBandwidth_ = value; }
void setExtranetUploadBandwidth(int64_t value) { extranetUploadBandwidth_ = value; }
void setTotalDownloadBandwidth(int64_t value) { totalDownloadBandwidth_ = value; }
void setIntranetDownloadBandwidth(int64_t value) { intranetDownloadBandwidth_ = value; }
void setExtranetDownloadBandwidth(int64_t value) { extranetDownloadBandwidth_ = value; }
void setTotalQps(int64_t value) { totalQps_ = value; }
void setIntranetQps(int64_t value) { intranetQps_ = value; }
void setExtranetQps(int64_t value) { extranetQps_ = value; }
private:
int64_t totalUploadBandwidth_;
int64_t intranetUploadBandwidth_;
int64_t extranetUploadBandwidth_;
int64_t totalDownloadBandwidth_;
int64_t intranetDownloadBandwidth_;
int64_t extranetDownloadBandwidth_;
int64_t totalQps_;
int64_t intranetQps_;
int64_t extranetQps_;
};
}
} | YifuLiu/AliOS-Things | components/oss/include/alibabacloud/oss/model/QosConfiguration.h | C++ | apache-2.0 | 2,940 |
/*
* 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.
*/
#pragma once
#include <alibabacloud/oss/Export.h>
#include <alibabacloud/oss/OssRequest.h>
#include <string>
namespace AlibabaCloud
{
namespace OSS
{
class ALIBABACLOUD_OSS_EXPORT RestoreObjectRequest: public OssObjectRequest
{
public:
RestoreObjectRequest(const std::string& bucket, const std::string& key);
void setDays(uint32_t days);
void setTierType(TierType type);
protected:
virtual std::string payload() const;
virtual ParameterCollection specialParameters() const;
private:
uint32_t days_;
TierType tierType_;
bool tierTypeIsSet_;
};
}
}
| YifuLiu/AliOS-Things | components/oss/include/alibabacloud/oss/model/RestoreObjectRequest.h | C++ | apache-2.0 | 1,263 |
/*
* 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.
*/
#pragma once
#include <alibabacloud/oss/Export.h>
#include <alibabacloud/oss/OssResult.h>
#include <alibabacloud/oss/Types.h>
namespace AlibabaCloud
{
namespace OSS
{
class ALIBABACLOUD_OSS_EXPORT RestoreObjectResult : public OssObjectResult
{
public:
RestoreObjectResult();
RestoreObjectResult(const HeaderCollection& header);
};
}
}
| YifuLiu/AliOS-Things | components/oss/include/alibabacloud/oss/model/RestoreObjectResult.h | C++ | apache-2.0 | 1,032 |
/*
* 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.
*/
#pragma once
#include <alibabacloud/oss/OssRequest.h>
#include <alibabacloud/oss/model/GetObjectRequest.h>
#include <alibabacloud/oss/Types.h>
#include <alibabacloud/oss/model/InputFormat.h>
#include <alibabacloud/oss/model/OutputFormat.h>
#include <alibabacloud/oss/model/CreateSelectObjectMetaRequest.h>
namespace AlibabaCloud
{
namespace OSS
{
enum ExpressionType
{
SQL,
};
class OssClientImpl;
class ALIBABACLOUD_OSS_EXPORT SelectObjectRequest : public GetObjectRequest
{
public:
SelectObjectRequest(const std::string& bucket, const std::string& key);
void setExpression(const std::string& expression, ExpressionType type = SQL);
void setSkippedRecords(bool skipPartialDataRecord, uint64_t maxSkippedRecords);
void setInputFormat(InputFormat& inputFormat);
void setOutputFormat(OutputFormat& OutputFormat);
uint64_t MaxSkippedRecordsAllowed() const;
void setResponseStreamFactory(const IOStreamFactory& factory);
protected:
friend class OssClientImpl;
virtual std::string payload() const;
virtual int validate() const;
virtual ParameterCollection specialParameters() const;
int dispose() const;
private:
ExpressionType expressionType_;
std::string expression_;
bool skipPartialDataRecord_;
uint64_t maxSkippedRecordsAllowed_;
InputFormat *inputFormat_;
OutputFormat *outputFormat_;
mutable std::shared_ptr<std::streambuf> streamBuffer_;
mutable std::shared_ptr<std::iostream> upperContent_;
IOStreamFactory upperResponseStreamFactory_;
};
}
} | YifuLiu/AliOS-Things | components/oss/include/alibabacloud/oss/model/SelectObjectRequest.h | C++ | apache-2.0 | 2,201 |
/*
* 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.
*/
#pragma once
#include <alibabacloud/oss/Export.h>
#include <alibabacloud/oss/OssRequest.h>
#include <alibabacloud/oss/Types.h>
namespace AlibabaCloud
{
namespace OSS
{
class ALIBABACLOUD_OSS_EXPORT SetBucketAclRequest: public OssBucketRequest
{
public:
SetBucketAclRequest(const std::string& bucket, CannedAccessControlList acl);
void setAcl(CannedAccessControlList acl);
protected:
virtual HeaderCollection specialHeaders() const;
virtual ParameterCollection specialParameters() const;
private:
CannedAccessControlList acl_;
};
}
}
| YifuLiu/AliOS-Things | components/oss/include/alibabacloud/oss/model/SetBucketAclRequest.h | C++ | apache-2.0 | 1,227 |
/*
* 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.
*/
#pragma once
#include <alibabacloud/oss/Export.h>
#include <alibabacloud/oss/OssRequest.h>
#include <alibabacloud/oss/Types.h>
#include <alibabacloud/oss/model/CORSRule.h>
namespace AlibabaCloud
{
namespace OSS
{
class ALIBABACLOUD_OSS_EXPORT SetBucketCorsRequest : public OssBucketRequest
{
public:
SetBucketCorsRequest(const std::string& bucket);
void addCORSRule(const CORSRule& rule);
void setCORSRules(const CORSRuleList& rules);
void clearCORSRules() { ruleList_.clear(); }
const CORSRuleList& CORSRules() const { return ruleList_; }
protected:
virtual std::string payload() const;
virtual ParameterCollection specialParameters() const;
virtual int validate() const;
private:
CORSRuleList ruleList_;
};
}
}
| YifuLiu/AliOS-Things | components/oss/include/alibabacloud/oss/model/SetBucketCorsRequest.h | C++ | apache-2.0 | 1,439 |
/*
* 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.
*/
#pragma once
#include <alibabacloud/oss/Export.h>
#include <alibabacloud/oss/OssRequest.h>
#include <alibabacloud/oss/Types.h>
namespace AlibabaCloud
{
namespace OSS
{
class ALIBABACLOUD_OSS_EXPORT SetBucketEncryptionRequest : public OssBucketRequest
{
public:
SetBucketEncryptionRequest(const std::string& bucket, SSEAlgorithm sse = SSEAlgorithm::AES256, const std::string& key = "");
void setSSEAlgorithm(SSEAlgorithm sse);
void setKMSMasterKeyID(const std::string& key);
protected:
virtual ParameterCollection specialParameters() const;
virtual std::string payload() const;
private:
SSEAlgorithm SSEAlgorithm_;
std::string KMSMasterKeyID_;
};
}
}
| YifuLiu/AliOS-Things | components/oss/include/alibabacloud/oss/model/SetBucketEncryptionRequest.h | C++ | apache-2.0 | 1,356 |
/*
* 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.
*/
#pragma once
#include <alibabacloud/oss/Export.h>
#include <alibabacloud/oss/OssRequest.h>
#include <alibabacloud/oss/model/InventoryConfiguration.h>
namespace AlibabaCloud
{
namespace OSS
{
class ALIBABACLOUD_OSS_EXPORT SetBucketInventoryConfigurationRequest : public OssBucketRequest
{
public:
SetBucketInventoryConfigurationRequest(const std::string& bucket);
SetBucketInventoryConfigurationRequest(const std::string& bucket, const InventoryConfiguration& conf);
void setInventoryConfiguration(InventoryConfiguration conf);
protected:
virtual ParameterCollection specialParameters() const;
virtual std::string payload() const;
private:
InventoryConfiguration inventoryConfiguration_;
};
}
}
| YifuLiu/AliOS-Things | components/oss/include/alibabacloud/oss/model/SetBucketInventoryConfigurationRequest.h | C++ | apache-2.0 | 1,392 |
/*
* 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.
*/
#pragma once
#include <alibabacloud/oss/Export.h>
#include <alibabacloud/oss/OssRequest.h>
#include <alibabacloud/oss/model/LifecycleRule.h>
namespace AlibabaCloud
{
namespace OSS
{
class ALIBABACLOUD_OSS_EXPORT SetBucketLifecycleRequest : public OssBucketRequest
{
public:
SetBucketLifecycleRequest(const std::string& bucket);
void addLifecycleRule(const LifecycleRule& rule) { lifecycleRules_.push_back(rule); }
void setLifecycleRules(const LifecycleRuleList& ruleList) { lifecycleRules_= ruleList; }
void clearLifecycleRules() { lifecycleRules_.clear(); }
const LifecycleRuleList& LifecycleRules() const { return lifecycleRules_; }
protected:
virtual std::string payload() const;
virtual ParameterCollection specialParameters() const;
virtual int validate() const;
private:
LifecycleRuleList lifecycleRules_;
};
}
}
| YifuLiu/AliOS-Things | components/oss/include/alibabacloud/oss/model/SetBucketLifecycleRequest.h | C++ | apache-2.0 | 1,587 |
/*
* 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.
*/
#pragma once
#include <alibabacloud/oss/Export.h>
#include <alibabacloud/oss/OssRequest.h>
namespace AlibabaCloud
{
namespace OSS
{
class ALIBABACLOUD_OSS_EXPORT SetBucketLoggingRequest : public OssBucketRequest
{
public:
SetBucketLoggingRequest(const std::string& bucket);
SetBucketLoggingRequest(const std::string& bucket,
const std::string& targetBucket, const std::string& targetPrefix);
void setTargetBucket(const std::string& bucket) { targetBucket_ = bucket; }
void setTargetPrefix(const std::string& prefix) { targetPrefix_ = prefix; }
protected:
virtual std::string payload() const;
virtual ParameterCollection specialParameters() const;
virtual int validate() const;
private:
std::string targetBucket_;
std::string targetPrefix_;
};
}
}
| YifuLiu/AliOS-Things | components/oss/include/alibabacloud/oss/model/SetBucketLoggingRequest.h | C++ | apache-2.0 | 1,527 |
/*
* 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.
*/
#pragma once
#include <alibabacloud/oss/Export.h>
#include <alibabacloud/oss/OssRequest.h>
#include <alibabacloud/oss/Types.h>
namespace AlibabaCloud
{
namespace OSS
{
class ALIBABACLOUD_OSS_EXPORT SetBucketRequestPaymentRequest : public OssBucketRequest
{
public:
SetBucketRequestPaymentRequest(const std::string& bucket);
SetBucketRequestPaymentRequest(const std::string& bucket, RequestPayer payer);
void setRequestPayer(RequestPayer payer) { payer_ = payer; }
protected:
virtual std::string payload() const;
virtual ParameterCollection specialParameters() const;
private:
RequestPayer payer_;
};
}
}
| YifuLiu/AliOS-Things | components/oss/include/alibabacloud/oss/model/SetBucketPaymentRequest.h | C++ | apache-2.0 | 1,306 |
/*
* 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.
*/
#pragma once
#include <alibabacloud/oss/Export.h>
#include <alibabacloud/oss/OssRequest.h>
namespace AlibabaCloud
{
namespace OSS
{
class ALIBABACLOUD_OSS_EXPORT SetBucketPolicyRequest : public OssBucketRequest
{
public:
SetBucketPolicyRequest(const std::string& bucket);
SetBucketPolicyRequest(const std::string& bucket, const std::string& policy);
void setPolicy(const std::string& policy) { policy_ = policy; }
protected:
virtual std::string payload() const;
virtual ParameterCollection specialParameters() const;
private:
std::string policy_;
};
}
}
| YifuLiu/AliOS-Things | components/oss/include/alibabacloud/oss/model/SetBucketPolicyRequest.h | C++ | apache-2.0 | 1,252 |
/*
* 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.
*/
#pragma once
#include <alibabacloud/oss/Export.h>
#include <alibabacloud/oss/OssRequest.h>
#include <alibabacloud/oss/model/QosConfiguration.h>
namespace AlibabaCloud
{
namespace OSS
{
class ALIBABACLOUD_OSS_EXPORT SetBucketQosInfoRequest : public OssBucketRequest
{
public:
SetBucketQosInfoRequest(const std::string& bucket);
SetBucketQosInfoRequest(const std::string& bucket, const QosConfiguration& qos);
protected:
virtual std::string payload() const;
virtual ParameterCollection specialParameters() const;
private:
QosConfiguration qosInfo_;
};
}
}
| YifuLiu/AliOS-Things | components/oss/include/alibabacloud/oss/model/SetBucketQosInfoRequest.h | C++ | apache-2.0 | 1,244 |
/*
* 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.
*/
#pragma once
#include <alibabacloud/oss/Export.h>
#include <alibabacloud/oss/OssRequest.h>
#include <alibabacloud/oss/Types.h>
#include <vector>
namespace AlibabaCloud
{
namespace OSS
{
class ALIBABACLOUD_OSS_EXPORT SetBucketRefererRequest : public OssBucketRequest
{
public:
SetBucketRefererRequest(const std::string& bucket);
SetBucketRefererRequest(const std::string& bucket, const RefererList& refererList);
SetBucketRefererRequest(const std::string& bucket, const RefererList& refererList,
bool allowEmptyReferer);
void setAllowEmptyReferer(bool allow)
{
allowEmptyReferer_ = allow;
}
void addReferer(const std::string& referer)
{
refererList_.push_back(referer);
}
void clearRefererList()
{
refererList_.clear();
}
protected:
virtual std::string payload() const;
virtual ParameterCollection specialParameters() const;
private:
bool allowEmptyReferer_;
RefererList refererList_;
};
}
}
| YifuLiu/AliOS-Things | components/oss/include/alibabacloud/oss/model/SetBucketRefererRequest.h | C++ | apache-2.0 | 1,778 |
/*
* 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.
*/
#pragma once
#include <alibabacloud/oss/Export.h>
#include <alibabacloud/oss/OssRequest.h>
namespace AlibabaCloud
{
namespace OSS
{
class ALIBABACLOUD_OSS_EXPORT SetBucketStorageCapacityRequest : public OssBucketRequest
{
public:
SetBucketStorageCapacityRequest(const std::string& bucket, int64_t storageCapacity);
protected:
virtual ParameterCollection specialParameters() const;
virtual std::string payload() const;
virtual int validate() const;
private:
int64_t storageCapacity_;
};
}
}
| YifuLiu/AliOS-Things | components/oss/include/alibabacloud/oss/model/SetBucketStorageCapacityRequest.h | C++ | apache-2.0 | 1,184 |
/*
* 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.
*/
#pragma once
#include <alibabacloud/oss/Export.h>
#include <alibabacloud/oss/OssRequest.h>
#include <alibabacloud/oss/model/Tagging.h>
namespace AlibabaCloud
{
namespace OSS
{
class ALIBABACLOUD_OSS_EXPORT SetBucketTaggingRequest : public OssBucketRequest
{
public:
SetBucketTaggingRequest(const std::string& bucket);
SetBucketTaggingRequest(const std::string& bucket, const Tagging& tagging);
void setTagging(const Tagging& tagging);
protected:
virtual std::string payload() const;
virtual ParameterCollection specialParameters() const;
virtual int validate() const;
private:
Tagging tagging_;
};
}
}
| YifuLiu/AliOS-Things | components/oss/include/alibabacloud/oss/model/SetBucketTaggingRequest.h | C++ | apache-2.0 | 1,308 |
/*
* 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.
*/
#pragma once
#include <alibabacloud/oss/Export.h>
#include <alibabacloud/oss/OssRequest.h>
namespace AlibabaCloud
{
namespace OSS
{
class ALIBABACLOUD_OSS_EXPORT SetBucketVersioningRequest : public OssBucketRequest
{
public:
SetBucketVersioningRequest(const std::string& bucket, VersioningStatus status);
void setStatus(VersioningStatus status);
protected:
virtual std::string payload() const;
virtual ParameterCollection specialParameters() const;
private:
VersioningStatus status_;
};
}
}
| YifuLiu/AliOS-Things | components/oss/include/alibabacloud/oss/model/SetBucketVersioningRequest.h | C++ | apache-2.0 | 1,222 |
/*
* 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.
*/
#pragma once
#include <alibabacloud/oss/Export.h>
#include <alibabacloud/oss/OssRequest.h>
namespace AlibabaCloud
{
namespace OSS
{
class ALIBABACLOUD_OSS_EXPORT SetBucketWebsiteRequest : public OssBucketRequest
{
public:
SetBucketWebsiteRequest(const std::string& bucket);
void setIndexDocument(const std::string& document)
{
indexDocument_ = document;
indexDocumentIsSet_ = true;
}
void setErrorDocument(const std::string& document)
{
errorDocument_ = document;
errorDocumentIsSet_ = true;
}
protected:
virtual std::string payload() const;
virtual ParameterCollection specialParameters() const;
virtual int validate() const;
private:
std::string indexDocument_;
bool indexDocumentIsSet_;
std::string errorDocument_;
bool errorDocumentIsSet_;
};
}
}
| YifuLiu/AliOS-Things | components/oss/include/alibabacloud/oss/model/SetBucketWebsiteRequest.h | C++ | apache-2.0 | 1,615 |
/*
* 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.
*/
#pragma once
#include <alibabacloud/oss/Export.h>
#include <alibabacloud/oss/OssRequest.h>
#include <alibabacloud/oss/Types.h>
#include <string>
namespace AlibabaCloud
{
namespace OSS
{
class ALIBABACLOUD_OSS_EXPORT SetObjectAclRequest: public OssObjectRequest
{
public:
SetObjectAclRequest(const std::string& bucket, const std::string& key);
SetObjectAclRequest(const std::string& bucket, const std::string& key,
CannedAccessControlList acl);
void setAcl(CannedAccessControlList acl);
protected:
virtual HeaderCollection specialHeaders() const;
virtual ParameterCollection specialParameters() const;
private:
CannedAccessControlList acl_;
bool hasSetAcl_ ;
};
}
}
| YifuLiu/AliOS-Things | components/oss/include/alibabacloud/oss/model/SetObjectAclRequest.h | C++ | apache-2.0 | 1,387 |
/*
* 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.
*/
#pragma once
#include <alibabacloud/oss/Export.h>
#include <alibabacloud/oss/OssResult.h>
#include <alibabacloud/oss/Types.h>
namespace AlibabaCloud
{
namespace OSS
{
class ALIBABACLOUD_OSS_EXPORT SetObjectAclResult : public OssObjectResult
{
public:
SetObjectAclResult();
SetObjectAclResult(const HeaderCollection& header);
};
}
}
| YifuLiu/AliOS-Things | components/oss/include/alibabacloud/oss/model/SetObjectAclResult.h | C++ | apache-2.0 | 1,029 |
/*
* 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.
*/
#pragma once
#include <alibabacloud/oss/Export.h>
#include <alibabacloud/oss/OssRequest.h>
#include <alibabacloud/oss/model/Tagging.h>
namespace AlibabaCloud
{
namespace OSS
{
class ALIBABACLOUD_OSS_EXPORT SetObjectTaggingRequest : public OssObjectRequest
{
public:
SetObjectTaggingRequest(const std::string& bucket, const std::string& key);
SetObjectTaggingRequest(const std::string& bucket, const std::string& key,
const Tagging& tagging);
void setTagging(const Tagging& tagging);
protected:
virtual std::string payload() const;
virtual ParameterCollection specialParameters() const;
virtual int validate() const;
private:
Tagging tagging_;
};
}
}
| YifuLiu/AliOS-Things | components/oss/include/alibabacloud/oss/model/SetObjectTaggingRequest.h | C++ | apache-2.0 | 1,414 |
/*
* 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.
*/
#pragma once
#include <alibabacloud/oss/Export.h>
#include <alibabacloud/oss/OssResult.h>
namespace AlibabaCloud
{
namespace OSS
{
class ALIBABACLOUD_OSS_EXPORT SetObjectTaggingResult : public OssObjectResult
{
public:
SetObjectTaggingResult(): OssObjectResult() {}
SetObjectTaggingResult(const HeaderCollection& headers): OssObjectResult(headers) {}
};
}
}
| YifuLiu/AliOS-Things | components/oss/include/alibabacloud/oss/model/SetObjectTaggingResult.h | C++ | apache-2.0 | 1,054 |
/*
* 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.
*/
#pragma once
#include <alibabacloud/oss/Export.h>
#include <alibabacloud/oss/Types.h>
namespace AlibabaCloud
{
namespace OSS
{
class ALIBABACLOUD_OSS_EXPORT Tag
{
public:
Tag() {};
Tag(const std::string& key, const std::string& value) :
key_(key), value_(value)
{}
void setKey(const std::string& key) { key_ = key; }
void setValue(const std::string& value) { value_ = value; }
const std::string& Key() const { return key_; }
const std::string& Value() const { return value_; }
private:
std::string key_;
std::string value_;
};
using TagSet = std::vector<Tag>;
class ALIBABACLOUD_OSS_EXPORT Tagging
{
public:
Tagging() {};
Tagging(const TagSet& tags) { tagSet_ = tags;}
const TagSet& Tags() const { return tagSet_; }
void setTags(const TagSet& tags) { tagSet_ = tags; }
void setTags(TagSet&& tags) { tagSet_ = std::move(tags); }
void addTag(const Tag& tag) { tagSet_.push_back(tag) ; }
void addTag(Tag&& tag) { tagSet_.push_back(std::move(tag)); }
void clear() { tagSet_.clear();}
std::string toQueryParameters();
private:
TagSet tagSet_;
};
}
}
| YifuLiu/AliOS-Things | components/oss/include/alibabacloud/oss/model/Tagging.h | C++ | apache-2.0 | 1,945 |
/*
* 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.
*/
#pragma once
#include <alibabacloud/oss/Export.h>
#include <alibabacloud/oss/OssRequest.h>
#include <alibabacloud/oss/Types.h>
#include <alibabacloud/oss/model/ObjectMetaData.h>
#include <alibabacloud/oss/http/HttpType.h>
namespace AlibabaCloud
{
namespace OSS
{
class ALIBABACLOUD_OSS_EXPORT UploadObjectRequest : public OssResumableBaseRequest
{
public:
UploadObjectRequest(const std::string& bucket, const std::string& key,
const std::string& filePath, const std::string& checkpointDir,
const uint64_t partSize, const uint32_t threadNum);
UploadObjectRequest(const std::string& bucket, const std::string& key,
const std::string& filePath, const std::string &checkpointDir,
const uint64_t partSize, const uint32_t threadNum, const ObjectMetaData& meta);
UploadObjectRequest(const std::string& bucket, const std::string& key,
const std::string& filePath, const std::string& checkpointDir,
const ObjectMetaData& meta);
UploadObjectRequest(const std::string& bucket, const std::string& key,
const std::string& filePath, const std::string& checkpointDir);
UploadObjectRequest(const std::string& bucket, const std::string& key,
const std::string& filePath);
std::shared_ptr<std::iostream> Content(){ return content_; }
const std::string& EncodingType() const{return encodingType_;}
const std::string& FilePath() const{return filePath_;}
const ObjectMetaData& MetaData() const { return metaData_; }
ObjectMetaData& MetaData() { return metaData_; }
UploadObjectRequest(const std::string& bucket, const std::string& key,
const std::wstring& filePath, const std::wstring& checkpointDir,
const uint64_t partSize, const uint32_t threadNum);
UploadObjectRequest(const std::string& bucket, const std::string& key,
const std::wstring& filePath, const std::wstring &checkpointDir,
const uint64_t partSize, const uint32_t threadNum, const ObjectMetaData& meta);
UploadObjectRequest(const std::string& bucket, const std::string& key,
const std::wstring& filePath, const std::wstring& checkpointDir,
const ObjectMetaData& meta);
UploadObjectRequest(const std::string& bucket, const std::string& key,
const std::wstring& filePath, const std::wstring& checkpointDir);
UploadObjectRequest(const std::string& bucket, const std::string& key,
const std::wstring& filePath);
const std::wstring& FilePathW() const { return filePathW_; }
void setCacheControl(const std::string& value){metaData_.addHeader(Http::CACHE_CONTROL, value);}
void setContentDisposition(const std::string& value){metaData_.addHeader(Http::CONTENT_DISPOSITION, value);}
void setContentEncoding(const std::string& value){metaData_.addHeader(Http::CONTENT_ENCODING, value);}
void setExpires(const std::string& value){metaData_.addHeader(Http::EXPIRES, value);}
void setAcl(CannedAccessControlList& acl);
void setCallback(const std::string& callback, const std::string& callbackVar = "");
void setEncodingType(const std::string& type) {encodingType_ = type; }
void setTagging(const std::string& value);
protected:
virtual int validate() const;
private:
std::string filePath_;
std::shared_ptr<std::iostream> content_;
ObjectMetaData metaData_;
std::string encodingType_;
std::wstring filePathW_;
bool isFileExist_;
};
}
} | YifuLiu/AliOS-Things | components/oss/include/alibabacloud/oss/model/UploadObjectRequest.h | C++ | apache-2.0 | 4,361 |
/*
* Copyright 2009-2018 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.
*/
#pragma once
#include <alibabacloud/oss/Export.h>
#include <alibabacloud/oss/OssRequest.h>
#include <sstream>
#include <iostream>
namespace AlibabaCloud
{
namespace OSS
{
class ALIBABACLOUD_OSS_EXPORT UploadPartCopyRequest: public OssObjectRequest
{
public:
UploadPartCopyRequest(const std::string& bucket, const std::string& key);
UploadPartCopyRequest(const std::string& bucket, const std::string& key,
const std::string& srcBucket, const std::string& srcKey);
UploadPartCopyRequest(const std::string& bucket, const std::string& key,
const std::string& srcBucket, const std::string& srcKey,
const std::string& uploadId, int partNumber);
UploadPartCopyRequest(const std::string& bucket, const std::string& key,
const std::string& srcBucket, const std::string& srcKey,
const std::string& uploadId, int partNumber,
const std::string& sourceIfMatchETag,
const std::string& sourceIfNotMatchETag,
const std::string& sourceIfModifiedSince,
const std::string& sourceIfUnModifiedSince);
void setPartNumber(uint32_t partNumber);
void setUploadId(const std::string& uploadId);
void SetCopySource(const std::string& srcBucket, const std::string& srcKey);
void setCopySourceRange(uint64_t begin, uint64_t end);
void SetSourceIfMatchETag(const std::string& value);
void SetSourceIfNotMatchETag(const std::string& value);
void SetSourceIfModifiedSince(const std::string& value);
void SetSourceIfUnModifiedSince(const std::string& value);
void setTrafficLimit(uint64_t value);
protected:
virtual ParameterCollection specialParameters() const;
virtual HeaderCollection specialHeaders() const;
virtual int validate() const;
private:
std::string uploadId_;
std::string sourceBucket_;
std::string sourceKey_;
uint32_t partNumber_;
uint64_t sourceRange_[2];
bool sourceRangeIsSet_;
std::string sourceIfMatchETag_;
bool sourceIfMatchETagIsSet_;
std::string sourceIfNotMatchETag_;
bool sourceIfNotMatchETagIsSet_;
std::string sourceIfModifiedSince_;
bool sourceIfModifiedSinceIsSet_;
std::string sourceIfUnModifiedSince_;
bool sourceIfUnModifiedSinceIsSet_;
uint64_t trafficLimit_;
};
}
}
| YifuLiu/AliOS-Things | components/oss/include/alibabacloud/oss/model/UploadPartCopyRequest.h | C++ | apache-2.0 | 3,243 |
/*
* Copyright 2009-2018 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.
*/
#pragma once
#include <string>
#include <memory>
#include <alibabacloud/oss/Export.h>
#include <alibabacloud/oss/Types.h>
#include <alibabacloud/oss/OssResult.h>
namespace AlibabaCloud
{
namespace OSS
{
class ALIBABACLOUD_OSS_EXPORT UploadPartCopyResult :public OssObjectResult
{
public:
UploadPartCopyResult();
UploadPartCopyResult(const std::string& data);
UploadPartCopyResult(const std::shared_ptr<std::iostream>& data,
const HeaderCollection &header);
UploadPartCopyResult& operator=(const std::string& data);
const std::string& LastModified() const;
const std::string& ETag() const;
const std::string& SourceVersionId() { return sourceVersionId_; }
private:
std::string lastModified_;
std::string eTag_;
std::string sourceVersionId_;
};
}
}
| YifuLiu/AliOS-Things | components/oss/include/alibabacloud/oss/model/UploadPartCopyResult.h | C++ | apache-2.0 | 1,537 |
/*
* Copyright 2009-2018 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.
*/
#pragma once
#include <alibabacloud/oss/Export.h>
#include <alibabacloud/oss/OssRequest.h>
#include <sstream>
#include <iostream>
namespace AlibabaCloud
{
namespace OSS
{
class ALIBABACLOUD_OSS_EXPORT UploadPartRequest: public OssObjectRequest
{
public:
UploadPartRequest(const std::string& bucket, const std::string& key,
const std::shared_ptr<std::iostream>& content);
UploadPartRequest(const std::string &bucket, const std::string& key,
int partNumber, const std::string& uploadId,
const std::shared_ptr<std::iostream>& content);
virtual std::shared_ptr<std::iostream> Body() const;
void setPartNumber(int partNumber);
void setUploadId(const std::string& uploadId);
void setConetent(const std::shared_ptr<std::iostream>& content);
void setContentLength(uint64_t length);
void setTrafficLimit(uint64_t value);
void setUserAgent(const std::string& ua);
int PartNumber() const;
protected:
virtual HeaderCollection specialHeaders() const;
virtual ParameterCollection specialParameters() const;
virtual int validate() const;
private:
int partNumber_;
std::string uploadId_;
std::shared_ptr<std::iostream> content_;
uint64_t contentLength_;
bool contentLengthIsSet_;
uint64_t trafficLimit_;
std::string userAgent_;
};
}
}
| YifuLiu/AliOS-Things | components/oss/include/alibabacloud/oss/model/UploadPartRequest.h | C++ | apache-2.0 | 2,070 |
/*
* 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.
*/
#pragma once
#include <alibabacloud/oss/OssResult.h>
namespace AlibabaCloud
{
namespace OSS
{
class ALIBABACLOUD_OSS_EXPORT VoidResult :public OssResult
{
public:
VoidResult() = default;
~VoidResult() = default;
private:
};
}
}
| YifuLiu/AliOS-Things | components/oss/include/alibabacloud/oss/model/VoidResult.h | C++ | apache-2.0 | 893 |
/*
* 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.
*/
#pragma once
#include <atomic>
#include <condition_variable>
#include <queue>
#include <vector>
#include <thread>
#include <mutex>
#include <unordered_map>
#include <alibabacloud/oss/Export.h>
#include <alibabacloud/oss/utils/Runnable.h>
namespace AlibabaCloud
{
namespace OSS
{
class ALIBABACLOUD_OSS_EXPORT Executor
{
public:
Executor();
virtual ~Executor();
virtual void execute(Runnable* task) = 0;
};
}
}
| YifuLiu/AliOS-Things | components/oss/include/alibabacloud/oss/utils/Executor.h | C++ | apache-2.0 | 1,104 |
/*
* 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.
*/
#pragma once
namespace AlibabaCloud
{
namespace OSS
{
template<typename E, typename R>
class Outcome
{
public:
Outcome():success_(false), e_(), r_()
{
}
Outcome(const E& e) :success_(false), e_(e)
{
}
Outcome(const R& r): success_(true), r_(r)
{
}
Outcome(E&& e) : success_(false), e_(std::forward<E>(e))
{
} // Error move constructor
Outcome(R&& r) : success_(true), r_(std::forward<R>(r))
{
} // Result move constructor
Outcome(const Outcome& other) :
success_(other.success_),
e_(other.e_),
r_(other.r_)
{
}
Outcome(Outcome&& other):
success_(other.success_),
e_(std::move(other.e_)),
r_(std::move(other.r_))
{
//*this = std::move(other);
}
Outcome& operator=(const Outcome& other)
{
if (this != &other) {
success_ = other.success_;
e_ = other.e_;
r_ = other.r_;
}
return *this;
}
Outcome& operator=(Outcome&& other)
{
if (this != &other)
{
success_ = other.success_;
r_ = std::move(other.r_);
e_ = std::move(other.e_);
}
return *this;
}
bool isSuccess()const { return success_; }
const E& error()const { return e_; }
const R& result()const { return r_; }
E& error() { return e_; }
R& result() { return r_; }
private:
bool success_;
E e_;
R r_;
};
}
}
| YifuLiu/AliOS-Things | components/oss/include/alibabacloud/oss/utils/Outcome.h | C++ | apache-2.0 | 2,359 |
/*
* 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.
*/
#pragma once
#include <functional>
#include <alibabacloud/oss/Export.h>
namespace AlibabaCloud
{
namespace OSS
{
class ALIBABACLOUD_OSS_EXPORT Runnable
{
public:
explicit Runnable(const std::function<void()> f);
void run()const;
private:
std::function<void()> f_;
};
}
}
| YifuLiu/AliOS-Things | components/oss/include/alibabacloud/oss/utils/Runnable.h | C++ | apache-2.0 | 963 |
/*
* 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/oss/OssClient.h>
#include "auth/SimpleCredentialsProvider.h"
#include "http/CurlHttpClient.h"
#include "OssClientImpl.h"
#include <fstream>
#include "utils/LogUtils.h"
#include "utils/Crc64.h"
using namespace AlibabaCloud::OSS;
static bool SdkInitDone = false;
bool AlibabaCloud::OSS::IsSdkInitialized()
{
return SdkInitDone;
}
void AlibabaCloud::OSS::InitializeSdk()
{
if (IsSdkInitialized())
return;
InitLogInner();
CurlHttpClient::initGlobalState();
SdkInitDone = true;
}
void AlibabaCloud::OSS::ShutdownSdk()
{
if (!IsSdkInitialized())
return;
CurlHttpClient::cleanupGlobalState();
DeinitLogInner();
SdkInitDone = false;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
void AlibabaCloud::OSS::SetLogLevel(LogLevel level)
{
SetLogLevelInner(level);
}
void AlibabaCloud::OSS::SetLogCallback(LogCallback callback)
{
SetLogCallbackInner(callback);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
uint64_t AlibabaCloud::OSS::ComputeCRC64(uint64_t crc, void *buf, size_t len)
{
return CRC64::CalcCRC(crc, buf, len);
}
uint64_t AlibabaCloud::OSS::CombineCRC64(uint64_t crc1, uint64_t crc2, uintmax_t len2)
{
return CRC64::CombineCRC(crc1, crc2, len2);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
OssClient::OssClient(const std::string &endpoint, const std::string & accessKeyId, const std::string & accessKeySecret, const ClientConfiguration & configuration) :
OssClient(endpoint, accessKeyId, accessKeySecret, "", configuration)
{
}
OssClient::OssClient(const std::string &endpoint, const std::string & accessKeyId, const std::string & accessKeySecret, const std::string & securityToken,
const ClientConfiguration & configuration) :
OssClient(endpoint, std::make_shared<SimpleCredentialsProvider>(accessKeyId, accessKeySecret, securityToken), configuration)
{
}
OssClient::OssClient(const std::string &endpoint, const Credentials &credentials, const ClientConfiguration &configuration) :
OssClient(endpoint, std::make_shared<SimpleCredentialsProvider>(credentials), configuration)
{
}
OssClient::OssClient(const std::string &endpoint, const std::shared_ptr<CredentialsProvider>& credentialsProvider, const ClientConfiguration & configuration) :
client_(std::make_shared<OssClientImpl>(endpoint, credentialsProvider, configuration))
{
}
OssClient::~OssClient()
{
}
#if (!OSS_DISABLE_BUCKET)
ListBucketsOutcome OssClient::ListBuckets() const
{
return client_->ListBuckets(ListBucketsRequest());
}
ListBucketsOutcome OssClient::ListBuckets(const ListBucketsRequest &request) const
{
return client_->ListBuckets(request);
}
ListBucketInventoryConfigurationsOutcome OssClient::ListBucketInventoryConfigurations(const ListBucketInventoryConfigurationsRequest& request) const
{
return client_->ListBucketInventoryConfigurations(request);
}
CreateBucketOutcome OssClient::CreateBucket(const std::string &bucket, StorageClass storageClass) const
{
return client_->CreateBucket(CreateBucketRequest(bucket, storageClass));
}
CreateBucketOutcome OssClient::CreateBucket(const std::string &bucket, StorageClass storageClass, CannedAccessControlList acl) const
{
return client_->CreateBucket(CreateBucketRequest(bucket, storageClass, acl));
}
CreateBucketOutcome OssClient::CreateBucket(const CreateBucketRequest &request) const
{
return client_->CreateBucket(request);
}
VoidOutcome OssClient::SetBucketAcl(const std::string &bucket, CannedAccessControlList acl) const
{
return client_->SetBucketAcl(SetBucketAclRequest(bucket, acl));
}
VoidOutcome OssClient::SetBucketAcl(const SetBucketAclRequest& request) const
{
return client_->SetBucketAcl(request);
}
VoidOutcome OssClient::SetBucketLogging(const std::string &bucket, const std::string &targetBucket, const std::string &targetPrefix) const
{
return client_->SetBucketLogging(SetBucketLoggingRequest(bucket, targetBucket, targetPrefix));
}
VoidOutcome OssClient::SetBucketLogging(const SetBucketLoggingRequest& request) const
{
return client_->SetBucketLogging(request);
}
VoidOutcome OssClient::SetBucketWebsite(const std::string &bucket, const std::string &indexDocument) const
{
SetBucketWebsiteRequest request(bucket);
request.setIndexDocument(indexDocument);
return client_->SetBucketWebsite(request);
}
VoidOutcome OssClient::SetBucketWebsite(const std::string &bucket, const std::string &indexDocument, const std::string &errorDocument) const
{
SetBucketWebsiteRequest request(bucket);
request.setIndexDocument(indexDocument);
request.setErrorDocument(errorDocument);
return client_->SetBucketWebsite(request);
}
VoidOutcome OssClient::SetBucketWebsite(const SetBucketWebsiteRequest& request) const
{
return client_->SetBucketWebsite(request);
}
VoidOutcome OssClient::SetBucketReferer(const std::string &bucket, const RefererList &refererList, bool allowEmptyReferer) const
{
return client_->SetBucketReferer(SetBucketRefererRequest(bucket, refererList, allowEmptyReferer));
}
VoidOutcome OssClient::SetBucketReferer(const SetBucketRefererRequest& request) const
{
return client_->SetBucketReferer(request);
}
VoidOutcome OssClient::SetBucketLifecycle(const SetBucketLifecycleRequest& request) const
{
return client_->SetBucketLifecycle(request);
}
VoidOutcome OssClient::SetBucketCors(const std::string &bucket, const CORSRuleList &rules) const
{
SetBucketCorsRequest request(bucket);
request.setCORSRules(rules);
return client_->SetBucketCors(request);
}
VoidOutcome OssClient::SetBucketCors(const SetBucketCorsRequest& request) const
{
return client_->SetBucketCors(request);
}
VoidOutcome OssClient::SetBucketStorageCapacity(const std::string &bucket, int64_t storageCapacity) const
{
return client_->SetBucketStorageCapacity(SetBucketStorageCapacityRequest(bucket, storageCapacity));
}
VoidOutcome OssClient::SetBucketStorageCapacity(const SetBucketStorageCapacityRequest& request) const
{
return client_->SetBucketStorageCapacity(request);
}
VoidOutcome OssClient::SetBucketPolicy(const SetBucketPolicyRequest& request) const
{
return client_->SetBucketPolicy(request);
}
VoidOutcome OssClient::SetBucketRequestPayment(const SetBucketRequestPaymentRequest& request) const
{
return client_->SetBucketRequestPayment(request);
}
VoidOutcome OssClient::SetBucketEncryption(const SetBucketEncryptionRequest& request) const
{
return client_->SetBucketEncryption(request);
}
VoidOutcome OssClient::SetBucketTagging(const SetBucketTaggingRequest& request) const
{
return client_->SetBucketTagging(request);
}
VoidOutcome OssClient::SetBucketQosInfo(const SetBucketQosInfoRequest& request) const
{
return client_->SetBucketQosInfo(request);
}
VoidOutcome OssClient::DeleteBucketPolicy(const DeleteBucketPolicyRequest& request) const
{
return client_->DeleteBucketPolicy(request);
}
VoidOutcome OssClient::SetBucketVersioning(const SetBucketVersioningRequest& request) const
{
return client_->SetBucketVersioning(request);
}
VoidOutcome OssClient::SetBucketInventoryConfiguration(const SetBucketInventoryConfigurationRequest& request) const
{
return client_->SetBucketInventoryConfiguration(request);
}
VoidOutcome OssClient::DeleteBucket(const std::string &bucket) const
{
return client_->DeleteBucket(DeleteBucketRequest(bucket));
}
VoidOutcome OssClient::DeleteBucket(const DeleteBucketRequest &request) const
{
return client_->DeleteBucket(request);
}
VoidOutcome OssClient::DeleteBucketLogging(const std::string &bucket) const
{
return client_->DeleteBucketLogging(DeleteBucketLoggingRequest(bucket));
}
VoidOutcome OssClient::DeleteBucketLogging(const DeleteBucketLoggingRequest& request) const
{
return client_->DeleteBucketLogging(request);
}
VoidOutcome OssClient::DeleteBucketWebsite(const std::string &bucket) const
{
return client_->DeleteBucketWebsite(DeleteBucketWebsiteRequest(bucket));
}
VoidOutcome OssClient::DeleteBucketWebsite(const DeleteBucketWebsiteRequest& request) const
{
return client_->DeleteBucketWebsite(request);
}
VoidOutcome OssClient::DeleteBucketLifecycle(const std::string &bucket) const
{
return client_->DeleteBucketLifecycle(DeleteBucketLifecycleRequest(bucket));
}
VoidOutcome OssClient::DeleteBucketLifecycle(const DeleteBucketLifecycleRequest& request) const
{
return client_->DeleteBucketLifecycle(request);
}
VoidOutcome OssClient::DeleteBucketCors(const std::string &bucket) const
{
return client_->DeleteBucketCors(DeleteBucketCorsRequest(bucket));
}
VoidOutcome OssClient::DeleteBucketCors(const DeleteBucketCorsRequest& request) const
{
return client_->DeleteBucketCors(request);
}
VoidOutcome OssClient::DeleteBucketEncryption(const DeleteBucketEncryptionRequest& request) const
{
return client_->DeleteBucketEncryption(request);
}
VoidOutcome OssClient::DeleteBucketTagging(const DeleteBucketTaggingRequest& request) const
{
return client_->DeleteBucketTagging(request);
}
VoidOutcome OssClient::DeleteBucketQosInfo(const DeleteBucketQosInfoRequest& request) const
{
return client_->DeleteBucketQosInfo(request);
}
VoidOutcome OssClient::DeleteBucketInventoryConfiguration(const DeleteBucketInventoryConfigurationRequest& request) const
{
return client_->DeleteBucketInventoryConfiguration(request);
}
GetBucketAclOutcome OssClient::GetBucketAcl(const std::string &bucket) const
{
return client_->GetBucketAcl(GetBucketAclRequest(bucket));
}
GetBucketAclOutcome OssClient::GetBucketAcl(const GetBucketAclRequest &request) const
{
return client_->GetBucketAcl(request);
}
GetBucketLocationOutcome OssClient::GetBucketLocation(const std::string &bucket) const
{
return client_->GetBucketLocation(GetBucketLocationRequest(bucket));
}
GetBucketLocationOutcome OssClient::GetBucketLocation(const GetBucketLocationRequest &request) const
{
return client_->GetBucketLocation(request);
}
GetBucketInfoOutcome OssClient::GetBucketInfo(const std::string &bucket) const
{
return client_->GetBucketInfo(GetBucketInfoRequest(bucket));
}
GetBucketInfoOutcome OssClient::GetBucketInfo(const GetBucketInfoRequest &request) const
{
return client_->GetBucketInfo(request);
}
GetBucketLoggingOutcome OssClient::GetBucketLogging(const std::string &bucket) const
{
return client_->GetBucketLogging(GetBucketLoggingRequest(bucket));
}
GetBucketLoggingOutcome OssClient::GetBucketLogging(const GetBucketLoggingRequest &request) const
{
return client_->GetBucketLogging(request);
}
GetBucketWebsiteOutcome OssClient::GetBucketWebsite(const std::string &bucket) const
{
return client_->GetBucketWebsite(GetBucketWebsiteRequest(bucket));
}
GetBucketWebsiteOutcome OssClient::GetBucketWebsite(const GetBucketWebsiteRequest &request) const
{
return client_->GetBucketWebsite(request);
}
GetBucketRefererOutcome OssClient::GetBucketReferer(const std::string &bucket) const
{
return client_->GetBucketReferer(GetBucketRefererRequest(bucket));
}
GetBucketRefererOutcome OssClient::GetBucketReferer(const GetBucketRefererRequest &request) const
{
return client_->GetBucketReferer(request);
}
GetBucketLifecycleOutcome OssClient::GetBucketLifecycle(const std::string &bucket) const
{
return client_->GetBucketLifecycle(GetBucketLifecycleRequest(bucket));
}
GetBucketLifecycleOutcome OssClient::GetBucketLifecycle(const GetBucketLifecycleRequest &request) const
{
return client_->GetBucketLifecycle(request);
}
GetBucketStatOutcome OssClient::GetBucketStat(const std::string &bucket) const
{
return client_->GetBucketStat(GetBucketStatRequest(bucket));
}
GetBucketStatOutcome OssClient::GetBucketStat(const GetBucketStatRequest &request) const
{
return client_->GetBucketStat(request);
}
GetBucketCorsOutcome OssClient::GetBucketCors(const std::string &bucket) const
{
return client_->GetBucketCors(GetBucketCorsRequest(bucket));
}
GetBucketCorsOutcome OssClient::GetBucketCors(const GetBucketCorsRequest &request) const
{
return client_->GetBucketCors(request);
}
GetBucketStorageCapacityOutcome OssClient::GetBucketStorageCapacity(const std::string &bucket) const
{
return client_->GetBucketStorageCapacity(GetBucketStorageCapacityRequest(bucket));
}
GetBucketStorageCapacityOutcome OssClient::GetBucketStorageCapacity(const GetBucketStorageCapacityRequest& request) const
{
return client_->GetBucketStorageCapacity(request);
}
GetBucketPolicyOutcome OssClient::GetBucketPolicy(const GetBucketPolicyRequest& request) const
{
return client_->GetBucketPolicy(request);
}
GetBucketPaymentOutcome OssClient::GetBucketRequestPayment(const GetBucketRequestPaymentRequest& request) const
{
return client_->GetBucketRequestPayment(request);
}
GetBucketEncryptionOutcome OssClient::GetBucketEncryption(const GetBucketEncryptionRequest& request) const
{
return client_->GetBucketEncryption(request);
}
GetBucketTaggingOutcome OssClient::GetBucketTagging(const GetBucketTaggingRequest& request) const
{
return client_->GetBucketTagging(request);
}
GetBucketQosInfoOutcome OssClient::GetBucketQosInfo(const GetBucketQosInfoRequest& request) const
{
return client_->GetBucketQosInfo(request);
}
GetUserQosInfoOutcome OssClient::GetUserQosInfo(const GetUserQosInfoRequest& request) const
{
return client_->GetUserQosInfo(request);
}
GetBucketVersioningOutcome OssClient::GetBucketVersioning(const GetBucketVersioningRequest& request) const
{
return client_->GetBucketVersioning(request);
}
GetBucketInventoryConfigurationOutcome OssClient::GetBucketInventoryConfiguration(const GetBucketInventoryConfigurationRequest& request) const
{
return client_->GetBucketInventoryConfiguration(request);
}
#endif
ListObjectOutcome OssClient::ListObjects(const std::string &bucket) const
{
return client_->ListObjects(ListObjectsRequest(bucket));
}
ListObjectOutcome OssClient::ListObjects(const std::string &bucket, const std::string &prefix) const
{
ListObjectsRequest request(bucket);
request.setPrefix(prefix);
return client_->ListObjects(request);
}
ListObjectOutcome OssClient::ListObjects(const ListObjectsRequest &request) const
{
return client_->ListObjects(request);
}
ListObjectVersionsOutcome OssClient::ListObjectVersions(const std::string &bucket) const
{
return client_->ListObjectVersions(ListObjectVersionsRequest(bucket));
}
ListObjectVersionsOutcome OssClient::ListObjectVersions(const std::string &bucket, const std::string &prefix) const
{
ListObjectVersionsRequest request(bucket);
request.setPrefix(prefix);
return client_->ListObjectVersions(request);
}
ListObjectVersionsOutcome OssClient::ListObjectVersions(const ListObjectVersionsRequest& request) const
{
return client_->ListObjectVersions(request);
}
GetObjectOutcome OssClient::GetObject(const std::string &bucket, const std::string &key) const
{
return client_->GetObject(GetObjectRequest(bucket, key));
}
GetObjectOutcome OssClient::GetObject(const std::string &bucket, const std::string &key, const std::shared_ptr<std::iostream> &content) const
{
GetObjectRequest request(bucket, key);
request.setResponseStreamFactory([=]() { return content; });
return client_->GetObject(request);
}
GetObjectOutcome OssClient::GetObject(const std::string &bucket, const std::string &key, const std::string &fileToSave) const
{
GetObjectRequest request(bucket, key);
request.setResponseStreamFactory([=]() {return std::make_shared<std::fstream>(fileToSave, std::ios_base::out | std::ios_base::trunc | std::ios::binary); });
return client_->GetObject(request);
}
GetObjectOutcome OssClient::GetObject(const GetObjectRequest &request) const
{
return client_->GetObject(request);
}
PutObjectOutcome OssClient::PutObject(const std::string &bucket, const std::string &key, const std::shared_ptr<std::iostream> &content) const
{
return client_->PutObject(PutObjectRequest(bucket, key, content));
}
PutObjectOutcome OssClient::PutObject(const std::string &bucket, const std::string &key, const std::string &fileToUpload) const
{
std::shared_ptr<std::iostream> content = std::make_shared<std::fstream>(fileToUpload, std::ios::in|std::ios::binary);
return client_->PutObject(PutObjectRequest(bucket, key, content));
}
PutObjectOutcome OssClient::PutObject(const std::string &bucket, const std::string &key, const std::shared_ptr<std::iostream> &content, const ObjectMetaData &meta) const
{
return client_->PutObject(PutObjectRequest(bucket, key, content, meta));
}
PutObjectOutcome OssClient::PutObject(const std::string &bucket, const std::string &key, const std::string &fileToUpload, const ObjectMetaData &meta) const
{
std::shared_ptr<std::iostream> content = std::make_shared<std::fstream>(fileToUpload, std::ios::in | std::ios::binary);
return client_->PutObject(PutObjectRequest(bucket, key, content, meta));
}
PutObjectOutcome OssClient::PutObject(const PutObjectRequest &request) const
{
return client_->PutObject(request);
}
DeleteObjectOutcome OssClient::DeleteObject(const std::string &bucket, const std::string &key) const
{
return client_->DeleteObject(DeleteObjectRequest(bucket, key));
}
DeleteObjectOutcome OssClient::DeleteObject(const DeleteObjectRequest &request) const
{
return client_->DeleteObject(request);
}
DeleteObjecstOutcome OssClient::DeleteObjects(const std::string bucket, const DeletedKeyList &keyList) const
{
DeleteObjectsRequest request(bucket);
request.setKeyList(keyList);
return client_->DeleteObjects(request);
}
DeleteObjecstOutcome OssClient::DeleteObjects(const DeleteObjectsRequest &request) const
{
return client_->DeleteObjects(request);
}
DeleteObjecVersionstOutcome OssClient::DeleteObjectVersions(const std::string bucket, const ObjectIdentifierList &objectList) const
{
DeleteObjectVersionsRequest request(bucket);
request.setObjects(objectList);
return client_->DeleteObjectVersions(request);
}
DeleteObjecVersionstOutcome OssClient::DeleteObjectVersions(const DeleteObjectVersionsRequest &request) const
{
return client_->DeleteObjectVersions(request);
}
ObjectMetaDataOutcome OssClient::HeadObject(const std::string &bucket, const std::string &key) const
{
return client_->HeadObject(HeadObjectRequest(bucket, key));
}
ObjectMetaDataOutcome OssClient::HeadObject(const HeadObjectRequest &request) const
{
return client_->HeadObject(request);
}
ObjectMetaDataOutcome OssClient::GetObjectMeta(const std::string &bucket, const std::string &key) const
{
return client_->GetObjectMeta(GetObjectMetaRequest(bucket, key));
}
ObjectMetaDataOutcome OssClient::GetObjectMeta(const GetObjectMetaRequest &request) const
{
return client_->GetObjectMeta(request);
}
GetObjectAclOutcome OssClient::GetObjectAcl(const GetObjectAclRequest &request) const
{
return client_->GetObjectAcl(request);
}
AppendObjectOutcome OssClient::AppendObject(const AppendObjectRequest &request) const
{
return client_->AppendObject(request);
}
CopyObjectOutcome OssClient::CopyObject(const CopyObjectRequest &request) const
{
return client_->CopyObject(request);
}
GetSymlinkOutcome OssClient::GetSymlink(const GetSymlinkRequest &request) const
{
return client_->GetSymlink(request);
}
GetObjectOutcome OssClient::ProcessObject(const ProcessObjectRequest &request) const
{
return client_->ProcessObject(request);
}
RestoreObjectOutcome OssClient::RestoreObject(const std::string &bucket, const std::string &key) const
{
return client_->RestoreObject(RestoreObjectRequest(bucket, key));
}
RestoreObjectOutcome OssClient::RestoreObject(const RestoreObjectRequest &request) const
{
return client_->RestoreObject(request);
}
CreateSymlinkOutcome OssClient::CreateSymlink(const CreateSymlinkRequest &request) const
{
return client_->CreateSymlink(request);
}
SetObjectAclOutcome OssClient::SetObjectAcl(const SetObjectAclRequest &request) const
{
return client_->SetObjectAcl(request);
}
GetObjectOutcome OssClient::SelectObject(const SelectObjectRequest &request) const
{
return client_->SelectObject(request);
}
CreateSelectObjectMetaOutcome OssClient::CreateSelectObjectMeta(const CreateSelectObjectMetaRequest &request) const
{
return client_->CreateSelectObjectMeta(request);
}
SetObjectTaggingOutcome OssClient::SetObjectTagging(const SetObjectTaggingRequest& request) const
{
return client_->SetObjectTagging(request);
}
DeleteObjectTaggingOutcome OssClient::DeleteObjectTagging(const DeleteObjectTaggingRequest& request) const
{
return client_->DeleteObjectTagging(request);
}
GetObjectTaggingOutcome OssClient::GetObjectTagging(const GetObjectTaggingRequest& request) const
{
return client_->GetObjectTagging(request);
}
StringOutcome OssClient::GeneratePresignedUrl(const GeneratePresignedUrlRequest &request) const
{
return client_->GeneratePresignedUrl(request);
}
StringOutcome OssClient::GeneratePresignedUrl(const std::string &bucket, const std::string &key) const
{
return GeneratePresignedUrl(GeneratePresignedUrlRequest(bucket, key));
}
StringOutcome OssClient::GeneratePresignedUrl(const std::string &bucket, const std::string &key, int64_t expires) const
{
GeneratePresignedUrlRequest request(bucket, key);
request.setExpires(expires);
return GeneratePresignedUrl(request);
}
StringOutcome OssClient::GeneratePresignedUrl(const std::string &bucket, const std::string &key, int64_t expires, Http::Method method) const
{
GeneratePresignedUrlRequest request(bucket, key, method);
request.setExpires(expires);
return GeneratePresignedUrl(request);
}
GetObjectOutcome OssClient::GetObjectByUrl(const GetObjectByUrlRequest &request) const
{
return client_->GetObjectByUrl(request);
}
GetObjectOutcome OssClient::GetObjectByUrl(const std::string &url) const
{
return client_->GetObjectByUrl(GetObjectByUrlRequest(url));
}
GetObjectOutcome OssClient::GetObjectByUrl(const std::string &url, const std::string &file) const
{
GetObjectByUrlRequest request(url);
request.setResponseStreamFactory([=]() {return std::make_shared<std::fstream>(file, std::ios_base::out | std::ios_base::in | std::ios_base::trunc); });
return client_->GetObjectByUrl(request);
}
PutObjectOutcome OssClient::PutObjectByUrl(const PutObjectByUrlRequest &request) const
{
return client_->PutObjectByUrl(request);
}
PutObjectOutcome OssClient::PutObjectByUrl(const std::string &url, const std::string &file) const
{
std::shared_ptr<std::iostream> content = std::make_shared<std::fstream>(file, std::ios::in|std::ios::binary);
return client_->PutObjectByUrl(PutObjectByUrlRequest(url, content));
}
PutObjectOutcome OssClient::PutObjectByUrl(const std::string &url, const std::string &file, const ObjectMetaData &metaData) const
{
std::shared_ptr<std::iostream> content = std::make_shared<std::fstream>(file, std::ios::in | std::ios::binary);
return client_->PutObjectByUrl(PutObjectByUrlRequest(url, content, metaData));
}
PutObjectOutcome OssClient::PutObjectByUrl(const std::string &url, const std::shared_ptr<std::iostream> &content) const
{
return client_->PutObjectByUrl(PutObjectByUrlRequest(url, content));
}
PutObjectOutcome OssClient::PutObjectByUrl(const std::string &url, const std::shared_ptr<std::iostream> &content, const ObjectMetaData &metaData) const
{
return client_->PutObjectByUrl(PutObjectByUrlRequest(url, content, metaData));
}
InitiateMultipartUploadOutcome OssClient::InitiateMultipartUpload(const InitiateMultipartUploadRequest &request)const
{
return client_->InitiateMultipartUpload(request);
}
PutObjectOutcome OssClient::UploadPart(const UploadPartRequest &request) const
{
return client_->UploadPart(request);
}
UploadPartCopyOutcome OssClient::UploadPartCopy(const UploadPartCopyRequest &request) const
{
return client_->UploadPartCopy(request);
}
CompleteMultipartUploadOutcome OssClient::CompleteMultipartUpload(const CompleteMultipartUploadRequest &request) const
{
return client_->CompleteMultipartUpload(request);
}
VoidOutcome OssClient::AbortMultipartUpload(const AbortMultipartUploadRequest &request) const
{
return client_->AbortMultipartUpload(request);
}
ListMultipartUploadsOutcome OssClient::ListMultipartUploads(const ListMultipartUploadsRequest &request) const
{
return client_->ListMultipartUploads(request);
}
ListPartsOutcome OssClient::ListParts(const ListPartsRequest &request) const
{
return client_->ListParts(request);
}
/*Aysnc APIs*/
void OssClient::ListObjectsAsync(const ListObjectsRequest &request, const ListObjectAsyncHandler &handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, client_->ListObjects(request), context);
};
client_->asyncExecute(new Runnable(fn));
}
void OssClient::GetObjectAsync(const GetObjectRequest &request, const GetObjectAsyncHandler &handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, client_->GetObject(request), context);
};
client_->asyncExecute(new Runnable(fn));
}
void OssClient::PutObjectAsync(const PutObjectRequest &request, const PutObjectAsyncHandler &handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, client_->PutObject(request), context);
};
client_->asyncExecute(new Runnable(fn));
}
void OssClient::UploadPartAsync(const UploadPartRequest &request, const UploadPartAsyncHandler &handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, client_->UploadPart(request), context);
};
client_->asyncExecute(new Runnable(fn));
}
void OssClient::UploadPartCopyAsync(const UploadPartCopyRequest &request, const UploadPartCopyAsyncHandler &handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, client_->UploadPartCopy(request), context);
};
client_->asyncExecute(new Runnable(fn));
}
/*Callable APIs*/
ListObjectOutcomeCallable OssClient::ListObjectsCallable(const ListObjectsRequest &request) const
{
auto task = std::make_shared<std::packaged_task<ListObjectOutcome()>>(
[this, request]()
{
return this->ListObjects(request);
});
client_->asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
GetObjectOutcomeCallable OssClient::GetObjectCallable(const GetObjectRequest &request) const
{
auto task = std::make_shared<std::packaged_task<GetObjectOutcome()>>(
[this, request]()
{
return this->GetObject(request);
});
client_->asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
PutObjectOutcomeCallable OssClient::PutObjectCallable(const PutObjectRequest &request) const
{
auto task = std::make_shared<std::packaged_task<PutObjectOutcome()>>(
[this, request]()
{
return this->PutObject(request);
});
client_->asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
PutObjectOutcomeCallable OssClient::UploadPartCallable(const UploadPartRequest &request) const
{
auto task = std::make_shared<std::packaged_task<PutObjectOutcome()>>(
[this, request]()
{
return this->UploadPart(request);
});
client_->asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
UploadPartCopyOutcomeCallable OssClient::UploadPartCopyCallable(const UploadPartCopyRequest &request) const
{
auto task = std::make_shared<std::packaged_task<UploadPartCopyOutcome()>>(
[this, request]()
{
return this->UploadPartCopy(request);
});
client_->asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
/*Extended APIs*/
#if (!OSS_DISABLE_BUCKET)
bool OssClient::DoesBucketExist(const std::string &bucket) const
{
return client_->GetBucketAcl(GetBucketAclRequest(bucket)).isSuccess();
}
#endif
bool OssClient::DoesObjectExist(const std::string &bucket, const std::string &key) const
{
return client_->GetObjectMeta(GetObjectMetaRequest(bucket, key)).isSuccess();
}
CopyObjectOutcome OssClient::ModifyObjectMeta(const std::string& bucket, const std::string& key, const ObjectMetaData& meta)
{
CopyObjectRequest copyRequest(bucket, key, meta);
copyRequest.setCopySource(bucket, key);
copyRequest.setMetadataDirective(CopyActionList::Replace);
return client_->CopyObject(copyRequest);
}
#if (!OSS_DISABLE_LIVECHANNEL)
VoidOutcome OssClient::PutLiveChannelStatus(const PutLiveChannelStatusRequest &request) const
{
return client_->PutLiveChannelStatus(request);
}
PutLiveChannelOutcome OssClient::PutLiveChannel(const PutLiveChannelRequest &request) const
{
return client_->PutLiveChannel(request);
}
VoidOutcome OssClient::PostVodPlaylist(const PostVodPlaylistRequest &request) const
{
return client_->PostVodPlaylist(request);
}
GetVodPlaylistOutcome OssClient::GetVodPlaylist(const GetVodPlaylistRequest &request) const
{
return client_->GetVodPlaylist(request);
}
GetLiveChannelStatOutcome OssClient::GetLiveChannelStat(const GetLiveChannelStatRequest &request) const
{
return client_->GetLiveChannelStat(request);
}
GetLiveChannelInfoOutcome OssClient::GetLiveChannelInfo(const GetLiveChannelInfoRequest &request) const
{
return client_->GetLiveChannelInfo(request);
}
GetLiveChannelHistoryOutcome OssClient::GetLiveChannelHistory(const GetLiveChannelHistoryRequest &request) const
{
return client_->GetLiveChannelHistory(request);
}
ListLiveChannelOutcome OssClient::ListLiveChannel(const ListLiveChannelRequest &request) const
{
return client_->ListLiveChannel(request);
}
VoidOutcome OssClient::DeleteLiveChannel(const DeleteLiveChannelRequest &request) const
{
return client_->DeleteLiveChannel(request);
}
StringOutcome OssClient::GenerateRTMPSignedUrl(const GenerateRTMPSignedUrlRequest &request) const
{
return client_->GenerateRTMPSignedUrl(request);
}
#endif
void OssClient::DisableRequest()
{
client_->DisableRequest();
}
void OssClient::EnableRequest()
{
client_->EnableRequest();
}
#if (!OSS_DISABLE_RESUAMABLE)
PutObjectOutcome OssClient::ResumableUploadObject(const UploadObjectRequest &request) const
{
return client_->ResumableUploadObject(request);
}
CopyObjectOutcome OssClient::ResumableCopyObject(const MultiCopyObjectRequest &request) const
{
return client_->ResumableCopyObject(request);
}
GetObjectOutcome OssClient::ResumableDownloadObject(const DownloadObjectRequest &request) const
{
return client_->ResumableDownloadObject(request);
}
#endif | YifuLiu/AliOS-Things | components/oss/src/OssClient.cc | C++ | apache-2.0 | 31,811 |
/*
* 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 <ctime>
#include <algorithm>
#include <sstream>
#include <set>
#include <external/tinyxml2/tinyxml2.h>
#include <alibabacloud/oss/http/HttpType.h>
#include <alibabacloud/oss/Const.h>
#include <fstream>
#include "utils/Utils.h"
#include "utils/SignUtils.h"
#include "utils/ThreadExecutor.h"
#include "auth/HmacSha1Signer.h"
#include "OssClientImpl.h"
#include "utils/LogUtils.h"
#include "utils/FileSystemUtils.h"
#if (!OSS_DISABLE_RESUAMABLE)
#include "resumable/ResumableUploader.h"
#include "resumable/ResumableDownloader.h"
#include "resumable/ResumableCopier.h"
#endif
#ifdef __cplusplus
extern "C" {
#endif
#if USE_AOS_TIME_POSIX_API
#if ESP_PLATFORM
#if MICROPY_PY_UCLOUD_AI
#include "mpconfigport.h"
#include "shared/timeutils/timeutils.h"
extern void timeutils_seconds_since_2000_to_struct_time(mp_uint_t t, timeutils_struct_time_t *tm);
#endif
#include <sys/time.h>
#include "py/mpprint.h"
#else
#include <posix/timer.h>
#endif
#endif
#ifdef __cplusplus
}
#endif
using namespace AlibabaCloud::OSS;
using namespace tinyxml2;
Url g_ags_url;
namespace
{
const std::string SERVICE_NAME = "OSS";
const char *TAG = "OssClientImpl";
}
OssClientImpl::OssClientImpl(const std::string &endpoint, const std::shared_ptr<CredentialsProvider>& credentialsProvider, const ClientConfiguration & configuration) :
Client(SERVICE_NAME, configuration),
endpoint_(endpoint),
credentialsProvider_(credentialsProvider),
signer_(std::make_shared<HmacSha1Signer>()),
executor_(configuration.executor ? configuration.executor :std::make_shared<ThreadExecutor>())
{
}
OssClientImpl::~OssClientImpl()
{
}
int OssClientImpl::asyncExecute(Runnable * r) const
{
if (executor_ == nullptr)
return 1;
executor_->execute(r);
return 0;
}
std::shared_ptr<HttpRequest> OssClientImpl::buildHttpRequest(const std::string & endpoint, const ServiceRequest & msg, Http::Method method) const
{
auto httpRequest = std::make_shared<HttpRequest>(method);
auto calcContentMD5 = !!(msg.Flags()&REQUEST_FLAG_CONTENTMD5);
auto paramInPath = !!(msg.Flags()&REQUEST_FLAG_PARAM_IN_PATH);
httpRequest->setResponseStreamFactory(msg.ResponseStreamFactory());
addHeaders(httpRequest, msg.Headers());
addBody(httpRequest, msg.Body(), calcContentMD5);
if (paramInPath) {
httpRequest->setUrl(Url(msg.Path()));
}
else {
addSignInfo(httpRequest, msg);
addUrl(httpRequest, endpoint, msg);
}
addOther(httpRequest, msg);
return httpRequest;
}
bool OssClientImpl::hasResponseError(const std::shared_ptr<HttpResponse>&response) const
{
if (BASE::hasResponseError(response)) {
return true;
}
//check crc64
if (response->request().hasCheckCrc64() &&
!response->request().hasHeader(Http::RANGE) &&
response->hasHeader("x-oss-hash-crc64ecma")) {
uint64_t clientCrc64 = response->request().Crc64Result();
uint64_t serverCrc64 = std::strtoull(response->Header("x-oss-hash-crc64ecma").c_str(), nullptr, 10);
if (clientCrc64 != serverCrc64) {
response->setStatusCode(ERROR_CRC_INCONSISTENT);
std::stringstream ss;
ss << "Crc64 validation failed. Expected hash:" << serverCrc64
<< " not equal to calculated hash:" << clientCrc64
<< ". Transferd bytes:" << response->request().TransferedBytes()
<< ". RequestId:" << response->Header("x-oss-request-id").c_str();
response->setStatusMsg(ss.str().c_str());
return true;
}
}
// check Calback
if (response->statusCode() == 203 &&
(response->request().hasHeader("x-oss-callback") ||
(response->request().url().query().find("callback=") != std::string::npos))) {
return true;
}
return false;
}
void OssClientImpl::addHeaders(const std::shared_ptr<HttpRequest> &httpRequest, const HeaderCollection &headers) const
{
for (auto const& header : headers) {
httpRequest->addHeader(header.first, header.second);
}
//common headers
httpRequest->addHeader(Http::USER_AGENT, configuration().userAgent);
//Date
if (httpRequest->hasHeader("x-oss-date")) {
httpRequest->addHeader(Http::DATE, httpRequest->Header("x-oss-date"));
}
if (!httpRequest->hasHeader(Http::DATE)) {
#if USE_AOS_TIME_POSIX_API
struct timespec currentTime;
time_t t;
clock_gettime(CLOCK_REALTIME, ¤tTime);
t = currentTime.tv_nsec/1000000000 + currentTime.tv_sec;
// printf("----- time %lld ---------\r\n",t);
#else
std::time_t t = std::time(nullptr);
#endif
t += getRequestDateOffset();
#if ESP_PLATFORM
time_t now;
struct tm *timeinfo = NULL;
char GMT_DATA_TIME[30];
now = time(NULL) - 3600 * 8; // change local time to GMT
timeinfo = localtime(&now);
memset(GMT_DATA_TIME, 0, sizeof(GMT_DATA_TIME));
strftime(GMT_DATA_TIME, sizeof(GMT_DATA_TIME), "%a, %d %b %Y %H:%M:%S GMT", timeinfo);
httpRequest->addHeader(Http::DATE, GMT_DATA_TIME);
#else
httpRequest->addHeader(Http::DATE, ToGmtTime(t));
#endif
}
}
void OssClientImpl::addBody(const std::shared_ptr<HttpRequest> &httpRequest, const std::shared_ptr<std::iostream>& body, bool contentMd5) const
{
if (body == nullptr) {
Http::Method methold = httpRequest->method();
if (methold == Http::Method::Get || methold == Http::Method::Post) {
httpRequest->setHeader(Http::CONTENT_LENGTH, "0");
} else {
httpRequest->removeHeader(Http::CONTENT_LENGTH);
}
}
if ((body != nullptr) && !httpRequest->hasHeader(Http::CONTENT_LENGTH)) {
auto streamSize = GetIOStreamLength(*body);
httpRequest->setHeader(Http::CONTENT_LENGTH, std::to_string(streamSize));
}
if (contentMd5 && body && !httpRequest->hasHeader(Http::CONTENT_MD5)) {
auto md5 = ComputeContentMD5(*body);
httpRequest->setHeader(Http::CONTENT_MD5, md5);
}
httpRequest->addBody(body);
}
void OssClientImpl::addSignInfo(const std::shared_ptr<HttpRequest> &httpRequest, const ServiceRequest &request) const
{
const Credentials credentials = credentialsProvider_->getCredentials();
if (!credentials.SessionToken().empty()) {
httpRequest->addHeader("x-oss-security-token", credentials.SessionToken());
}
//Sort the parameters
ParameterCollection parameters;
for (auto const¶m : request.Parameters()) {
parameters[param.first] = param.second;
}
std::string method = Http::MethodToString(httpRequest->method());
const OssRequest& ossRequest = static_cast<const OssRequest&>(request);
std::string resource;
resource.append("/");
if (!ossRequest.bucket().empty()) {
resource.append(ossRequest.bucket());
resource.append("/");
}
if (!ossRequest.key().empty()) {
resource.append(ossRequest.key());
}
std::string date = httpRequest->Header(Http::DATE);
SignUtils signUtils(signer_->version());
signUtils.build(method, resource, date, httpRequest->Headers(), parameters);
auto signature = signer_->generate(signUtils.CanonicalString(), credentials.AccessKeySecret());
std::stringstream authValue;
authValue
<< "OSS "
<< credentials.AccessKeyId()
<< ":"
<< signature;
httpRequest->addHeader(Http::AUTHORIZATION, authValue.str());
OSS_LOG(LogLevel::LogDebug, TAG, "client(%p) request(%p) CanonicalString:%s", this, httpRequest.get(), signUtils.CanonicalString().c_str());
OSS_LOG(LogLevel::LogDebug, TAG, "client(%p) request(%p) Authorization:%s", this, httpRequest.get(), authValue.str().c_str());
}
void OssClientImpl::addUrl(const std::shared_ptr<HttpRequest> &httpRequest, const std::string &endpoint, const ServiceRequest &request) const
{
const OssRequest& ossRequest = static_cast<const OssRequest&>(request);
auto host = CombineHostString(endpoint, ossRequest.bucket(), configuration().isCname);
auto path = CombinePathString(endpoint, ossRequest.bucket(), ossRequest.key());
Url url(host);
url.setPath(path);
OSS_LOG(LogLevel::LogDebug, TAG, "client(%p) request(%p) host:%s, path:%s", this, httpRequest.get(), host.c_str(), path.c_str());
auto parameters = request.Parameters();
if (!parameters.empty()) {
std::stringstream queryString;
for (const auto &p : parameters)
{
if (p.second.empty())
queryString << "&" << UrlEncode(p.first);
else
queryString << "&" << UrlEncode(p.first) << "=" << UrlEncode(p.second);
}
url.setQuery(queryString.str().substr(1));
}
httpRequest->setUrl(url);
g_ags_url = httpRequest->url();
//std::cout << "addUrl url:" << url.toString() <<std::endl;
//std::cout << "g_ags_url url:" << g_ags_url.toString() <<std::endl;
}
void OssClientImpl::addOther(const std::shared_ptr<HttpRequest> &httpRequest, const ServiceRequest &request) const
{
//progress
httpRequest->setTransferProgress(request.TransferProgress());
//crc64 check
auto checkCRC64 = !!(request.Flags()&REQUEST_FLAG_CHECK_CRC64);
if (configuration().enableCrc64 && checkCRC64 ) {
httpRequest->setCheckCrc64(true);
#ifdef ENABLE_OSS_TEST
if (!!(request.Flags()&0x80000000)) {
httpRequest->addHeader("oss-test-crc64", "1");
}
#endif
}
}
OssError OssClientImpl::buildError(const Error &error) const
{
OssError err;
if (((error.Status() == 203) || (error.Status() > 299 && error.Status() < 600)) &&
!error.Message().empty()) {
XMLDocument doc;
XMLError xml_err;
if ((xml_err = doc.Parse(error.Message().c_str(), error.Message().size())) == XML_SUCCESS) {
XMLElement* root =doc.RootElement();
if (root && !std::strncmp("Error", root->Name(), 5)) {
XMLElement *node;
node = root->FirstChildElement("Code");
err.setCode(node ? node->GetText(): "");
node = root->FirstChildElement("Message");
err.setMessage(node ? node->GetText(): "");
node = root->FirstChildElement("RequestId");
err.setRequestId(node ? node->GetText(): "");
node = root->FirstChildElement("HostId");
err.setHost(node ? node->GetText(): "");
} else {
err.setCode("ParseXMLError");
err.setMessage("Xml format invalid, root node name is not Error. the content is:\n" + error.Message());
}
} else {
std::stringstream ss;
ss << "ParseXMLError:" << xml_err;
err.setCode(ss.str());
err.setMessage(XMLDocument::ErrorIDToName(xml_err));
}
}
else {
err.setCode(error.Code());
err.setMessage(error.Message());
}
//get from header if body has nothing
if (err.RequestId().empty()) {
auto it = error.Headers().find("x-oss-request-id");
if (it != error.Headers().end()) {
err.setRequestId(it->second);
}
}
return err;
}
ServiceResult OssClientImpl::buildResult(const OssRequest &request, const std::shared_ptr<HttpResponse> &httpResponse) const
{
ServiceResult result;
auto flag = request.Flags();
if ((flag & REQUEST_FLAG_CHECK_CRC64) &&
(flag & REQUEST_FLAG_SAVE_CLIENT_CRC64)) {
httpResponse->addHeader("x-oss-hash-crc64ecma-by-client", std::to_string(httpResponse->request().Crc64Result()));
}
result.setRequestId(httpResponse->Header("x-oss-request-id"));
result.setPlayload(httpResponse->Body());
result.setResponseCode(httpResponse->statusCode());
result.setHeaderCollection(httpResponse->Headers());
return result;
}
OssOutcome OssClientImpl::MakeRequest(const OssRequest &request, Http::Method method) const
{
int ret = request.validate();
if (ret != 0) {
return OssOutcome(OssError("ValidateError", request.validateMessage(ret)));
}
auto outcome = BASE::AttemptRequest(endpoint_, request, method);
if (outcome.isSuccess()) {
return OssOutcome(buildResult(request, outcome.result()));
} else {
return OssOutcome(buildError(outcome.error()));
}
}
#if (!OSS_DISABLE_BUCKET)
ListBucketsOutcome OssClientImpl::ListBuckets(const ListBucketsRequest &request) const
{
auto outcome = MakeRequest(request, Http::Method::Get);
if (outcome.isSuccess()) {
ListBucketsResult result(outcome.result().payload());
result.requestId_ = outcome.result().RequestId();
return result.ParseDone() ? ListBucketsOutcome(std::move(result)) :
ListBucketsOutcome(OssError("ParseXMLError", "Parsing ListBuckets result fail."));
} else {
return ListBucketsOutcome(outcome.error());
}
}
CreateBucketOutcome OssClientImpl::CreateBucket(const CreateBucketRequest &request) const
{
auto outcome = MakeRequest(request, Http::Method::Put);
if (outcome.isSuccess()) {
return CreateBucketOutcome(Bucket());
} else {
return CreateBucketOutcome(outcome.error());
}
}
VoidOutcome OssClientImpl::SetBucketAcl(const SetBucketAclRequest& request) const
{
auto outcome = MakeRequest(request, Http::Method::Put);
if (outcome.isSuccess()) {
VoidResult result;
result.requestId_ = outcome.result().RequestId();
return VoidOutcome(result);
} else {
return VoidOutcome(outcome.error());
}
}
VoidOutcome OssClientImpl::SetBucketLogging(const SetBucketLoggingRequest& request) const
{
auto outcome = MakeRequest(request, Http::Method::Put);
if (outcome.isSuccess()) {
VoidResult result;
result.requestId_ = outcome.result().RequestId();
return VoidOutcome(result);
}
else {
return VoidOutcome(outcome.error());
}
}
VoidOutcome OssClientImpl::SetBucketWebsite(const SetBucketWebsiteRequest& request) const
{
auto outcome = MakeRequest(request, Http::Method::Put);
if (outcome.isSuccess()) {
VoidResult result;
result.requestId_ = outcome.result().RequestId();
return VoidOutcome(result);
}
else {
return VoidOutcome(outcome.error());
}
}
VoidOutcome OssClientImpl::SetBucketReferer(const SetBucketRefererRequest& request) const
{
auto outcome = MakeRequest(request, Http::Method::Put);
if (outcome.isSuccess()) {
VoidResult result;
result.requestId_ = outcome.result().RequestId();
return VoidOutcome(result);
}
else {
return VoidOutcome(outcome.error());
}
}
VoidOutcome OssClientImpl::SetBucketLifecycle(const SetBucketLifecycleRequest& request) const
{
auto outcome = MakeRequest(request, Http::Method::Put);
if (outcome.isSuccess()) {
VoidResult result;
result.requestId_ = outcome.result().RequestId();
return VoidOutcome(result);
}
else {
return VoidOutcome(outcome.error());
}
}
VoidOutcome OssClientImpl::SetBucketCors(const SetBucketCorsRequest& request) const
{
auto outcome = MakeRequest(request, Http::Method::Put);
if (outcome.isSuccess()) {
VoidResult result;
result.requestId_ = outcome.result().RequestId();
return VoidOutcome(result);
}
else {
return VoidOutcome(outcome.error());
}
}
VoidOutcome OssClientImpl::SetBucketStorageCapacity(const SetBucketStorageCapacityRequest& request) const
{
auto outcome = MakeRequest(request, Http::Method::Put);
if (outcome.isSuccess()) {
VoidResult result;
result.requestId_ = outcome.result().RequestId();
return VoidOutcome(result);
}
else {
return VoidOutcome(outcome.error());
}
}
VoidOutcome OssClientImpl::SetBucketPolicy(const SetBucketPolicyRequest& request) const
{
auto outcome = MakeRequest(request, Http::Method::Put);
if (outcome.isSuccess()) {
VoidResult result;
result.requestId_ = outcome.result().RequestId();
return VoidOutcome(result);
}
else {
return VoidOutcome(outcome.error());
}
}
VoidOutcome OssClientImpl::SetBucketRequestPayment(const SetBucketRequestPaymentRequest& request) const
{
auto outcome = MakeRequest(request, Http::Method::Put);
if (outcome.isSuccess()) {
VoidResult result;
result.requestId_ = outcome.result().RequestId();
return VoidOutcome(result);
}
else {
return VoidOutcome(outcome.error());
}
}
VoidOutcome AlibabaCloud::OSS::OssClientImpl::SetBucketEncryption(const SetBucketEncryptionRequest& request) const
{
auto outcome = MakeRequest(request, Http::Method::Put);
if (outcome.isSuccess()) {
VoidResult result;
result.requestId_ = outcome.result().RequestId();
return VoidOutcome(result);
}
else {
return VoidOutcome(outcome.error());
}
}
VoidOutcome OssClientImpl::SetBucketTagging(const SetBucketTaggingRequest& request) const
{
auto outcome = MakeRequest(request, Http::Method::Put);
if (outcome.isSuccess()) {
VoidResult result;
result.requestId_ = outcome.result().RequestId();
return VoidOutcome(result);
}
else {
return VoidOutcome(outcome.error());
}
}
VoidOutcome OssClientImpl::SetBucketQosInfo(const SetBucketQosInfoRequest& request) const
{
auto outcome = MakeRequest(request, Http::Method::Put);
if (outcome.isSuccess()) {
VoidResult result;
result.requestId_ = outcome.result().RequestId();
return VoidOutcome(result);
}
else {
return VoidOutcome(outcome.error());
}
}
VoidOutcome OssClientImpl::SetBucketVersioning(const SetBucketVersioningRequest& request) const
{
auto outcome = MakeRequest(request, Http::Method::Put);
if (outcome.isSuccess()) {
VoidResult result;
result.requestId_ = outcome.result().RequestId();
return VoidOutcome(result);
}
else {
return VoidOutcome(outcome.error());
}
}
VoidOutcome OssClientImpl::SetBucketInventoryConfiguration(const SetBucketInventoryConfigurationRequest& request) const
{
auto outcome = MakeRequest(request, Http::Method::Put);
if (outcome.isSuccess()) {
VoidResult result;
result.requestId_ = outcome.result().RequestId();
return VoidOutcome(result);
}
else {
return VoidOutcome(outcome.error());
}
}
VoidOutcome OssClientImpl::DeleteBucket(const DeleteBucketRequest &request) const
{
auto outcome = MakeRequest(request, Http::Method::Delete);
if (outcome.isSuccess()) {
VoidResult result;
result.requestId_ = outcome.result().RequestId();
return VoidOutcome(result);
}
else {
return VoidOutcome(outcome.error());
}
}
VoidOutcome OssClientImpl::DeleteBucketLogging(const DeleteBucketLoggingRequest &request) const
{
auto outcome = MakeRequest(request, Http::Method::Delete);
if (outcome.isSuccess()) {
VoidResult result;
result.requestId_ = outcome.result().RequestId();
return VoidOutcome(result);
}
else {
return VoidOutcome(outcome.error());
}
}
VoidOutcome OssClientImpl::DeleteBucketWebsite(const DeleteBucketWebsiteRequest &request) const
{
auto outcome = MakeRequest(request, Http::Method::Delete);
if (outcome.isSuccess()) {
VoidResult result;
result.requestId_ = outcome.result().RequestId();
return VoidOutcome(result);
}
else {
return VoidOutcome(outcome.error());
}
}
VoidOutcome OssClientImpl::DeleteBucketLifecycle(const DeleteBucketLifecycleRequest &request) const
{
auto outcome = MakeRequest(request, Http::Method::Delete);
if (outcome.isSuccess()) {
VoidResult result;
result.requestId_ = outcome.result().RequestId();
return VoidOutcome(result);
}
else {
return VoidOutcome(outcome.error());
}
}
VoidOutcome OssClientImpl::DeleteBucketCors(const DeleteBucketCorsRequest& request) const
{
auto outcome = MakeRequest(request, Http::Method::Delete);
if (outcome.isSuccess()) {
VoidResult result;
result.requestId_ = outcome.result().RequestId();
return VoidOutcome(result);
}
else {
return VoidOutcome(outcome.error());
}
}
VoidOutcome OssClientImpl::DeleteBucketPolicy(const DeleteBucketPolicyRequest& request) const
{
auto outcome = MakeRequest(request, Http::Method::Delete);
if (outcome.isSuccess()) {
VoidResult result;
result.requestId_ = outcome.result().RequestId();
return VoidOutcome(result);
}
else {
return VoidOutcome(outcome.error());
}
}
VoidOutcome OssClientImpl::DeleteBucketEncryption(const DeleteBucketEncryptionRequest& request) const
{
auto outcome = MakeRequest(request, Http::Method::Delete);
if (outcome.isSuccess()) {
VoidResult result;
result.requestId_ = outcome.result().RequestId();
return VoidOutcome(result);
}
else {
return VoidOutcome(outcome.error());
}
}
VoidOutcome OssClientImpl::DeleteBucketTagging(const DeleteBucketTaggingRequest& request) const
{
auto outcome = MakeRequest(request, Http::Method::Delete);
if (outcome.isSuccess()) {
VoidResult result;
result.requestId_ = outcome.result().RequestId();
return VoidOutcome(result);
}
else {
return VoidOutcome(outcome.error());
}
}
VoidOutcome OssClientImpl::DeleteBucketQosInfo(const DeleteBucketQosInfoRequest& request) const
{
auto outcome = MakeRequest(request, Http::Method::Delete);
if (outcome.isSuccess()) {
VoidResult result;
result.requestId_ = outcome.result().RequestId();
return VoidOutcome(result);
}
else {
return VoidOutcome(outcome.error());
}
}
VoidOutcome OssClientImpl::DeleteBucketInventoryConfiguration(const DeleteBucketInventoryConfigurationRequest& request) const
{
auto outcome = MakeRequest(request, Http::Method::Delete);
if (outcome.isSuccess()) {
VoidResult result;
result.requestId_ = outcome.result().RequestId();
return VoidOutcome(result);
}
else {
return VoidOutcome(outcome.error());
}
}
GetBucketAclOutcome OssClientImpl::GetBucketAcl(const GetBucketAclRequest &request) const
{
auto outcome = MakeRequest(request, Http::Method::Get);
if (outcome.isSuccess()) {
GetBucketAclResult result(outcome.result().payload());
result.requestId_ = outcome.result().RequestId();
return result.ParseDone() ? GetBucketAclOutcome(std::move(result)) :
GetBucketAclOutcome(OssError("ParseXMLError", "Parsing ListObject result fail."));
}
else {
return GetBucketAclOutcome(outcome.error());
}
}
GetBucketLocationOutcome OssClientImpl::GetBucketLocation(const GetBucketLocationRequest &request) const
{
auto outcome = MakeRequest(request, Http::Method::Get);
if (outcome.isSuccess()) {
GetBucketLocationResult result(outcome.result().payload());
result.requestId_ = outcome.result().RequestId();
return result.ParseDone() ? GetBucketLocationOutcome(std::move(result)) :
GetBucketLocationOutcome(OssError("ParseXMLError", "Parsing ListObject result fail."));
}
else {
return GetBucketLocationOutcome(outcome.error());
}
}
GetBucketInfoOutcome OssClientImpl::GetBucketInfo(const GetBucketInfoRequest &request) const
{
auto outcome = MakeRequest(request, Http::Method::Get);
if (outcome.isSuccess()) {
GetBucketInfoResult result(outcome.result().payload());
result.requestId_ = outcome.result().RequestId();
return result.ParseDone() ? GetBucketInfoOutcome(std::move(result)) :
GetBucketInfoOutcome(OssError("ParseXMLError", "Parsing ListObject result fail."));
}
else {
return GetBucketInfoOutcome(outcome.error());
}
}
GetBucketLoggingOutcome OssClientImpl::GetBucketLogging(const GetBucketLoggingRequest &request) const
{
auto outcome = MakeRequest(request, Http::Method::Get);
if (outcome.isSuccess()) {
GetBucketLoggingResult result(outcome.result().payload());
result.requestId_ = outcome.result().RequestId();
return result.ParseDone() ? GetBucketLoggingOutcome(std::move(result)) :
GetBucketLoggingOutcome(OssError("ParseXMLError", "Parsing ListObject result fail."));
}
else {
return GetBucketLoggingOutcome(outcome.error());
}
}
GetBucketWebsiteOutcome OssClientImpl::GetBucketWebsite(const GetBucketWebsiteRequest &request) const
{
auto outcome = MakeRequest(request, Http::Method::Get);
if (outcome.isSuccess()) {
GetBucketWebsiteResult result(outcome.result().payload());
result.requestId_ = outcome.result().RequestId();
return result.ParseDone() ? GetBucketWebsiteOutcome(std::move(result)) :
GetBucketWebsiteOutcome(OssError("ParseXMLError", "Parsing ListObject result fail."));
}
else {
return GetBucketWebsiteOutcome(outcome.error());
}
}
GetBucketRefererOutcome OssClientImpl::GetBucketReferer(const GetBucketRefererRequest &request) const
{
auto outcome = MakeRequest(request, Http::Method::Get);
if (outcome.isSuccess()) {
GetBucketRefererResult result(outcome.result().payload());
result.requestId_ = outcome.result().RequestId();
return result.ParseDone() ? GetBucketRefererOutcome(std::move(result)) :
GetBucketRefererOutcome(OssError("ParseXMLError", "Parsing ListObject result fail."));
}
else {
return GetBucketRefererOutcome(outcome.error());
}
}
GetBucketLifecycleOutcome OssClientImpl::GetBucketLifecycle(const GetBucketLifecycleRequest &request) const
{
auto outcome = MakeRequest(request, Http::Method::Get);
if (outcome.isSuccess()) {
GetBucketLifecycleResult result(outcome.result().payload());
result.requestId_ = outcome.result().RequestId();
return result.ParseDone() ? GetBucketLifecycleOutcome(std::move(result)) :
GetBucketLifecycleOutcome(OssError("ParseXMLError", "Parsing ListObject result fail."));
}
else {
return GetBucketLifecycleOutcome(outcome.error());
}
}
GetBucketStatOutcome OssClientImpl::GetBucketStat(const GetBucketStatRequest &request) const
{
auto outcome = MakeRequest(request, Http::Method::Get);
if (outcome.isSuccess()) {
GetBucketStatResult result(outcome.result().payload());
result.requestId_ = outcome.result().RequestId();
return result.ParseDone() ? GetBucketStatOutcome(std::move(result)) :
GetBucketStatOutcome(OssError("ParseXMLError", "Parsing ListObject result fail."));
}
else {
return GetBucketStatOutcome(outcome.error());
}
}
GetBucketCorsOutcome OssClientImpl::GetBucketCors(const GetBucketCorsRequest &request) const
{
auto outcome = MakeRequest(request, Http::Method::Get);
if (outcome.isSuccess()) {
GetBucketCorsResult result(outcome.result().payload());
result.requestId_ = outcome.result().RequestId();
return result.ParseDone() ? GetBucketCorsOutcome(std::move(result)) :
GetBucketCorsOutcome(OssError("ParseXMLError", "Parsing ListObject result fail."));
}
else {
return GetBucketCorsOutcome(outcome.error());
}
}
GetBucketStorageCapacityOutcome OssClientImpl::GetBucketStorageCapacity(const GetBucketStorageCapacityRequest& request) const
{
auto outcome = MakeRequest(request, Http::Method::Get);
if (outcome.isSuccess()) {
GetBucketStorageCapacityResult result(outcome.result().payload());
result.requestId_ = outcome.result().RequestId();
return result.ParseDone() ? GetBucketStorageCapacityOutcome(std::move(result)) :
GetBucketStorageCapacityOutcome(OssError("ParseXMLError", "Parsing ListObject result fail."));
}
else {
return GetBucketStorageCapacityOutcome(outcome.error());
}
}
GetBucketPolicyOutcome OssClientImpl::GetBucketPolicy(const GetBucketPolicyRequest& request) const
{
auto outcome = MakeRequest(request, Http::Method::Get);
if (outcome.isSuccess()) {
GetBucketPolicyResult result(outcome.result().payload());
result.requestId_ = outcome.result().RequestId();
return result.ParseDone() ? GetBucketPolicyOutcome(std::move(result)) :
GetBucketPolicyOutcome(OssError("ParseXMLError", "Parsing ListObject result fail."));
}
else {
return GetBucketPolicyOutcome(outcome.error());
}
}
GetBucketPaymentOutcome OssClientImpl::GetBucketRequestPayment(const GetBucketRequestPaymentRequest& request) const
{
auto outcome = MakeRequest(request, Http::Method::Get);
if (outcome.isSuccess()) {
GetBucketPaymentResult result(outcome.result().payload());
result.requestId_ = outcome.result().RequestId();
return result.ParseDone() ? GetBucketPaymentOutcome(std::move(result)) :
GetBucketPaymentOutcome(OssError("ParseXMLError", "Parsing GetBucketPayment result fail."));
}
else {
return GetBucketPaymentOutcome(outcome.error());
}
}
GetBucketEncryptionOutcome OssClientImpl::GetBucketEncryption(const GetBucketEncryptionRequest& request) const
{
auto outcome = MakeRequest(request, Http::Method::Get);
if (outcome.isSuccess()) {
GetBucketEncryptionResult result(outcome.result().payload());
result.requestId_ = outcome.result().RequestId();
return result.ParseDone() ? GetBucketEncryptionOutcome(std::move(result)) :
GetBucketEncryptionOutcome(OssError("ParseXMLError", "Parsing GetBucketEncryption result fail."));
}
else {
return GetBucketEncryptionOutcome(outcome.error());
}
}
GetBucketTaggingOutcome OssClientImpl::GetBucketTagging(const GetBucketTaggingRequest& request) const
{
auto outcome = MakeRequest(request, Http::Method::Get);
if (outcome.isSuccess()) {
GetBucketTaggingResult result(outcome.result().payload());
result.requestId_ = outcome.result().RequestId();
return result.ParseDone() ? GetBucketTaggingOutcome(std::move(result)) :
GetBucketTaggingOutcome(OssError("ParseXMLError", "Parsing GetBucketTagging result fail."));
}
else {
return GetBucketTaggingOutcome(outcome.error());
}
}
GetBucketQosInfoOutcome OssClientImpl::GetBucketQosInfo(const GetBucketQosInfoRequest& request) const
{
auto outcome = MakeRequest(request, Http::Method::Get);
if (outcome.isSuccess()) {
GetBucketQosInfoResult result(outcome.result().payload());
result.requestId_ = outcome.result().RequestId();
return result.ParseDone() ? GetBucketQosInfoOutcome(std::move(result)) :
GetBucketQosInfoOutcome(OssError("ParseXMLError", "Parsing GetBucketQosInfo result fail."));
}
else {
return GetBucketQosInfoOutcome(outcome.error());
}
}
GetUserQosInfoOutcome OssClientImpl::GetUserQosInfo(const GetUserQosInfoRequest& request) const
{
auto outcome = MakeRequest(request, Http::Method::Get);
if (outcome.isSuccess()) {
GetUserQosInfoResult result(outcome.result().payload());
result.requestId_ = outcome.result().RequestId();
return result.ParseDone() ? GetUserQosInfoOutcome(std::move(result)) :
GetUserQosInfoOutcome(OssError("ParseXMLError", "Parsing GetUserQosInfo result fail."));
}
else {
return GetUserQosInfoOutcome(outcome.error());
}
}
GetBucketVersioningOutcome OssClientImpl::GetBucketVersioning(const GetBucketVersioningRequest& request) const
{
auto outcome = MakeRequest(request, Http::Method::Get);
if (outcome.isSuccess()) {
GetBucketVersioningResult result(outcome.result().payload());
result.requestId_ = outcome.result().RequestId();
return result.ParseDone() ? GetBucketVersioningOutcome(std::move(result)) :
GetBucketVersioningOutcome(OssError("ParseXMLError", "Parsing GetBucketVersioning result fail."));
}
else {
return GetBucketVersioningOutcome(outcome.error());
}
}
GetBucketInventoryConfigurationOutcome OssClientImpl::GetBucketInventoryConfiguration(const GetBucketInventoryConfigurationRequest& request) const
{
auto outcome = MakeRequest(request, Http::Method::Get);
if (outcome.isSuccess()) {
GetBucketInventoryConfigurationResult result(outcome.result().payload());
result.requestId_ = outcome.result().RequestId();
return result.ParseDone() ? GetBucketInventoryConfigurationOutcome(std::move(result)) :
GetBucketInventoryConfigurationOutcome(OssError("ParseXMLError", "Parsing GetBucketInventoryConfiguration result fail."));
}
else {
return GetBucketInventoryConfigurationOutcome(outcome.error());
}
}
ListBucketInventoryConfigurationsOutcome OssClientImpl::ListBucketInventoryConfigurations(const ListBucketInventoryConfigurationsRequest& request) const
{
auto outcome = MakeRequest(request, Http::Method::Get);
if (outcome.isSuccess()) {
ListBucketInventoryConfigurationsResult result(outcome.result().payload());
result.requestId_ = outcome.result().RequestId();
return result.ParseDone() ? ListBucketInventoryConfigurationsOutcome(std::move(result)) :
ListBucketInventoryConfigurationsOutcome(OssError("ParseXMLError", "Parsing ListBucketInventoryConfigurations result fail."));
}
else {
return ListBucketInventoryConfigurationsOutcome(outcome.error());
}
}
#endif
ListObjectOutcome OssClientImpl::ListObjects(const ListObjectsRequest &request) const
{
auto outcome = MakeRequest(request, Http::Method::Get);
if (outcome.isSuccess()) {
ListObjectsResult result(outcome.result().payload());
result.requestId_ = outcome.result().RequestId();
return result.ParseDone() ? ListObjectOutcome(std::move(result)) :
ListObjectOutcome(OssError("ParseXMLError", "Parsing ListObject result fail."));
}
else {
return ListObjectOutcome(outcome.error());
}
}
ListObjectVersionsOutcome OssClientImpl::ListObjectVersions(const ListObjectVersionsRequest &request) const
{
auto outcome = MakeRequest(request, Http::Method::Get);
if (outcome.isSuccess()) {
ListObjectVersionsResult result(outcome.result().payload());
result.requestId_ = outcome.result().RequestId();
return result.ParseDone() ? ListObjectVersionsOutcome(std::move(result)) :
ListObjectVersionsOutcome(OssError("ParseXMLError", "Parsing ListObjectVersions result fail."));
}
else {
return ListObjectVersionsOutcome(outcome.error());
}
}
#undef GetObject
GetObjectOutcome OssClientImpl::GetObject(const GetObjectRequest &request) const
{
auto outcome = MakeRequest(request, Http::Method::Get);
if (outcome.isSuccess()) {
return GetObjectOutcome(GetObjectResult(request.Bucket(), request.Key(),
outcome.result().payload(),outcome.result().headerCollection()));
}
else {
return GetObjectOutcome(outcome.error());
}
}
PutObjectOutcome OssClientImpl::PutObject(const PutObjectRequest &request) const
{
auto outcome = MakeRequest(request, Http::Method::Put);
if (outcome.isSuccess()) {
return PutObjectOutcome(PutObjectResult(outcome.result().headerCollection(),
outcome.result().payload()));
}
else {
return PutObjectOutcome(outcome.error());
}
}
DeleteObjectOutcome OssClientImpl::DeleteObject(const DeleteObjectRequest &request) const
{
auto outcome = MakeRequest(request, Http::Method::Delete);
if (outcome.isSuccess()) {
return DeleteObjectOutcome(DeleteObjectResult(outcome.result().headerCollection()));
}
else {
return DeleteObjectOutcome(outcome.error());
}
}
DeleteObjecstOutcome OssClientImpl::DeleteObjects(const DeleteObjectsRequest &request) const
{
auto outcome = MakeRequest(request, Http::Method::Post);
if (outcome.isSuccess()) {
DeleteObjectsResult result(outcome.result().payload());
result.requestId_ = outcome.result().RequestId();
return result.ParseDone() ? DeleteObjecstOutcome(std::move(result)) :
DeleteObjecstOutcome(OssError("ParseXMLError", "Parsing DeleteObjects result fail."));
}
else {
return DeleteObjecstOutcome(outcome.error());
}
}
DeleteObjecVersionstOutcome OssClientImpl::DeleteObjectVersions(const DeleteObjectVersionsRequest& request) const
{
auto outcome = MakeRequest(request, Http::Method::Post);
if (outcome.isSuccess()) {
DeleteObjectVersionsResult result(outcome.result().payload());
result.requestId_ = outcome.result().RequestId();
return result.ParseDone() ? DeleteObjecVersionstOutcome(std::move(result)) :
DeleteObjecVersionstOutcome(OssError("ParseXMLError", "Parsing DeleteObjectVersions result fail."));
}
else {
return DeleteObjecVersionstOutcome(outcome.error());
}
}
ObjectMetaDataOutcome OssClientImpl::HeadObject(const HeadObjectRequest &request) const
{
auto outcome = MakeRequest(request, Http::Method::Head);
if (outcome.isSuccess()) {
ObjectMetaData metaData = outcome.result().headerCollection();
return ObjectMetaDataOutcome(std::move(metaData));
}
else {
return ObjectMetaDataOutcome(outcome.error());
}
}
ObjectMetaDataOutcome OssClientImpl::GetObjectMeta(const GetObjectMetaRequest &request) const
{
auto outcome = MakeRequest(request, Http::Method::Head);
if (outcome.isSuccess()) {
ObjectMetaData metaData = outcome.result().headerCollection();
return ObjectMetaDataOutcome(std::move(metaData));
}
else {
return ObjectMetaDataOutcome(outcome.error());
}
}
GetObjectAclOutcome OssClientImpl::GetObjectAcl(const GetObjectAclRequest &request) const
{
auto outcome = MakeRequest(request, Http::Method::Get);
if (outcome.isSuccess()) {
GetObjectAclResult result(outcome.result().headerCollection(), outcome.result().payload());
return result.ParseDone() ? GetObjectAclOutcome(std::move(result)) :
GetObjectAclOutcome(OssError("ParseXMLError", "Parsing GetObjectAcl result fail."));
}
else {
return GetObjectAclOutcome(outcome.error());
}
}
AppendObjectOutcome OssClientImpl::AppendObject(const AppendObjectRequest &request) const
{
auto outcome = MakeRequest(request, Http::Method::Post);
if (outcome.isSuccess()) {
AppendObjectResult result(outcome.result().headerCollection());
return result.ParseDone() ? AppendObjectOutcome(std::move(result)) :
AppendObjectOutcome(OssError("ParseXMLError", "no position or no crc64"));
}
else {
return AppendObjectOutcome(outcome.error());
}
}
CopyObjectOutcome OssClientImpl::CopyObject(const CopyObjectRequest &request) const
{
auto outcome = MakeRequest(request, Http::Method::Put);
if (outcome.isSuccess()) {
return CopyObjectOutcome(CopyObjectResult(outcome.result().headerCollection(), outcome.result().payload()));
}
else {
return CopyObjectOutcome(outcome.error());
}
}
GetSymlinkOutcome OssClientImpl::GetSymlink(const GetSymlinkRequest &request) const
{
auto outcome = MakeRequest(request, Http::Method::Get);
if (outcome.isSuccess()) {
return GetSymlinkOutcome(GetSymlinkResult(outcome.result().headerCollection()));
}
else {
return GetSymlinkOutcome(outcome.error());
}
}
RestoreObjectOutcome OssClientImpl::RestoreObject(const RestoreObjectRequest &request) const
{
auto outcome = MakeRequest(request, Http::Method::Post);
if (outcome.isSuccess()) {
return RestoreObjectOutcome(RestoreObjectResult(outcome.result().headerCollection()));
}
else {
return RestoreObjectOutcome(outcome.error());
}
}
CreateSymlinkOutcome OssClientImpl::CreateSymlink(const CreateSymlinkRequest &request) const
{
auto outcome = MakeRequest(request, Http::Method::Put);
if (outcome.isSuccess()) {
return CreateSymlinkOutcome(CreateSymlinkResult(outcome.result().headerCollection()));
}
else {
return CreateSymlinkOutcome(outcome.error());
}
}
SetObjectAclOutcome OssClientImpl::SetObjectAcl(const SetObjectAclRequest &request) const
{
auto outcome = MakeRequest(request, Http::Method::Put);
if (outcome.isSuccess()) {
return SetObjectAclOutcome(SetObjectAclResult(outcome.result().headerCollection()));
}
else {
return SetObjectAclOutcome(outcome.error());
}
}
GetObjectOutcome OssClientImpl::ProcessObject(const ProcessObjectRequest &request) const
{
auto outcome = MakeRequest(request, Http::Method::Post);
if (outcome.isSuccess()) {
return GetObjectOutcome(GetObjectResult(request.Bucket(), request.Key(),
outcome.result().payload(), outcome.result().headerCollection()));
}
else {
return GetObjectOutcome(outcome.error());
}
}
GetObjectOutcome OssClientImpl::SelectObject(const SelectObjectRequest &request) const
{
auto outcome = MakeRequest(request, Http::Method::Post);
int ret = request.dispose();
if (outcome.isSuccess()) {
return GetObjectOutcome(GetObjectResult(request.Bucket(), request.Key(),
outcome.result().payload(), outcome.result().headerCollection()));
}
else {
if (ret != 0) {
return GetObjectOutcome(OssError("SelectObjectError", request.validateMessage(ret)));
}
return GetObjectOutcome(outcome.error());
}
}
CreateSelectObjectMetaOutcome OssClientImpl::CreateSelectObjectMeta(const CreateSelectObjectMetaRequest &request) const
{
auto outcome = MakeRequest(request, Http::Method::Post);
if (outcome.isSuccess()) {
CreateSelectObjectMetaResult result(request.Bucket(), request.Key(),
outcome.result().RequestId(), outcome.result().payload());
return result.ParseDone() ? CreateSelectObjectMetaOutcome(result) :
CreateSelectObjectMetaOutcome(OssError("ParseIOStreamError", "Parse create select object meta IOStream fail."));
}
else {
return CreateSelectObjectMetaOutcome(outcome.error());
}
}
SetObjectTaggingOutcome OssClientImpl::SetObjectTagging(const SetObjectTaggingRequest& request) const
{
auto outcome = MakeRequest(request, Http::Method::Put);
if (outcome.isSuccess()) {
return SetObjectTaggingOutcome(SetObjectTaggingResult(outcome.result().headerCollection()));
}
else {
return SetObjectTaggingOutcome(outcome.error());
}
}
DeleteObjectTaggingOutcome OssClientImpl::DeleteObjectTagging(const DeleteObjectTaggingRequest& request) const
{
auto outcome = MakeRequest(request, Http::Method::Delete);
if (outcome.isSuccess()) {
return DeleteObjectTaggingOutcome(DeleteObjectTaggingResult(outcome.result().headerCollection()));
}
else {
return DeleteObjectTaggingOutcome(outcome.error());
}
}
GetObjectTaggingOutcome OssClientImpl::GetObjectTagging(const GetObjectTaggingRequest& request) const
{
auto outcome = MakeRequest(request, Http::Method::Get);
if (outcome.isSuccess()) {
GetObjectTaggingResult result(outcome.result().headerCollection(), outcome.result().payload());
return result.ParseDone() ? GetObjectTaggingOutcome(std::move(result)) :
GetObjectTaggingOutcome(OssError("ParseXMLError", "Parsing ObjectTagging result fail."));
}
else {
return GetObjectTaggingOutcome(outcome.error());
}
}
StringOutcome OssClientImpl::GeneratePresignedUrl(const GeneratePresignedUrlRequest &request) const
{
if (!IsValidBucketName(request.bucket_) ||
!IsValidObjectKey(request.key_)) {
return StringOutcome(OssError("ValidateError", "The Bucket or Key is invalid."));
}
HeaderCollection headers = request.metaData_.toHeaderCollection();
ParameterCollection parameters;
const Credentials credentials = credentialsProvider_->getCredentials();
if (!credentials.SessionToken().empty()) {
parameters["security-token"] = credentials.SessionToken();
}
for (auto const¶m : request.parameters_) {
parameters[param.first] = param.second;
}
SignUtils signUtils(signer_->version());
auto method = Http::MethodToString(request.method_);
auto resource = std::string().append("/").append(request.bucket_).append("/").append(request.key_);
auto date = headers[Http::EXPIRES];
signUtils.build(method, resource, date, headers, parameters);
auto signature = signer_->generate(signUtils.CanonicalString(), credentials.AccessKeySecret());
parameters["Expires"] = date;
parameters["OSSAccessKeyId"] = credentials.AccessKeyId();
parameters["Signature"] = signature;
std::stringstream ss;
ss << CombineHostString(endpoint_, request.bucket_, configuration().isCname);
ss << CombinePathString(endpoint_, request.bucket_, request.key_);
ss << "?";
ss << CombineQueryString(parameters);
return StringOutcome(ss.str());
}
GetObjectOutcome OssClientImpl::GetObjectByUrl(const GetObjectByUrlRequest &request) const
{
auto outcome = BASE::AttemptRequest(endpoint_, request, Http::Method::Get);
if (outcome.isSuccess()) {
return GetObjectOutcome(GetObjectResult("", "",
outcome.result()->Body(),
outcome.result()->Headers()));
}
else {
return GetObjectOutcome(buildError(outcome.error()));
}
}
PutObjectOutcome OssClientImpl::PutObjectByUrl(const PutObjectByUrlRequest &request) const
{
auto outcome = BASE::AttemptRequest(endpoint_, request, Http::Method::Put);
if (outcome.isSuccess()) {
return PutObjectOutcome(PutObjectResult(outcome.result()->Headers(),
outcome.result()->Body()));
}
else {
return PutObjectOutcome(buildError(outcome.error()));
}
}
InitiateMultipartUploadOutcome OssClientImpl::InitiateMultipartUpload(const InitiateMultipartUploadRequest &request) const
{
auto outcome = MakeRequest(request, Http::Post);
if(outcome.isSuccess()){
InitiateMultipartUploadResult result(outcome.result().payload());
result.requestId_ = outcome.result().RequestId();
return result.ParseDone() ? InitiateMultipartUploadOutcome(std::move(result)):
InitiateMultipartUploadOutcome(
OssError("InitiateMultipartUploadError",
"Parsing InitiateMultipartUploadResult fail"));
}
else{
return InitiateMultipartUploadOutcome(outcome.error());
}
}
PutObjectOutcome OssClientImpl::UploadPart(const UploadPartRequest &request)const
{
auto outcome = MakeRequest(request, Http::Put);
if(outcome.isSuccess()){
const HeaderCollection& header = outcome.result().headerCollection();
return PutObjectOutcome(PutObjectResult(header));
}else{
return PutObjectOutcome(outcome.error());
}
}
UploadPartCopyOutcome OssClientImpl::UploadPartCopy(const UploadPartCopyRequest &request) const
{
auto outcome = MakeRequest(request, Http::Put);
if(outcome.isSuccess()){
const HeaderCollection& header = outcome.result().headerCollection();
return UploadPartCopyOutcome(
UploadPartCopyResult(outcome.result().payload(), header));
}
else{
return UploadPartCopyOutcome(outcome.error());
}
}
CompleteMultipartUploadOutcome OssClientImpl::CompleteMultipartUpload(const CompleteMultipartUploadRequest &request) const
{
auto outcome = MakeRequest(request, Http::Post);
if (outcome.isSuccess()){
CompleteMultipartUploadResult result(outcome.result().payload(), outcome.result().headerCollection());
result.requestId_ = outcome.result().RequestId();
return result.ParseDone() ?
CompleteMultipartUploadOutcome(std::move(result)) :
CompleteMultipartUploadOutcome(OssError("CompleteMultipartUpload", ""));
}
else {
return CompleteMultipartUploadOutcome(outcome.error());
}
}
VoidOutcome OssClientImpl::AbortMultipartUpload(const AbortMultipartUploadRequest &request) const
{
auto outcome = MakeRequest(request, Http::Delete);
if(outcome.isSuccess()){
VoidResult result;
result.requestId_ = outcome.result().RequestId();
return VoidOutcome(result);
}
else {
return VoidOutcome(outcome.error());
}
}
ListMultipartUploadsOutcome OssClientImpl::ListMultipartUploads(
const ListMultipartUploadsRequest &request) const
{
auto outcome = MakeRequest(request, Http::Get);
if(outcome.isSuccess())
{
ListMultipartUploadsResult result(outcome.result().payload());
result.requestId_ = outcome.result().RequestId();
return result.ParseDone() ?
ListMultipartUploadsOutcome(std::move(result)) :
ListMultipartUploadsOutcome(OssError("ListMultipartUploads", "Parse Error"));
}
else {
return ListMultipartUploadsOutcome(outcome.error());
}
}
ListPartsOutcome OssClientImpl::ListParts(const ListPartsRequest &request) const
{
auto outcome = MakeRequest(request, Http::Get);
if(outcome.isSuccess())
{
ListPartsResult result(outcome.result().payload());
result.requestId_ = outcome.result().RequestId();
return result.ParseDone() ?
ListPartsOutcome(std::move(result)) :
ListPartsOutcome(OssError("ListParts", "Parse Error"));
}else{
return ListPartsOutcome(outcome.error());
}
}
#if (!OSS_DISABLE_RESUAMABLE)
/*Resumable Operation*/
PutObjectOutcome OssClientImpl::ResumableUploadObject(const UploadObjectRequest& request) const
{
const auto& reqeustBase = static_cast<const OssResumableBaseRequest &>(request);
int code = reqeustBase.validate();
if (code != 0) {
return PutObjectOutcome(OssError("ValidateError", reqeustBase.validateMessage(code)));
}
if (request.ObjectSize() <= request.PartSize())
{
auto content = GetFstreamByPath(request.FilePath(), request.FilePathW(),
std::ios::in | std::ios::binary);
PutObjectRequest putObjectReq(request.Bucket(), request.Key(), content, request.MetaData());
if (request.TransferProgress().Handler) {
putObjectReq.setTransferProgress(request.TransferProgress());
}
if (request.RequestPayer() == RequestPayer::Requester) {
putObjectReq.setRequestPayer(request.RequestPayer());
}
if (request.TrafficLimit() != 0) {
putObjectReq.setTrafficLimit(request.TrafficLimit());
}
return PutObject(putObjectReq);
}
else
{
ResumableUploader uploader(request, this);
return uploader.Upload();
}
}
CopyObjectOutcome OssClientImpl::ResumableCopyObject(const MultiCopyObjectRequest& request) const
{
const auto& reqeustBase = static_cast<const OssResumableBaseRequest &>(request);
int code = reqeustBase.validate();
if (code != 0) {
return CopyObjectOutcome(OssError("ValidateError", reqeustBase.validateMessage(code)));
}
auto getObjectMetaReq = GetObjectMetaRequest(request.SrcBucket(), request.SrcKey());
if (request.RequestPayer() == RequestPayer::Requester) {
getObjectMetaReq.setRequestPayer(request.RequestPayer());
}
if (!request.VersionId().empty()) {
getObjectMetaReq.setVersionId(request.VersionId());
}
auto outcome = GetObjectMeta(getObjectMetaReq);
if (!outcome.isSuccess()) {
return CopyObjectOutcome(outcome.error());
}
auto objectSize = outcome.result().ContentLength();
if (objectSize < (int64_t)request.PartSize()) {
auto copyObjectReq = CopyObjectRequest(request.Bucket(), request.Key(), request.MetaData());
copyObjectReq.setCopySource(request.SrcBucket(), request.SrcKey());
if (request.RequestPayer() == RequestPayer::Requester) {
copyObjectReq.setRequestPayer(request.RequestPayer());
}
if (request.TrafficLimit() != 0) {
copyObjectReq.setTrafficLimit(request.TrafficLimit());
}
if (!request.VersionId().empty()) {
copyObjectReq.setVersionId(request.VersionId());
}
return CopyObject(copyObjectReq);
}
ResumableCopier copier(request, this, objectSize);
return copier.Copy();
}
GetObjectOutcome OssClientImpl::ResumableDownloadObject(const DownloadObjectRequest &request) const
{
const auto& reqeustBase = static_cast<const OssResumableBaseRequest &>(request);
int code = reqeustBase.validate();
if (code != 0) {
return GetObjectOutcome(OssError("ValidateError", reqeustBase.validateMessage(code)));
}
auto getObjectMetaReq = GetObjectMetaRequest(request.Bucket(), request.Key());
if (request.RequestPayer() == RequestPayer::Requester) {
getObjectMetaReq.setRequestPayer(request.RequestPayer());
}
if (!request.VersionId().empty()) {
getObjectMetaReq.setVersionId(request.VersionId());
}
auto hOutcome = GetObjectMeta(getObjectMetaReq);
if (!hOutcome.isSuccess()) {
return GetObjectOutcome(hOutcome.error());
}
auto objectSize = hOutcome.result().ContentLength();
if (objectSize < (int64_t)request.PartSize()) {
auto getObjectReq = GetObjectRequest(request.Bucket(), request.Key(), request.ModifiedSinceConstraint(), request.UnmodifiedSinceConstraint(),request.MatchingETagsConstraint(), request.NonmatchingETagsConstraint(), request.ResponseHeaderParameters());
if (request.RangeIsSet()) {
getObjectReq.setRange(request.RangeStart(), request.RangeEnd());
}
if (request.TransferProgress().Handler) {
getObjectReq.setTransferProgress(request.TransferProgress());
}
if (request.RequestPayer() == RequestPayer::Requester) {
getObjectReq.setRequestPayer(request.RequestPayer());
}
if (request.TrafficLimit() != 0) {
getObjectReq.setTrafficLimit(request.TrafficLimit());
}
if (!request.VersionId().empty()) {
getObjectReq.setVersionId(request.VersionId());
}
getObjectReq.setResponseStreamFactory([=]() {
return GetFstreamByPath(request.FilePath(), request.FilePathW(),
std::ios_base::out | std::ios_base::in | std::ios_base::trunc | std::ios_base::binary);
});
auto outcome = this->GetObject(getObjectReq);
std::shared_ptr<std::iostream> content = nullptr;
outcome.result().setContent(content);
if (IsFileExist(request.TempFilePath())) {
RemoveFile(request.TempFilePath());
}
#ifdef _WIN32
else if (IsFileExist(request.TempFilePathW())) {
RemoveFile(request.TempFilePathW());
}
#endif
return outcome;
}
ResumableDownloader downloader(request, this, objectSize);
return downloader.Download();
}
#endif
#if (!OSS_DISABLE_LIVECHANNEL)
/*Live Channel*/
VoidOutcome OssClientImpl::PutLiveChannelStatus(const PutLiveChannelStatusRequest& request) const
{
auto outcome = MakeRequest(request, Http::Put);
if(outcome.isSuccess())
{
VoidResult result;
result.requestId_ = outcome.result().RequestId();
return VoidOutcome(result);
}else{
return VoidOutcome(outcome.error());
}
}
PutLiveChannelOutcome OssClientImpl::PutLiveChannel(const PutLiveChannelRequest& request) const
{
auto outcome = MakeRequest(request, Http::Put);
if(outcome.isSuccess())
{
PutLiveChannelResult result(outcome.result().payload());
result.requestId_ = outcome.result().RequestId();
return result.ParseDone()?
PutLiveChannelOutcome(std::move(result)):
PutLiveChannelOutcome(OssError("PutLiveChannelError", "Parse Error"));
}else{
return PutLiveChannelOutcome(outcome.error());
}
}
VoidOutcome OssClientImpl::PostVodPlaylist(const PostVodPlaylistRequest &request) const
{
auto outcome = MakeRequest(request, Http::Post);
if(outcome.isSuccess())
{
VoidResult result;
result.requestId_ = outcome.result().RequestId();
return VoidOutcome(std::move(result));
}else{
return VoidOutcome(outcome.error());
}
}
GetVodPlaylistOutcome OssClientImpl::GetVodPlaylist(const GetVodPlaylistRequest &request) const
{
auto outcome = MakeRequest(request, Http::Get);
if(outcome.isSuccess())
{
GetVodPlaylistResult result(outcome.result().payload());
result.requestId_ = outcome.result().RequestId();
return GetVodPlaylistOutcome(std::move(result));
}else{
return GetVodPlaylistOutcome(outcome.error());
}
}
GetLiveChannelStatOutcome OssClientImpl::GetLiveChannelStat(const GetLiveChannelStatRequest &request) const
{
auto outcome = MakeRequest(request, Http::Get);
if(outcome.isSuccess())
{
GetLiveChannelStatResult result(outcome.result().payload());
result.requestId_ = outcome.result().RequestId();
return result.ParseDone()?
GetLiveChannelStatOutcome(std::move(result)):
GetLiveChannelStatOutcome(OssError("GetLiveChannelStatError", "Parse Error"));
}else{
return GetLiveChannelStatOutcome(outcome.error());
}
}
GetLiveChannelInfoOutcome OssClientImpl::GetLiveChannelInfo(const GetLiveChannelInfoRequest &request) const
{
auto outcome = MakeRequest(request, Http::Get);
if(outcome.isSuccess())
{
GetLiveChannelInfoResult result(outcome.result().payload());
result.requestId_ = outcome.result().RequestId();
return result.ParseDone()?
GetLiveChannelInfoOutcome(std::move(result)):
GetLiveChannelInfoOutcome(OssError("GetLiveChannelStatError", "Parse Error"));
}else{
return GetLiveChannelInfoOutcome(outcome.error());
}
}
GetLiveChannelHistoryOutcome OssClientImpl::GetLiveChannelHistory(const GetLiveChannelHistoryRequest &request) const
{
auto outcome = MakeRequest(request, Http::Get);
if(outcome.isSuccess())
{
GetLiveChannelHistoryResult result(outcome.result().payload());
result.requestId_ = outcome.result().RequestId();
return result.ParseDone()?
GetLiveChannelHistoryOutcome(std::move(result)):
GetLiveChannelHistoryOutcome(OssError("GetLiveChannelStatError", "Parse Error"));
}else{
return GetLiveChannelHistoryOutcome(outcome.error());
}
}
ListLiveChannelOutcome OssClientImpl::ListLiveChannel(const ListLiveChannelRequest &request) const
{
auto outcome = MakeRequest(request, Http::Get);
if(outcome.isSuccess())
{
ListLiveChannelResult result(outcome.result().payload());
result.requestId_ = outcome.result().RequestId();
return result.ParseDone()?
ListLiveChannelOutcome(std::move(result)):
ListLiveChannelOutcome(OssError("GetLiveChannelStatError", "Parse Error"));
}else{
return ListLiveChannelOutcome(outcome.error());
}
}
VoidOutcome OssClientImpl::DeleteLiveChannel(const DeleteLiveChannelRequest &request) const
{
auto outcome = MakeRequest(request, Http::Delete);
if(outcome.isSuccess())
{
VoidResult result;
result.requestId_ = outcome.result().RequestId();
return VoidOutcome(std::move(result));
}else{
return VoidOutcome(outcome.error());
}
}
StringOutcome OssClientImpl::GenerateRTMPSignedUrl(const GenerateRTMPSignedUrlRequest &request) const
{
if (!IsValidBucketName(request.bucket_) ||
!IsValidChannelName(request.ChannelName()) ||
!IsValidPlayListName(request.PlayList()) ||
0 == request.Expires()) {
return StringOutcome(OssError("ValidateError", "The Bucket or ChannelName or "
"PlayListName or Expires is invalid."));
}
ParameterCollection parameters;
const Credentials credentials = credentialsProvider_->getCredentials();
if (!credentials.SessionToken().empty()) {
parameters["security-token"] = credentials.SessionToken();
}
parameters = request.Parameters();
std::string expireStr;
std::stringstream ss;
ss << request.Expires();
expireStr = ss.str();
SignUtils signUtils(signer_->version());
auto resource = std::string().append("/").append(request.Bucket()).append("/").append(request.ChannelName());
signUtils.build(expireStr, resource, parameters);
auto signature = signer_->generate(signUtils.CanonicalString(), credentials.AccessKeySecret());
parameters["Expires"] = expireStr;
parameters["OSSAccessKeyId"] = credentials.AccessKeyId();
parameters["Signature"] = signature;
ss.str("");
ss << CombineRTMPString(endpoint_, request.bucket_, configuration().isCname);
ss << "/live";
ss << CombinePathString(endpoint_, request.bucket_, request.key_);
ss << "?";
ss << CombineQueryString(parameters);
return StringOutcome(ss.str());
}
#endif
/*Requests control*/
void OssClientImpl::DisableRequest()
{
BASE::disableRequest();
OSS_LOG(LogLevel::LogDebug, TAG, "client(%p) DisableRequest", this);
}
void OssClientImpl::EnableRequest()
{
BASE::enableRequest();
OSS_LOG(LogLevel::LogDebug, TAG, "client(%p) EnableRequest", this);
}
| YifuLiu/AliOS-Things | components/oss/src/OssClientImpl.cc | C++ | apache-2.0 | 62,456 |
/*
* 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_OSS_OSSCLIENTIMPL_H_
#define ALIBABACLOUD_OSS_OSSCLIENTIMPL_H_
#include <alibabacloud/oss/client/ClientConfiguration.h>
#include <alibabacloud/oss/auth/CredentialsProvider.h>
#include <alibabacloud/oss/OssRequest.h>
#include <alibabacloud/oss/OssResponse.h>
#include <alibabacloud/oss/utils/Executor.h>
#include <alibabacloud/oss/OssFwd.h>
#include "auth/Signer.h"
#include "client/Client.h"
#ifdef GetObject
#undef GetObject
#endif
namespace AlibabaCloud
{
namespace OSS
{
class OssClientImpl : public Client
{
public:
typedef Client BASE;
OssClientImpl(const std::string &endpoint, const std::shared_ptr<CredentialsProvider>& credentialsProvider, const ClientConfiguration & configuration);
virtual ~OssClientImpl();
int asyncExecute(Runnable * r) const;
#if (!OSS_DISABLE_BUCKET)
ListBucketsOutcome ListBuckets(const ListBucketsRequest &request) const;
CreateBucketOutcome CreateBucket(const CreateBucketRequest &request) const;
VoidOutcome SetBucketAcl(const SetBucketAclRequest& request) const;
VoidOutcome SetBucketLogging(const SetBucketLoggingRequest& request) const;
VoidOutcome SetBucketWebsite(const SetBucketWebsiteRequest& request) const;
VoidOutcome SetBucketReferer(const SetBucketRefererRequest& request) const;
VoidOutcome SetBucketLifecycle(const SetBucketLifecycleRequest& request) const;
VoidOutcome SetBucketCors(const SetBucketCorsRequest& request) const;
VoidOutcome SetBucketStorageCapacity(const SetBucketStorageCapacityRequest& request) const;
VoidOutcome SetBucketPolicy(const SetBucketPolicyRequest& request) const;
VoidOutcome SetBucketRequestPayment(const SetBucketRequestPaymentRequest& request) const;
VoidOutcome SetBucketEncryption(const SetBucketEncryptionRequest& request) const;
VoidOutcome SetBucketTagging(const SetBucketTaggingRequest& request) const;
VoidOutcome SetBucketQosInfo(const SetBucketQosInfoRequest& request) const;
VoidOutcome SetBucketVersioning(const SetBucketVersioningRequest& request) const;
VoidOutcome SetBucketInventoryConfiguration(const SetBucketInventoryConfigurationRequest& request) const;
VoidOutcome DeleteBucket(const DeleteBucketRequest &request) const;
VoidOutcome DeleteBucketLogging(const DeleteBucketLoggingRequest& request) const;
VoidOutcome DeleteBucketWebsite(const DeleteBucketWebsiteRequest& request) const;
VoidOutcome DeleteBucketLifecycle(const DeleteBucketLifecycleRequest& request) const;
VoidOutcome DeleteBucketCors(const DeleteBucketCorsRequest& request) const;
VoidOutcome DeleteBucketPolicy(const DeleteBucketPolicyRequest& request) const;
VoidOutcome DeleteBucketEncryption(const DeleteBucketEncryptionRequest& request) const;
VoidOutcome DeleteBucketTagging(const DeleteBucketTaggingRequest& request) const;
VoidOutcome DeleteBucketQosInfo(const DeleteBucketQosInfoRequest& request) const;
VoidOutcome DeleteBucketInventoryConfiguration(const DeleteBucketInventoryConfigurationRequest& request) const;
ListBucketInventoryConfigurationsOutcome ListBucketInventoryConfigurations(const ListBucketInventoryConfigurationsRequest& request) const;
GetBucketAclOutcome GetBucketAcl(const GetBucketAclRequest &request) const;
GetBucketLocationOutcome GetBucketLocation(const GetBucketLocationRequest &request) const;
GetBucketInfoOutcome GetBucketInfo(const GetBucketInfoRequest &request) const;
GetBucketLoggingOutcome GetBucketLogging(const GetBucketLoggingRequest &request) const;
GetBucketWebsiteOutcome GetBucketWebsite(const GetBucketWebsiteRequest &request) const;
GetBucketRefererOutcome GetBucketReferer(const GetBucketRefererRequest &request) const;
GetBucketLifecycleOutcome GetBucketLifecycle(const GetBucketLifecycleRequest &request) const;
GetBucketStatOutcome GetBucketStat(const GetBucketStatRequest &request) const;
GetBucketCorsOutcome GetBucketCors(const GetBucketCorsRequest &request) const;
GetBucketStorageCapacityOutcome GetBucketStorageCapacity(const GetBucketStorageCapacityRequest& request) const;
GetBucketPolicyOutcome GetBucketPolicy(const GetBucketPolicyRequest& request) const;
GetBucketPaymentOutcome GetBucketRequestPayment(const GetBucketRequestPaymentRequest& request) const;
GetBucketEncryptionOutcome GetBucketEncryption(const GetBucketEncryptionRequest& request) const;
GetBucketTaggingOutcome GetBucketTagging(const GetBucketTaggingRequest& request) const;
GetBucketQosInfoOutcome GetBucketQosInfo(const GetBucketQosInfoRequest& request) const;
GetUserQosInfoOutcome GetUserQosInfo(const GetUserQosInfoRequest& request) const;
GetBucketVersioningOutcome GetBucketVersioning(const GetBucketVersioningRequest& request) const;
GetBucketInventoryConfigurationOutcome GetBucketInventoryConfiguration(const GetBucketInventoryConfigurationRequest& request) const;
#endif
/*Object*/
ListObjectOutcome ListObjects(const ListObjectsRequest &request) const;
ListObjectVersionsOutcome ListObjectVersions(const ListObjectVersionsRequest &request) const;
GetObjectOutcome GetObject(const GetObjectRequest &request) const;
PutObjectOutcome PutObject(const PutObjectRequest &request) const;
DeleteObjectOutcome DeleteObject(const DeleteObjectRequest &request) const;
DeleteObjecstOutcome DeleteObjects(const DeleteObjectsRequest &request) const;
DeleteObjecVersionstOutcome DeleteObjectVersions(const DeleteObjectVersionsRequest& request) const;
ObjectMetaDataOutcome HeadObject(const HeadObjectRequest &request) const;
ObjectMetaDataOutcome GetObjectMeta(const GetObjectMetaRequest &request) const;
GetObjectAclOutcome GetObjectAcl(const GetObjectAclRequest &request) const;
AppendObjectOutcome AppendObject(const AppendObjectRequest &request) const;
CopyObjectOutcome CopyObject(const CopyObjectRequest &request) const;
GetSymlinkOutcome GetSymlink(const GetSymlinkRequest &request) const;
RestoreObjectOutcome RestoreObject(const RestoreObjectRequest &request) const;
CreateSymlinkOutcome CreateSymlink(const CreateSymlinkRequest &request) const;
SetObjectAclOutcome SetObjectAcl(const SetObjectAclRequest &request) const;
GetObjectOutcome ProcessObject(const ProcessObjectRequest &request) const;
GetObjectOutcome SelectObject(const SelectObjectRequest &request) const;
CreateSelectObjectMetaOutcome CreateSelectObjectMeta(const CreateSelectObjectMetaRequest &request) const;
SetObjectTaggingOutcome SetObjectTagging(const SetObjectTaggingRequest& request) const;
DeleteObjectTaggingOutcome DeleteObjectTagging(const DeleteObjectTaggingRequest& request) const;
GetObjectTaggingOutcome GetObjectTagging(const GetObjectTaggingRequest& request) const;
/*MultipartUpload*/
InitiateMultipartUploadOutcome InitiateMultipartUpload(const InitiateMultipartUploadRequest &request) const;
PutObjectOutcome UploadPart(const UploadPartRequest& request) const;
UploadPartCopyOutcome UploadPartCopy(const UploadPartCopyRequest &request) const;
CompleteMultipartUploadOutcome CompleteMultipartUpload(const CompleteMultipartUploadRequest &request) const;
VoidOutcome AbortMultipartUpload(const AbortMultipartUploadRequest &request) const;
ListMultipartUploadsOutcome ListMultipartUploads(const ListMultipartUploadsRequest &request) const;
ListPartsOutcome ListParts(const ListPartsRequest &request) const;
/*Generate URL*/
StringOutcome GeneratePresignedUrl(const GeneratePresignedUrlRequest &request) const;
GetObjectOutcome GetObjectByUrl(const GetObjectByUrlRequest &request) const;
PutObjectOutcome PutObjectByUrl(const PutObjectByUrlRequest &request) const;
/*Generate Post Policy*/
#if (!OSS_DISABLE_RESUAMABLE)
/*Resumable Operation*/
PutObjectOutcome ResumableUploadObject(const UploadObjectRequest& request) const;
CopyObjectOutcome ResumableCopyObject(const MultiCopyObjectRequest& request) const;
GetObjectOutcome ResumableDownloadObject(const DownloadObjectRequest& request) const;
#endif
#if (!OSS_DISABLE_LIVECHANNEL)
/*Live Channel*/
VoidOutcome PutLiveChannelStatus(const PutLiveChannelStatusRequest &request) const;
PutLiveChannelOutcome PutLiveChannel(const PutLiveChannelRequest &request) const;
VoidOutcome PostVodPlaylist(const PostVodPlaylistRequest &request) const;
GetVodPlaylistOutcome GetVodPlaylist(const GetVodPlaylistRequest& request) const;
GetLiveChannelStatOutcome GetLiveChannelStat(const GetLiveChannelStatRequest &request) const;
GetLiveChannelInfoOutcome GetLiveChannelInfo(const GetLiveChannelInfoRequest &request) const;
GetLiveChannelHistoryOutcome GetLiveChannelHistory(const GetLiveChannelHistoryRequest &request) const;
ListLiveChannelOutcome ListLiveChannel(const ListLiveChannelRequest &request) const;
VoidOutcome DeleteLiveChannel(const DeleteLiveChannelRequest &request) const;
StringOutcome GenerateRTMPSignedUrl(const GenerateRTMPSignedUrlRequest &request) const;
#endif
/*Requests control*/
void DisableRequest();
void EnableRequest();
protected:
virtual std::shared_ptr<HttpRequest> buildHttpRequest(const std::string & endpoint, const ServiceRequest &msg, Http::Method method) const;
virtual bool hasResponseError(const std::shared_ptr<HttpResponse>&response) const;
OssOutcome MakeRequest(const OssRequest &request, Http::Method method) const;
private:
void addHeaders(const std::shared_ptr<HttpRequest> &httpRequest, const HeaderCollection &headers) const;
void addBody(const std::shared_ptr<HttpRequest> &httpRequest, const std::shared_ptr<std::iostream>& body, bool contentMd5 = false) const;
void addSignInfo(const std::shared_ptr<HttpRequest> &httpRequest, const ServiceRequest &request) const;
void addUrl(const std::shared_ptr<HttpRequest> &httpRequest, const std::string &endpoint, const ServiceRequest &request) const;
void addOther(const std::shared_ptr<HttpRequest> &httpRequest, const ServiceRequest &request) const;
OssError buildError(const Error &error) const;
ServiceResult buildResult(const OssRequest &request, const std::shared_ptr<HttpResponse> &httpResponse) const;
private:
std::string endpoint_;
std::shared_ptr<CredentialsProvider> credentialsProvider_;
std::shared_ptr<Signer> signer_;
std::shared_ptr<Executor> executor_;
};
}
}
#endif // !ALIBABACLOUD_OSS_OSSCLIENTIMPL_H_
| YifuLiu/AliOS-Things | components/oss/src/OssClientImpl.h | C++ | apache-2.0 | 11,576 |
/*
* 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/oss/OssRequest.h>
#include <alibabacloud/oss/Const.h>
#include <sstream>
#include "http/HttpType.h"
#include "utils/Utils.h"
#include "model/ModelError.h"
#include "utils/FileSystemUtils.h"
using namespace AlibabaCloud::OSS;
OssRequest:: OssRequest():
ServiceRequest(),
bucket_(),
key_()
{
}
OssRequest:: OssRequest(const std::string &bucket, const std::string &key):
ServiceRequest(),
bucket_(bucket),
key_(key)
{
}
HeaderCollection OssRequest::Headers() const
{
auto headers = specialHeaders();
if(headers.size() == 0 || (headers.size() > 0 && headers.count(Http::CONTENT_TYPE) == 0))
{
headers[Http::CONTENT_TYPE] = "application/xml";
}
return headers;
}
ParameterCollection OssRequest::Parameters() const
{
return specialParameters();
}
std::shared_ptr<std::iostream> OssRequest::Body() const
{
std::string&& p = payload();
std::shared_ptr<std::iostream> payloadBody;
if (!p.empty())
{
payloadBody = std::make_shared<std::stringstream>();
*payloadBody << p;
}
return payloadBody;
}
int OssRequest::validate() const
{
return 0;
}
const char * OssRequest::validateMessage(int code) const
{
return GetModelErrorMsg(code);
}
std::string OssRequest::payload() const
{
return "";
}
HeaderCollection OssRequest::specialHeaders() const
{
return HeaderCollection();
}
ParameterCollection OssRequest::specialParameters() const
{
return ParameterCollection();
}
const std::string& OssRequest::bucket() const
{
return bucket_;
}
const std::string& OssRequest::key() const
{
return key_;
}
int OssBucketRequest::validate() const
{
if (!IsValidBucketName(Bucket())) {
return ARG_ERROR_BUCKET_NAME;
}
return 0;
}
void OssBucketRequest::setBucket(const std::string &bucket)
{
bucket_ = bucket;
}
const std::string& OssBucketRequest::Bucket() const
{
return OssRequest::bucket();
}
int OssObjectRequest::validate() const
{
if (!IsValidBucketName(Bucket())) {
return ARG_ERROR_BUCKET_NAME;
}
if (!IsValidObjectKey(Key())) {
return ARG_ERROR_OBJECT_NAME;
}
return 0;
}
void OssObjectRequest::setBucket(const std::string &bucket)
{
bucket_ = bucket;
}
const std::string& OssObjectRequest::Bucket() const
{
return OssRequest::bucket();
}
void OssObjectRequest::setKey(const std::string &key)
{
key_ = key;
}
const std::string& OssObjectRequest::Key() const
{
return OssRequest::key();
}
void OssObjectRequest::setRequestPayer(AlibabaCloud::OSS::RequestPayer key)
{
requestPayer_ = key;
}
AlibabaCloud::OSS::RequestPayer OssObjectRequest::RequestPayer() const
{
return requestPayer_;
}
void OssObjectRequest::setVersionId(const std::string& versionId)
{
versionId_ = versionId;
}
const std::string& OssObjectRequest::VersionId() const
{
return versionId_;
}
HeaderCollection OssObjectRequest::specialHeaders() const
{
auto headers = OssRequest::specialHeaders();
if (requestPayer_ == AlibabaCloud::OSS::RequestPayer::Requester) {
headers["x-oss-request-payer"] = ToLower(ToRequestPayerName(AlibabaCloud::OSS::RequestPayer::Requester));
}
return headers;
}
ParameterCollection OssObjectRequest::specialParameters() const
{
auto parameters = OssRequest::specialParameters();
if (!versionId_.empty()) {
parameters["versionId"] = versionId_;
}
return parameters;
}
int OssResumableBaseRequest::validate() const
{
if (!IsValidBucketName(Bucket())) {
return ARG_ERROR_BUCKET_NAME;
}
if (!IsValidObjectKey(Key())) {
return ARG_ERROR_OBJECT_NAME;
}
if (partSize_ < PartSizeLowerLimit) {
return ARG_ERROR_CHECK_PART_SIZE_LOWER;
}
if (threadNum_ <= 0) {
return ARG_ERROR_CHECK_THREAD_NUM_LOWER;
}
#if !defined(_WIN32)
if (!checkpointDirW_.empty()) {
return ARG_ERROR_PATH_NOT_SUPPORT_WSTRING_TYPE;
}
#endif
// if directory do not exist, return error
if (hasCheckpointDir()) {
if ((!checkpointDir_.empty() && !IsDirectoryExist(checkpointDir_))
#ifdef _WIN32
|| (!checkpointDirW_.empty() && !IsDirectoryExist(checkpointDirW_))
#endif
) {
return ARG_ERROR_CHECK_POINT_DIR_NONEXIST;
}
}
return 0;
}
const char *OssResumableBaseRequest::validateMessage(int code) const
{
return GetModelErrorMsg(code);
}
void OssResumableBaseRequest::setBucket(const std::string &bucket)
{
bucket_ = bucket;
}
const std::string& OssResumableBaseRequest::Bucket() const
{
return OssRequest::bucket();
}
void OssResumableBaseRequest::setKey(const std::string &key)
{
key_ = key;
}
const std::string& OssResumableBaseRequest::Key() const
{
return OssRequest::key();
}
void OssResumableBaseRequest::setPartSize(uint64_t partSize)
{
partSize_ = partSize;
}
uint64_t OssResumableBaseRequest::PartSize() const
{
return partSize_;
}
void OssResumableBaseRequest::setObjectSize(uint64_t objectSize)
{
objectSize_ = objectSize;
}
uint64_t OssResumableBaseRequest::ObjectSize() const
{
return objectSize_;
}
void OssResumableBaseRequest::setThreadNum(uint32_t threadNum)
{
threadNum_ = threadNum;
}
uint32_t OssResumableBaseRequest::ThreadNum() const
{
return threadNum_;
}
void OssResumableBaseRequest::setCheckpointDir(const std::string &checkpointDir)
{
checkpointDir_ = checkpointDir;
checkpointDirW_.clear();
}
const std::string& OssResumableBaseRequest::CheckpointDir() const
{
return checkpointDir_;
}
void OssResumableBaseRequest::setCheckpointDir(const std::wstring& checkpointDir)
{
checkpointDirW_ = checkpointDir;
checkpointDir_.clear();
}
const std::wstring& OssResumableBaseRequest::CheckpointDirW() const
{
return checkpointDirW_;
}
void OssResumableBaseRequest::setObjectMtime(const std::string &mtime)
{
mtime_ = mtime;
}
const std::string& OssResumableBaseRequest::ObjectMtime() const
{
return mtime_;
}
void OssResumableBaseRequest::setRequestPayer(AlibabaCloud::OSS::RequestPayer value)
{
requestPayer_ = value;
}
AlibabaCloud::OSS::RequestPayer OssResumableBaseRequest::RequestPayer() const
{
return requestPayer_;
}
void OssResumableBaseRequest::setTrafficLimit(uint64_t value)
{
trafficLimit_ = value;
}
uint64_t OssResumableBaseRequest::TrafficLimit() const
{
return trafficLimit_;
}
void OssResumableBaseRequest::setVersionId(const std::string& versionId)
{
versionId_ = versionId;
}
const std::string& OssResumableBaseRequest::VersionId() const
{
return versionId_;
}
bool OssResumableBaseRequest::hasCheckpointDir() const
{
return (!checkpointDir_.empty() || !checkpointDirW_.empty());
}
void LiveChannelRequest::setBucket(const std::string &bucket)
{
bucket_ = bucket;
}
const std::string& LiveChannelRequest::Bucket() const
{
return bucket_;
}
void LiveChannelRequest::setChannelName(const std::string &channelName)
{
channelName_ = channelName;
key_ = channelName;
}
const std::string& LiveChannelRequest::ChannelName() const
{
return channelName_;
}
int LiveChannelRequest::validate() const
{
if (!IsValidBucketName(Bucket())) {
return ARG_ERROR_BUCKET_NAME;
}
if(!IsValidChannelName(channelName_))
{
return ARG_ERROR_LIVECHANNEL_BAD_CHANNELNAME_PARAM;
}
return 0;
}
| YifuLiu/AliOS-Things | components/oss/src/OssRequest.cc | C++ | apache-2.0 | 8,057 |
/*
* 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/oss/OssResponse.h>
using namespace AlibabaCloud::OSS;
OssResponse::OssResponse() :
payload_()
{
}
OssResponse::OssResponse(const std::string &payload) :
payload_(payload)
{
}
OssResponse::~OssResponse()
{
}
std::string OssResponse::payload() const
{
return payload_;
}
| YifuLiu/AliOS-Things | components/oss/src/OssResponse.cc | C++ | apache-2.0 | 920 |
/*
* 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/oss/OssResult.h>
#include <sstream>
using namespace AlibabaCloud::OSS;
OssResult::OssResult() :
parseDone_(false)
{
}
OssResult::OssResult(const HeaderCollection& header):
OssResult()
{
if (header.find("x-oss-request-id") != header.end()) {
requestId_ = header.at("x-oss-request-id");
}
}
OssObjectResult::OssObjectResult() :
OssResult()
{
}
OssObjectResult::OssObjectResult(const HeaderCollection& header) :
OssResult(header)
{
if (header.find("x-oss-version-id") != header.end()) {
versionId_ = header.at("x-oss-version-id");
}
}
| YifuLiu/AliOS-Things | components/oss/src/OssResult.cc | C++ | apache-2.0 | 1,266 |
/*
* 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/oss/ServiceRequest.h>
#include <sstream>
using namespace AlibabaCloud::OSS;
ServiceRequest::ServiceRequest() :
flags_(0),
path_("/"),
responseStreamFactory_([] { return std::make_shared<std::stringstream>(); })
{
transferProgress_.Handler = nullptr;
transferProgress_.UserData = nullptr;
}
std::string ServiceRequest::Path() const
{
return path_;
}
int ServiceRequest::Flags() const
{
return flags_;
}
const IOStreamFactory& ServiceRequest::ResponseStreamFactory() const
{
return responseStreamFactory_;
}
void ServiceRequest::setResponseStreamFactory(const IOStreamFactory& factory)
{
responseStreamFactory_ = factory;
}
const AlibabaCloud::OSS::TransferProgress & ServiceRequest::TransferProgress() const
{
return transferProgress_;
}
void ServiceRequest::setTransferProgress(const AlibabaCloud::OSS::TransferProgress &arg)
{
transferProgress_ = arg;
}
void ServiceRequest::setPath(const std::string & path)
{
path_ = path;
}
void ServiceRequest::setFlags(int flags)
{
flags_ = flags;
}
| YifuLiu/AliOS-Things | components/oss/src/ServiceRequest.cc | C++ | apache-2.0 | 1,715 |
/*
* 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/oss/auth/Credentials.h>
using namespace AlibabaCloud::OSS;
Credentials::Credentials(const std::string &accessKeyId,
const std::string &accessKeySecret,
const std::string &sessionToken) :
accessKeyId_(accessKeyId),
accessKeySecret_(accessKeySecret),
sessionToken_(sessionToken)
{
}
Credentials::~Credentials()
{
}
const std::string& Credentials::AccessKeyId () const
{
return accessKeyId_;
}
const std::string& Credentials::AccessKeySecret () const
{
return accessKeySecret_;
}
const std::string& Credentials::SessionToken () const
{
return sessionToken_;
}
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;
}
| YifuLiu/AliOS-Things | components/oss/src/auth/Credentials.cc | C++ | apache-2.0 | 1,582 |
/*
* 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/oss/auth/CredentialsProvider.h>
using namespace AlibabaCloud::OSS;
CredentialsProvider::~CredentialsProvider()
{
}
| YifuLiu/AliOS-Things | components/oss/src/auth/CredentialsProvider.cc | C++ | apache-2.0 | 768 |
/*
* 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 "HmacSha1Signer.h"
#if 0//def _WIN32
#include <windows.h>
#include <wincrypt.h>
#elif defined(USE_CRYPTO_MBEDTLS)
#include "mbedtls/compat-1.3.h"
#include "mbedtls/sha1.h"
#include "mbedtls/base64.h"
#include "mbedtls/md.h"
#else
#include <openssl/hmac.h>
#ifdef OPENSSL_IS_BORINGSSL
#include <openssl/base64.h>
#endif
#endif
using namespace AlibabaCloud::OSS;
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();
#if 0//def _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;
#elif 0//defined(USE_CRYPTO_MBEDTLS)
unsigned char md[20];
unsigned int mdLen = 20;
size_t olen = 0;
mbedtls_sha1_context sha1_ctx;
mbedtls_sha1_init(&sha1_ctx);
mbedtls_sha1_starts(&sha1_ctx);
mbedtls_sha1_update(&sha1_ctx, reinterpret_cast<const unsigned char*>(secret.c_str()), secret.size());
mbedtls_sha1_update(&sha1_ctx, reinterpret_cast<const unsigned char*>(src.c_str()), src.size());
mbedtls_sha1_finish(&sha1_ctx, md);
mbedtls_sha1_free(&sha1_ctx);
char encodedData[100];
mbedtls_base64_encode((unsigned char*)encodedData, sizeof(encodedData), &olen, md, mdLen);
return encodedData;
#elif defined(USE_CRYPTO_MBEDTLS)
unsigned char md[20];
unsigned int mdLen = 20;
size_t olen = 0;
mbedtls_md_hmac(mbedtls_md_info_from_type(MBEDTLS_MD_SHA1),
reinterpret_cast<const unsigned char*>(secret.c_str()),static_cast<int>(secret.size()),
reinterpret_cast<const unsigned char*>(src.c_str()), src.size(),
(unsigned char *)md);
char encodedData[100];
mbedtls_base64_encode((unsigned char*)encodedData, sizeof(encodedData), &olen, md, mdLen);
return encodedData;
#else
unsigned char md[32];
unsigned int mdLen = 32;
if (HMAC(EVP_sha1(), secret.c_str(), static_cast<int>(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
} | YifuLiu/AliOS-Things | components/oss/src/auth/HmacSha1Signer.cc | C++ | apache-2.0 | 4,491 |
/*
* 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.
*/
#pragma once
#include "Signer.h"
namespace AlibabaCloud
{
namespace OSS
{
class HmacSha1Signer : public Signer
{
public:
HmacSha1Signer();
~HmacSha1Signer();
virtual std::string generate(const std::string &src, const std::string &secret)const override;
};
}
}
| YifuLiu/AliOS-Things | components/oss/src/auth/HmacSha1Signer.h | C++ | apache-2.0 | 942 |
/*
* 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 "Signer.h"
using namespace AlibabaCloud::OSS;
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_;
}
| YifuLiu/AliOS-Things | components/oss/src/auth/Signer.cc | C++ | apache-2.0 | 1,026 |
/*
* 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.
*/
#pragma once
#include <string>
namespace AlibabaCloud
{
namespace OSS
{
class Signer
{
public:
enum Type
{
HmacSha1,
};
virtual ~Signer();
virtual std::string generate(const std::string &src, const std::string &secret)const = 0;
std::string name()const;
Type type() const;
std::string version()const;
protected:
Signer(Type type, const std::string &name, const std::string &version = "1.0");
private:
Type type_;
std::string name_;
std::string version_;
};
}
}
| YifuLiu/AliOS-Things | components/oss/src/auth/Signer.h | C++ | apache-2.0 | 1,226 |
/*
* 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 "SimpleCredentialsProvider.h"
using namespace AlibabaCloud::OSS;
SimpleCredentialsProvider::SimpleCredentialsProvider(const Credentials &credentials):
CredentialsProvider(),
credentials_(credentials)
{
}
SimpleCredentialsProvider::SimpleCredentialsProvider(const std::string & accessKeyId,
const std::string & accessKeySecret,
const std::string &securityToken) :
CredentialsProvider(),
credentials_(accessKeyId, accessKeySecret, securityToken)
{
}
SimpleCredentialsProvider::~SimpleCredentialsProvider()
{
}
Credentials SimpleCredentialsProvider::getCredentials()
{
return credentials_;
}
| YifuLiu/AliOS-Things | components/oss/src/auth/SimpleCredentialsProvider.cc | C++ | apache-2.0 | 1,260 |
/*
* 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.
*/
#pragma once
#include <alibabacloud/oss/auth/CredentialsProvider.h>
namespace AlibabaCloud
{
namespace OSS
{
class ALIBABACLOUD_OSS_EXPORT SimpleCredentialsProvider : public CredentialsProvider
{
public:
SimpleCredentialsProvider(const Credentials &credentials);
SimpleCredentialsProvider(const std::string &accessKeyId,
const std::string &accessKeySecret, const std::string &securityToken = "");
~SimpleCredentialsProvider();
virtual Credentials getCredentials() override;
private:
Credentials credentials_;
};
}
}
| YifuLiu/AliOS-Things | components/oss/src/auth/SimpleCredentialsProvider.h | C++ | apache-2.0 | 1,220 |
/*
* 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/oss/client/AsyncCallerContext.h>
#include "utils/Utils.h"
using namespace AlibabaCloud::OSS;
AsyncCallerContext::AsyncCallerContext() :
uuid_(GenerateUuid())
{
}
AsyncCallerContext::AsyncCallerContext(const std::string &uuid) :
uuid_(uuid)
{
}
AsyncCallerContext::~AsyncCallerContext()
{
}
const std::string &AsyncCallerContext::Uuid()const
{
return uuid_;
}
void AsyncCallerContext::setUuid(const std::string &uuid)
{
uuid_ = uuid;
}
| YifuLiu/AliOS-Things | components/oss/src/client/AsyncCallerContext.cc | C++ | apache-2.0 | 1,108 |
/*
* 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/oss/client/RetryStrategy.h>
#include <alibabacloud/oss/utils/Executor.h>
#include <external/tinyxml2/tinyxml2.h>
#include "Client.h"
#include "../http/CurlHttpClient.h"
#include "utils/Utils.h"
#include "../auth/Signer.h"
#include <sstream>
#include <ctime>
#if USE_AOS_TIME_POSIX_API
#if ESP_PLATFORM
#include <sys/time.h>
#else
#include <posix/timer.h>
#endif
#endif
using namespace AlibabaCloud::OSS;
using namespace tinyxml2;
Client::Client(const std::string & servicename, const ClientConfiguration &configuration) :
requestDateOffset_(0),
serviceName_(servicename),
configuration_(configuration),
httpClient_(configuration.httpClient? configuration.httpClient:std::make_shared<CurlHttpClient>(configuration))
{
}
Client::~Client()
{
}
const ClientConfiguration& Client::configuration()const
{
return configuration_;
}
std::string Client::serviceName()const
{
return serviceName_;
}
Client::ClientOutcome Client::AttemptRequest(const std::string & endpoint, const ServiceRequest & request, Http::Method method) const
{
for (int retry =0; ;retry++) {
auto outcome = AttemptOnceRequest(endpoint, request, method);
if (outcome.isSuccess()) {
return outcome;
}
else if (!httpClient_->isEnable()) {
return outcome;
}
else {
if (configuration_.enableDateSkewAdjustment &&
outcome.error().Status() == 403 &&
outcome.error().Message().find("RequestTimeTooSkewed")) {
auto serverTimeStr = analyzeServerTime(outcome.error().Message());
auto serverTime = UtcToUnixTime(serverTimeStr);
if (serverTime != -1) {
#if USE_AOS_TIME_POSIX_API
struct timespec currentTime;
time_t localTime;
clock_gettime(CLOCK_REALTIME, ¤tTime);
localTime = currentTime.tv_nsec/1000000000 + currentTime.tv_sec;
#else
std::time_t localTime = std::time(nullptr);
#endif
setRequestDateOffset(serverTime - localTime);
}
}
RetryStrategy *retryStrategy = configuration().retryStrategy.get();
if (retryStrategy == nullptr || !retryStrategy->shouldRetry(outcome.error(), retry)) {
return outcome;
}
long sleepTmeMs = retryStrategy->calcDelayTimeMs(outcome.error(), retry);
httpClient_->waitForRetry(sleepTmeMs);
}
}
}
Client::ClientOutcome Client::AttemptOnceRequest(const std::string & endpoint, const ServiceRequest & request, Http::Method method) const
{
if (!httpClient_->isEnable()) {
return ClientOutcome(Error("ClientError:100002", "Disable all requests by upper."));
}
auto r = buildHttpRequest(endpoint, request, method);
auto response = httpClient_->makeRequest(r);
if(hasResponseError(response)) {
return ClientOutcome(buildError(response));
} else {
return ClientOutcome(response);
}
}
std::string Client::analyzeServerTime(const std::string &message) const
{
XMLDocument doc;
if (doc.Parse(message.c_str(), message.size()) == XML_SUCCESS) {
XMLElement* root = doc.RootElement();
if (root && !std::strncmp("Error", root->Name(), 5)) {
XMLElement *node;
node = root->FirstChildElement("ServerTime");
return (node ? node->GetText() : "");
}
}
return "";
}
Error Client::buildError(const std::shared_ptr<HttpResponse> &response) const
{
Error error;
if (response == nullptr) {
error.setCode("NullptrError");
error.setMessage("HttpResponse is nullptr, should not be here.");
return error;
}
long responseCode = response->statusCode();
error.setStatus(responseCode);
std::stringstream ss;
if ((responseCode == 203) ||
(responseCode > 299 && responseCode < 600)) {
ss << "ServerError:" << responseCode;
error.setCode(ss.str());
if (response->Body() != nullptr) {
std::istreambuf_iterator<char> isb(*response->Body().get()), end;
error.setMessage(std::string(isb, end));
}
} else {
ss << "ClientError:" << responseCode;
error.setCode(ss.str());
error.setMessage(response->statusMsg());
}
error.setHeaders(response->Headers());
return error;
}
bool Client::hasResponseError(const std::shared_ptr<HttpResponse>&response)const
{
if (!response) {
return true;
}
return (response->statusCode()/100 != 2);
}
void Client::disableRequest()
{
httpClient_->disable();
}
void Client::enableRequest()
{
httpClient_->enable();
}
bool Client::isEnableRequest() const
{
return httpClient_->isEnable();
}
void Client::setRequestDateOffset(uint64_t offset) const
{
requestDateOffset_ = offset;
}
uint64_t Client::getRequestDateOffset() const
{
return requestDateOffset_;
} | YifuLiu/AliOS-Things | components/oss/src/client/Client.cc | C++ | apache-2.0 | 5,663 |
/*
* 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.
*/
#pragma once
#include <functional>
#include <memory>
#include <alibabacloud/oss/ServiceRequest.h>
#include <alibabacloud/oss/ServiceResult.h>
#include <alibabacloud/oss/client/ClientConfiguration.h>
#include <alibabacloud/oss/client/Error.h>
#include <alibabacloud/oss/utils/Outcome.h>
#include <alibabacloud/oss/http/HttpClient.h>
namespace AlibabaCloud
{
namespace OSS
{
class Client
{
public:
using ClientOutcome = Outcome<Error, std::shared_ptr<HttpResponse>> ;
Client(const std::string & servicename, const ClientConfiguration &configuration);
virtual ~Client();
std::string serviceName()const;
const ClientConfiguration &configuration()const;
bool isEnableRequest() const;
protected:
ClientOutcome AttemptRequest(const std::string & endpoint, const ServiceRequest &request, Http::Method method) const;
ClientOutcome AttemptOnceRequest(const std::string & endpoint, const ServiceRequest &request, Http::Method method) const;
virtual std::shared_ptr<HttpRequest> buildHttpRequest(const std::string & endpoint, const ServiceRequest &msg, Http::Method method) const = 0;
virtual bool hasResponseError(const std::shared_ptr<HttpResponse>&response) const;
void setRequestDateOffset(uint64_t offset) const;
uint64_t getRequestDateOffset() const;
void disableRequest();
void enableRequest();
private:
Error buildError(const std::shared_ptr<HttpResponse> &response) const ;
std::string analyzeServerTime(const std::string &message) const;
mutable uint64_t requestDateOffset_;
std::string serviceName_;
ClientConfiguration configuration_;
std::shared_ptr<HttpClient> httpClient_;
};
}
}
| YifuLiu/AliOS-Things | components/oss/src/client/Client.h | C++ | apache-2.0 | 2,482 |
/*
* 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/oss/Config.h>
#include <alibabacloud/oss/client/ClientConfiguration.h>
#include <alibabacloud/oss/client/RetryStrategy.h>
#include <sstream>
#include "utils/Utils.h"
using namespace AlibabaCloud::OSS;
//default for configuration begin
#if defined(PLATFORM_WINDOWS)
static const char* PLATFORM_NAME = "Windows";
#elif defined(PLATFORM_LINUX)
static const char* PLATFORM_NAME = "Linux";
#elif defined(PLATFORM_APPLE)
static const char* PLATFORM_NAME = "MacOS";
#elif defined(PLATFORM_ANDROID)
static const char* PLATFORM_NAME = "Android";
#else
static const char* PLATFORM_NAME = "Unknown";
#endif
static std::string DefaultUserAgent()
{
std::stringstream ss;
ss << "aliyun-sdk-cpp/" << ALIBABACLOUD_OSS_VERSION_STR << " (" << PLATFORM_NAME << ")";
return ss.str();
}
class DefaultRetryStrategy : public RetryStrategy
{
public:
DefaultRetryStrategy(long maxRetries = 3, long scaleFactor = 300) :
m_scaleFactor(scaleFactor), m_maxRetries(maxRetries)
{}
bool shouldRetry(const Error & error, long attemptedRetries) const;
long calcDelayTimeMs(const Error & error, long attemptedRetries) const;
private:
long m_scaleFactor;
long m_maxRetries;
};
bool DefaultRetryStrategy::shouldRetry(const Error & error, long attemptedRetries) const
{
if (attemptedRetries >= m_maxRetries)
return false;
long responseCode = error.Status();
//http code
if ((responseCode == 403 && error.Message().find("RequestTimeTooSkewed") != std::string::npos) ||
(responseCode > 499 && responseCode < 599)) {
return true;
}
else {
switch (responseCode)
{
//curl error code
case (ERROR_CURL_BASE + 7): //CURLE_COULDNT_CONNECT
case (ERROR_CURL_BASE + 18): //CURLE_PARTIAL_FILE
case (ERROR_CURL_BASE + 23): //CURLE_WRITE_ERROR
case (ERROR_CURL_BASE + 28): //CURLE_OPERATION_TIMEDOUT
case (ERROR_CURL_BASE + 52): //CURLE_GOT_NOTHING
case (ERROR_CURL_BASE + 55): //CURLE_SEND_ERROR
case (ERROR_CURL_BASE + 56): //CURLE_RECV_ERROR
return true;
default:
break;
};
}
return false;
}
long DefaultRetryStrategy::calcDelayTimeMs(const Error & error, long attemptedRetries) const
{
UNUSED_PARAM(error);
return (1 << attemptedRetries) * m_scaleFactor;
}
//default for configuration end
ClientConfiguration::ClientConfiguration() :
userAgent(DefaultUserAgent()),
scheme(Http::Scheme::HTTP),
maxConnections(16),
requestTimeoutMs(10000),
connectTimeoutMs(5000),
retryStrategy(std::make_shared<DefaultRetryStrategy>()),
proxyScheme(Http::Scheme::HTTP),
proxyPort(0),
verifySSL(false),
isCname(false),
enableCrc64(true),
enableDateSkewAdjustment(true),
sendRateLimiter(nullptr),
recvRateLimiter(nullptr),
executor(nullptr),
httpClient(nullptr)
{
}
| YifuLiu/AliOS-Things | components/oss/src/client/ClientConfiguration.cc | C++ | apache-2.0 | 3,683 |
/*
* 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 "CipherOpenssl.h"
#include <openssl/rand.h>
using namespace AlibabaCloud::OSS;
inline static std::string toAlgorithmName(CipherAlgorithm algo)
{
static const char* name[] = { "AES", "RSA"};
return name[static_cast<int>(algo) - static_cast<int>(CipherAlgorithm::AES)];
}
inline static std::string toModeName(CipherMode mode)
{
static const char* name[] = { "NONE", "ECB", "CBC", "CTR"};
return name[static_cast<int>(mode) - static_cast<int>(CipherMode::NONE)];
}
inline static std::string toPaddingName(CipherPadding pad)
{
static const char* name[] = { "NoPadding", "PKCS1Padding", "PKCS5Padding", "PKCS7Padding", "ZeroPadding"};
return name[static_cast<int>(pad) - static_cast<int>(CipherPadding::NoPadding)];
}
SymmetricCipher::SymmetricCipher(const std::string& impl, CipherAlgorithm algo, CipherMode mode, CipherPadding pad):
impl_(impl),
algorithm_(algo),
mode_(mode),
padding_(pad),
blockSize_(16)
{
name_ = toAlgorithmName(algo);
name_.append("/");
name_.append(toModeName(mode));
name_.append("/");
name_.append(toPaddingName(pad));
}
ByteBuffer SymmetricCipher::GenerateIV(size_t length)
{
//use openssl rand func
ByteBuffer out = ByteBuffer(length);
RAND_bytes((unsigned char *)out.data(), length);
return out;
}
ByteBuffer SymmetricCipher::GenerateKey(size_t length)
{
//use openssl rand func
ByteBuffer out = ByteBuffer(length);
RAND_bytes((unsigned char *)out.data(), length);
return out;
}
template<class T>
typename std::enable_if<std::is_unsigned<T>::value, T>::type
bswap(T i, T j = 0u, std::size_t n = 0u)
{
return n == sizeof(T) ? j :
bswap<T>(i >> CHAR_BIT, (j << CHAR_BIT) | (i & (T)(unsigned char)(-1)), n + 1);
}
ByteBuffer SymmetricCipher::IncCTRCounter(const ByteBuffer& counter, uint64_t numberOfBlocks)
{
ByteBuffer ctrCounter(counter);
uint64_t *ctrPtr = (uint64_t*)(ctrCounter.data() + ctrCounter.size() - sizeof(uint64_t));
uint64_t n = 1;
if (*(char *)&n) {
//little
*ctrPtr = bswap<uint64_t>(bswap<uint64_t>(*ctrPtr) + numberOfBlocks);
}
else {
//big
*ctrPtr += numberOfBlocks;
}
return ctrCounter;
}
std::shared_ptr<SymmetricCipher> SymmetricCipher::CreateAES128_CTRImpl()
{
return std::make_shared<SymmetricCipherOpenssl>(EVP_aes_128_ctr(),
CipherAlgorithm::AES, CipherMode::CTR, CipherPadding::NoPadding);
}
std::shared_ptr<SymmetricCipher> SymmetricCipher::CreateAES128_CBCImpl()
{
return std::make_shared<SymmetricCipherOpenssl>(EVP_aes_128_cbc(),
CipherAlgorithm::AES, CipherMode::CBC, CipherPadding::PKCS5Padding);
}
std::shared_ptr<SymmetricCipher> SymmetricCipher::CreateAES256_CTRImpl()
{
return std::make_shared<SymmetricCipherOpenssl>(EVP_aes_256_ctr(),
CipherAlgorithm::AES, CipherMode::CTR, CipherPadding::NoPadding);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
AsymmetricCipher::AsymmetricCipher(const std::string& impl, CipherAlgorithm algo, CipherMode mode, CipherPadding pad) :
impl_(impl),
algorithm_(algo),
mode_(mode),
padding_(pad)
{
name_ = toAlgorithmName(algo);
name_.append("/");
name_.append(toModeName(mode));
name_.append("/");
name_.append(toPaddingName(pad));
}
std::shared_ptr<AsymmetricCipher> AsymmetricCipher::CreateRSA_NONEImpl()
{
return std::make_shared<AsymmetricCipherOpenssl>(CipherAlgorithm::RSA, CipherMode::NONE, CipherPadding::PKCS1Padding);
}
| YifuLiu/AliOS-Things | components/oss/src/encryption/Cipher.cc | C++ | apache-2.0 | 4,333 |
/*
* 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 "CipherOpenssl.h"
#include <openssl/evp.h>
#include <openssl/rand.h>
#include <openssl/engine.h>
#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <cstring>
using namespace AlibabaCloud::OSS;
SymmetricCipherOpenssl::SymmetricCipherOpenssl(const EVP_CIPHER* cipher, CipherAlgorithm algo, CipherMode mode, CipherPadding pad):
SymmetricCipher("openssl-impl", algo, mode, pad),
encryptCtx_(nullptr),
decryptCtx_(nullptr),
cipher_(cipher)
{
blockSize_ = EVP_CIPHER_block_size(cipher_);
}
SymmetricCipherOpenssl::~SymmetricCipherOpenssl()
{
if (encryptCtx_) {
EVP_CIPHER_CTX_cleanup(encryptCtx_);
EVP_CIPHER_CTX_free(encryptCtx_);
encryptCtx_ = nullptr;
}
if (decryptCtx_) {
EVP_CIPHER_CTX_cleanup(decryptCtx_);
EVP_CIPHER_CTX_free(decryptCtx_);
decryptCtx_ = nullptr;
}
}
void SymmetricCipherOpenssl::EncryptInit(const ByteBuffer& key, const ByteBuffer& iv)
{
if (!encryptCtx_) {
encryptCtx_ = EVP_CIPHER_CTX_new();
}
EVP_EncryptInit_ex(encryptCtx_, cipher_, nullptr, key.data(), iv.data());
}
ByteBuffer SymmetricCipherOpenssl::Encrypt(const ByteBuffer& data)
{
if (data.empty()) {
return ByteBuffer();
}
int outlen = static_cast<int>(data.size() + EVP_MAX_BLOCK_LENGTH);
ByteBuffer out(static_cast<size_t>(outlen));
if (!EVP_EncryptUpdate(encryptCtx_, out.data(), &outlen, data.data(), static_cast<int>(data.size()))) {
return ByteBuffer();
}
out.resize(outlen);
return out;
}
int SymmetricCipherOpenssl::Encrypt(unsigned char* dst, int dstLen, const unsigned char* src, int srcLen)
{
if (!dst || !src) {
return -1;
}
if (!EVP_EncryptUpdate(encryptCtx_, dst, &dstLen, src, srcLen)) {
return -1;
}
return dstLen;
}
ByteBuffer SymmetricCipherOpenssl::EncryptFinish()
{
ByteBuffer out(EVP_MAX_BLOCK_LENGTH);
int outlen = 0;
if (!EVP_EncryptFinal_ex(encryptCtx_, out.data(), &outlen)) {
return ByteBuffer();
}
out.resize(static_cast<size_t>(outlen));
return out;
}
void SymmetricCipherOpenssl::DecryptInit(const ByteBuffer& key, const ByteBuffer& iv)
{
if (!decryptCtx_) {
decryptCtx_ = EVP_CIPHER_CTX_new();
}
EVP_DecryptInit_ex(decryptCtx_, cipher_, nullptr, key.data(), iv.data());
}
ByteBuffer SymmetricCipherOpenssl::Decrypt(const ByteBuffer& data)
{
if (data.empty()) {
return ByteBuffer();
}
int outlen = static_cast<int>(data.size() + EVP_MAX_BLOCK_LENGTH);
ByteBuffer out(static_cast<size_t>(outlen));
if (!EVP_DecryptUpdate(decryptCtx_, out.data(), &outlen, data.data(), static_cast<int>(data.size()))) {
return ByteBuffer();
}
out.resize(outlen);
return out;
}
int SymmetricCipherOpenssl::Decrypt(unsigned char * dst, int dstLen, const unsigned char* src, int srcLen)
{
if (!dst || !src) {
return -1;
}
if (!EVP_DecryptUpdate(decryptCtx_, dst, &dstLen, (const unsigned char *)src, srcLen)) {
return -1;
}
return dstLen;
}
ByteBuffer SymmetricCipherOpenssl::DecryptFinish()
{
ByteBuffer out(EVP_MAX_BLOCK_LENGTH);
int outlen = 0;
if (!EVP_DecryptFinal_ex(decryptCtx_, (unsigned char *)out.data(), &outlen)) {
return ByteBuffer();
}
out.resize(static_cast<size_t>(outlen));
return out;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
AsymmetricCipherOpenssl::AsymmetricCipherOpenssl(CipherAlgorithm algo, CipherMode mode, CipherPadding pad) :
AsymmetricCipher("openssl-impl", algo, mode, pad)
{
}
AsymmetricCipherOpenssl::~AsymmetricCipherOpenssl()
{
}
ByteBuffer AsymmetricCipherOpenssl::Encrypt(const ByteBuffer& data)
{
RSA* rsa = NULL;
BIO* bio = NULL;
EVP_PKEY* pkey = NULL;
ByteBuffer enc;
do {
if (data.empty()) {
break;
}
bio = BIO_new(BIO_s_mem());
BIO_puts(bio, PublicKey().c_str());
if (strncmp("-----BEGIN RSA", PublicKey().c_str(), 14) == 0) {
rsa = PEM_read_bio_RSAPublicKey(bio, &rsa, NULL, NULL);
}
else {
pkey = PEM_read_bio_PUBKEY(bio, &pkey, NULL, NULL);
rsa = pkey? EVP_PKEY_get1_RSA(pkey) : NULL;
}
if (rsa == NULL) {
break;
}
int rsa_len = RSA_size(rsa);
enc.resize(rsa_len, 0);
if (RSA_public_encrypt(data.size(), (unsigned char*)data.data(), (unsigned char*)enc.data(), rsa, RSA_PKCS1_PADDING) < 0) {
enc.resize(0);
}
} while (0);
if (bio) {
BIO_free(bio);
}
if (pkey) {
EVP_PKEY_free(pkey);
}
if (rsa) {
RSA_free(rsa);
}
return enc;
}
ByteBuffer AsymmetricCipherOpenssl::Decrypt(const ByteBuffer& data)
{
RSA* rsa = NULL;
BIO* bio = NULL;
EVP_PKEY* pkey = NULL;
ByteBuffer dec;
do {
if (data.empty()) {
break;
}
bio = BIO_new(BIO_s_mem());
BIO_puts(bio, PrivateKey().c_str());
if (strncmp("-----BEGIN RSA", PublicKey().c_str(), 14) == 0) {
rsa = PEM_read_bio_RSAPrivateKey(bio, &rsa, NULL, NULL);
}
else {
pkey = PEM_read_bio_PrivateKey(bio, &pkey, NULL, NULL);
rsa = pkey ? EVP_PKEY_get1_RSA(pkey) : NULL;
}
if (rsa == NULL) {
break;
}
int rsa_len = RSA_size(rsa);
dec.resize(rsa_len, 0);
auto dec_len = RSA_private_decrypt(rsa_len, (unsigned char*)data.data(), (unsigned char*)dec.data(), rsa, RSA_PKCS1_PADDING);
dec.resize(dec_len < 0 ? 0 : static_cast<size_t>(dec_len));
} while (0);
if (bio) {
BIO_free(bio);
}
if (pkey) {
EVP_PKEY_free(pkey);
}
if (rsa) {
RSA_free(rsa);
}
return dec;
}
| YifuLiu/AliOS-Things | components/oss/src/encryption/CipherOpenssl.cc | C++ | apache-2.0 | 6,827 |
/*
* 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.
*/
#pragma once
#include <alibabacloud/oss/encryption/Cipher.h>
#include <openssl/evp.h>
namespace AlibabaCloud
{
namespace OSS
{
class SymmetricCipherOpenssl : public SymmetricCipher
{
public:
~SymmetricCipherOpenssl();
SymmetricCipherOpenssl(const EVP_CIPHER* cipher, CipherAlgorithm algo, CipherMode mode, CipherPadding pad);
virtual void EncryptInit(const ByteBuffer& key, const ByteBuffer& iv);
virtual ByteBuffer Encrypt(const ByteBuffer& data);
virtual int Encrypt(unsigned char * dst, int dstLen, const unsigned char* src, int srcLen);
virtual ByteBuffer EncryptFinish();
virtual void DecryptInit(const ByteBuffer& key, const ByteBuffer& iv);
virtual ByteBuffer Decrypt(const ByteBuffer& data);
virtual int Decrypt(unsigned char * dst, int dstLen, const unsigned char* src, int srcLen);
virtual ByteBuffer DecryptFinish();
private:
EVP_CIPHER_CTX* encryptCtx_;
EVP_CIPHER_CTX* decryptCtx_;
const EVP_CIPHER* cipher_;
int blockSize_;
};
class AsymmetricCipherOpenssl : public AsymmetricCipher
{
public:
~AsymmetricCipherOpenssl();
AsymmetricCipherOpenssl(CipherAlgorithm algo, CipherMode mode, CipherPadding pad);
virtual ByteBuffer Encrypt(const ByteBuffer& data);
virtual ByteBuffer Decrypt(const ByteBuffer& data);
private:
};
}
}
| YifuLiu/AliOS-Things | components/oss/src/encryption/CipherOpenssl.h | C++ | apache-2.0 | 2,117 |
/*
* 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/oss/encryption/ContentCryptoMaterial.h>
using namespace AlibabaCloud::OSS;
ContentCryptoMaterial::ContentCryptoMaterial()
{
}
ContentCryptoMaterial::~ContentCryptoMaterial()
{
}
| YifuLiu/AliOS-Things | components/oss/src/encryption/ContentCryptoMaterial.cc | C++ | apache-2.0 | 861 |
/*
* 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/oss/encryption/CryptoConfiguration.h>
using namespace AlibabaCloud::OSS;
CryptoConfiguration::CryptoConfiguration():
cryptoMode(CryptoMode::ENCRYPTION_AESCTR),
cryptoStorageMethod(CryptoStorageMethod::METADATA)
{
}
CryptoConfiguration::~CryptoConfiguration()
{
}
| YifuLiu/AliOS-Things | components/oss/src/encryption/CryptoConfiguration.cc | C++ | apache-2.0 | 952 |
/*
* 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/oss/Const.h>
#include "CryptoModule.h"
#include "CryptoStreamBuf.h"
#include "utils/Utils.h"
using namespace AlibabaCloud::OSS;
#define CHECK_FUNC_RET(outcome, func, ret) \
do { \
if (ret != 0) { \
std::string errMsg(#func" fail, return value:"); errMsg.append(std::to_string(ret));\
return outcome(OssError("EncryptionClientError", errMsg)); \
} \
} while (0)
static std::string getUserAgent(const std::string& prefix)
{
std::stringstream ss;
ss << prefix << "/OssEncryptionClient";
return ss.str();
}
std::shared_ptr<CryptoModule> CryptoModule::CreateCryptoModule(const std::shared_ptr<EncryptionMaterials>& encryptionMaterials,
const CryptoConfiguration& cryptoConfig)
{
switch(cryptoConfig.cryptoMode) {
case CryptoMode::ENCRYPTION_AESCTR:
default:
return std::make_shared<CryptoModuleAESCTR>(encryptionMaterials, cryptoConfig);
};
}
CryptoModule::CryptoModule(const std::shared_ptr<EncryptionMaterials>& encryptionMaterials, const CryptoConfiguration& cryptoConfig):
encryptionMaterials_(encryptionMaterials),
cryptoConfig_(cryptoConfig)
{
}
CryptoModule::~CryptoModule()
{
}
PutObjectOutcome CryptoModule::PutObjectSecurely(const std::shared_ptr<OssClientImpl>& client, const PutObjectRequest& request)
{
PutObjectRequest putRequest(request);
ContentCryptoMaterial material;
initEncryptionCipher(material);
generateKeyIV(material);
auto ret = encryptionMaterials_->EncryptCEK(material);
CHECK_FUNC_RET(PutObjectOutcome, EncryptCEK, ret);
addMetaData(material, putRequest.MetaData());
addUserAgent(putRequest.MetaData(), client->configuration().userAgent);
CryptoStreamBuf cryptoStream(*putRequest.Body(), cipher_, material.ContentKey(), material.ContentIV());
return client->PutObject(putRequest);
}
GetObjectOutcome CryptoModule::GetObjectSecurely(const std::shared_ptr<OssClientImpl>& client, const GetObjectRequest& request, const ObjectMetaData& meta)
{
GetObjectRequest getRequest(request);
ContentCryptoMaterial material;
readMetaData(material, meta);
initDecryptionCipher(material);
if (material.CipherName() != cipher_->Name()) {
std::stringstream ss;
ss << "Cipher name is not support, " <<
"expect " << cipher_->Name() << ", "
"got " << material.CipherName() << ".";
return GetObjectOutcome(OssError("EncryptionClientError", ss.str()));
}
auto ret = encryptionMaterials_->DecryptCEK(material);
CHECK_FUNC_RET(GetObjectOutcome, DecryptCEK, ret);
//range
auto iv = material.ContentIV();
auto range = request.Range();
int64_t skipCnt = 0;
int64_t blkSize = static_cast<int64_t>(cipher_->BlockSize());
if (range.first > 0) {
auto blockOfNum = range.first / blkSize;
auto newBegin = blockOfNum * blkSize;
skipCnt = range.first % blkSize;
getRequest.setRange(newBegin, range.second);
iv = cipher_->IncCTRCounter(iv, static_cast<uint64_t>(blockOfNum));
}
//ua
getRequest.setUserAgent(getUserAgent(client->configuration().userAgent));
std::shared_ptr<CryptoStreamBuf> cryptoStream = nullptr;
std::shared_ptr<std::iostream> userContent = nullptr;
getRequest.setResponseStreamFactory([&]() {
auto content = request.ResponseStreamFactory()();
cryptoStream = std::make_shared<CryptoStreamBuf>(*content, cipher_, material.ContentKey(), iv, static_cast<int>(skipCnt));
userContent = content;
return content;
}
);
auto outcome = client->GetObject(getRequest);
if (skipCnt > 0 && outcome.isSuccess()) {
ObjectMetaData ometa = outcome.result().Metadata();
auto len = ometa.ContentLength();
ometa.setContentLength(len - skipCnt);
outcome.result().setMetaData(ometa);
}
cryptoStream = nullptr;
userContent = nullptr;
return outcome;
}
InitiateMultipartUploadOutcome CryptoModule::InitiateMultipartUploadSecurely(const std::shared_ptr<OssClientImpl>& client,
const InitiateMultipartUploadRequest& request, MultipartUploadCryptoContext& ctx)
{
std::string errMsg1;
if (!checkUserParameter(ctx, errMsg1)) {
return InitiateMultipartUploadOutcome(OssError("EncryptionClientError", errMsg1));
}
InitiateMultipartUploadRequest initRequest(request);
ContentCryptoMaterial material;
initEncryptionCipher(material);
generateKeyIV(material);
auto ret = encryptionMaterials_->EncryptCEK(material);
CHECK_FUNC_RET(InitiateMultipartUploadOutcome, EncryptCEK, ret);
addMetaData(material, initRequest.MetaData());
addMetaDataMultipart(ctx, initRequest.MetaData());
addUserAgent(initRequest.MetaData(), client->configuration().userAgent);
auto outcome = client->InitiateMultipartUpload(initRequest);
if (outcome.isSuccess()) {
ctx.setContentMaterial(material);
ctx.setUploadId(outcome.result().UploadId());
}
return outcome;
}
PutObjectOutcome CryptoModule::UploadPartSecurely(const std::shared_ptr<OssClientImpl>& client, const UploadPartRequest& request,
const MultipartUploadCryptoContext& ctx)
{
std::string errMsg;
if (!checkUserParameter(ctx, errMsg)) {
return PutObjectOutcome(OssError("EncryptionClientError", errMsg));
}
//check material
if (ctx.ContentMaterial().ContentKey().empty() ||
ctx.ContentMaterial().ContentIV().empty()) {
return PutObjectOutcome(OssError("EncryptionClientError", "ContentKey/IV in CryptoContext is empty."));
}
UploadPartRequest uRequest(request);
ContentCryptoMaterial material;
initEncryptionCipher(material);
#if 0
ObjectMetaData meta;
addMetaData(ctx.ContentMaterial(), meta);
addMetaDataMultipart(ctx, meta);
uRequest.setMetaData(meta);
#endif
//ua
uRequest.setUserAgent(getUserAgent(client->configuration().userAgent));
auto fileOffset = ctx.PartSize() * static_cast<int64_t>(uRequest.PartNumber() - 1);
auto blockNum = fileOffset / static_cast<int64_t>(cipher_->BlockSize());
auto iv = cipher_->IncCTRCounter(ctx.ContentMaterial().ContentIV(), static_cast<uint64_t>(blockNum));
CryptoStreamBuf cryptoStream(*uRequest.Body(), cipher_, ctx.ContentMaterial().ContentKey(), iv);
return client->UploadPart(uRequest);
}
void CryptoModule::addMetaData(const ContentCryptoMaterial& content, ObjectMetaData& meta)
{
//x-oss-meta-client-side-encryption-key
meta.addUserHeader("client-side-encryption-key",
Base64Encode((const char*)content.EncryptedContentKey().data(), content.EncryptedContentKey().size()));
//x-oss-meta-client-side-encryption-start //iv
meta.addUserHeader("client-side-encryption-start",
Base64Encode((const char*)content.EncryptedContentIV().data(), content.EncryptedContentIV().size()));
//x-oss-meta-client-side-encryption-cek-alg
meta.addUserHeader("client-side-encryption-cek-alg", content.CipherName());
//x-oss-meta-client-side-encryption-wrap-alg
meta.addUserHeader("client-side-encryption-wrap-alg", content.KeyWrapAlgorithm());
//x-oss-meta-client-side-encryption-matdesc,json format
if (!content.Description().empty()) {
std::string jsonStr = MapToJsonString(content.Description());
if (!jsonStr.empty()) {
meta.addUserHeader("client-side-encryption-matdesc", jsonStr);
}
}
//x-oss-meta-client-side-encryption-magic-number-hmac
if (!content.MagicNumber().empty()) {
meta.addUserHeader("client-side-encryption-magic-number-hmac", content.MagicNumber());
}
//x-oss-meta-client-side-encryption-unencrypted-content-md5
if (meta.hasHeader(Http::CONTENT_MD5)) {
meta.addUserHeader("client-side-encryption-unencrypted-content-md5", meta.ContentMd5());
meta.removeHeader(Http::CONTENT_MD5);
}
//x-oss-meta-client-side-encryption-unencrypted-content-length
//ToDo
}
void CryptoModule::addMetaDataMultipart(const MultipartUploadCryptoContext& ctx, ObjectMetaData& meta)
{
if (ctx.DataSize() > 0) {
meta.addUserHeader("client-side-encryption-data-size", std::to_string(ctx.DataSize()));
}
meta.addUserHeader("client-side-encryption-part-size", std::to_string(ctx.PartSize()));
}
void CryptoModule::readMetaData(ContentCryptoMaterial& content, const ObjectMetaData& meta)
{
//x-oss-meta-client-side-encryption-key
if (meta.hasUserHeader("client-side-encryption-key")) {
content.setEncryptedContentKey(Base64Decode(meta.UserMetaData().at("client-side-encryption-key")));
}
//x-oss-meta-client-side-encryption-start //iv
if (meta.hasUserHeader("client-side-encryption-start")) {
content.setEncryptedContentIV(Base64Decode(meta.UserMetaData().at("client-side-encryption-start")));
}
//x-oss-meta-client-side-encryption-cek-alg
if (meta.hasUserHeader("client-side-encryption-cek-alg")) {
content.setCipherName(meta.UserMetaData().at("client-side-encryption-cek-alg"));
}
//x-oss-meta-client-side-encryption-wrap-alg
if (meta.hasUserHeader("client-side-encryption-wrap-alg")) {
content.setKeyWrapAlgorithm(meta.UserMetaData().at("client-side-encryption-wrap-alg"));
}
//x-oss-meta-client-side-encryption-matdesc
if (meta.hasUserHeader("client-side-encryption-matdesc")) {
content.setDescription(JsonStringToMap(meta.UserMetaData().at("client-side-encryption-matdesc")));
}
}
void CryptoModule::addUserAgent(ObjectMetaData& meta, const std::string& prefix)
{
if (!meta.hasHeader(Http::USER_AGENT)) {
meta.addHeader(Http::USER_AGENT, getUserAgent(prefix));
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//CryptoModuleAES265_CTR
CryptoModuleAESCTR::CryptoModuleAESCTR(const std::shared_ptr<EncryptionMaterials>& encryptionMaterials,
const CryptoConfiguration& cryptoConfig):
CryptoModule(encryptionMaterials, cryptoConfig)
{
}
CryptoModuleAESCTR::~CryptoModuleAESCTR()
{
}
void CryptoModuleAESCTR::initEncryptionCipher(ContentCryptoMaterial& content)
{
cipher_ = SymmetricCipher::CreateAES256_CTRImpl();
content.setCipherName(cipher_->Name());
}
void CryptoModuleAESCTR::generateKeyIV(ContentCryptoMaterial& content)
{
content.setContentKey(SymmetricCipher::GenerateKey(32));
auto iv = SymmetricCipher::GenerateIV(16);
iv[8] = iv[9] = iv[10] = iv[11] = 0;
content.setContentIV(iv);
}
void CryptoModuleAESCTR::initDecryptionCipher(ContentCryptoMaterial& content)
{
UNUSED_PARAM(content);
cipher_ = SymmetricCipher::CreateAES256_CTRImpl();
}
bool CryptoModuleAESCTR::checkUserParameter(const MultipartUploadCryptoContext& ctx, std::string& errMsg)
{
if (ctx.PartSize() < PartSizeLowerLimit) {
errMsg = "PartSize should not be less than 102400.";
return false;
}
if (ctx.PartSize() % 16) {
errMsg = "PartSize is not 16 bytes alignment.";
return false;
}
return true;
}
| YifuLiu/AliOS-Things | components/oss/src/encryption/CryptoModule.cc | C++ | apache-2.0 | 11,771 |
/*
* 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.
*/
#pragma once
#include <alibabacloud/oss/encryption/CryptoConfiguration.h>
#include <alibabacloud/oss/encryption/EncryptionMaterials.h>
#include <alibabacloud/oss/encryption/Cipher.h>
#include <alibabacloud/oss/OssFwd.h>
#include <alibabacloud/oss/model/MultipartUploadCryptoContext.h>
#include "../OssClientImpl.h"
namespace AlibabaCloud
{
namespace OSS
{
class CryptoModule
{
public:
virtual ~CryptoModule();
PutObjectOutcome PutObjectSecurely(const std::shared_ptr<OssClientImpl>& client, const PutObjectRequest& request);
GetObjectOutcome GetObjectSecurely(const std::shared_ptr<OssClientImpl>& client, const GetObjectRequest& request, const ObjectMetaData& meta);
InitiateMultipartUploadOutcome InitiateMultipartUploadSecurely(const std::shared_ptr<OssClientImpl>& client,
const InitiateMultipartUploadRequest& request, MultipartUploadCryptoContext& ctx);
PutObjectOutcome UploadPartSecurely(const std::shared_ptr<OssClientImpl>& client, const UploadPartRequest& request,
const MultipartUploadCryptoContext& ctx);
public:
static std::shared_ptr<CryptoModule> CreateCryptoModule(const std::shared_ptr<EncryptionMaterials>& encryptionMaterials,
const CryptoConfiguration& cryptoConfig);
protected:
CryptoModule(const std::shared_ptr<EncryptionMaterials>& encryptionMaterials, const CryptoConfiguration& cryptoConfig);
void addMetaData(const ContentCryptoMaterial& content, ObjectMetaData& meta);
void addMetaDataMultipart(const MultipartUploadCryptoContext& ctx, ObjectMetaData& meta);
void readMetaData(ContentCryptoMaterial& content, const ObjectMetaData& meta);
void addUserAgent(ObjectMetaData& meta, const std::string& prefix);
virtual void initEncryptionCipher(ContentCryptoMaterial& content) = 0;
virtual void generateKeyIV(ContentCryptoMaterial& content) = 0;
virtual void initDecryptionCipher(ContentCryptoMaterial& content) = 0;
virtual bool checkUserParameter(const MultipartUploadCryptoContext& ctx, std::string& errMsg) = 0;
protected:
std::shared_ptr<EncryptionMaterials> encryptionMaterials_;
CryptoConfiguration cryptoConfig_;
std::shared_ptr<SymmetricCipher> cipher_;
};
class CryptoModuleAESCTR :public CryptoModule
{
public:
CryptoModuleAESCTR(const std::shared_ptr<EncryptionMaterials>& encryptionMaterials, const CryptoConfiguration& cryptoConfig);
~CryptoModuleAESCTR();
protected:
virtual void initEncryptionCipher(ContentCryptoMaterial& content);
virtual void generateKeyIV(ContentCryptoMaterial& content);
virtual void initDecryptionCipher(ContentCryptoMaterial& content);
virtual bool checkUserParameter(const MultipartUploadCryptoContext& ctx, std::string& errMsg);
private:
};
}
}
| YifuLiu/AliOS-Things | components/oss/src/encryption/CryptoModule.h | C++ | apache-2.0 | 3,529 |
/*
* 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 "CryptoStreamBuf.h"
#include <algorithm>
#include <cstring>
using namespace AlibabaCloud::OSS;
CryptoStreamBuf::CryptoStreamBuf(std::iostream& stream,
const std::shared_ptr<SymmetricCipher>& cipher,
const ByteBuffer& key, const ByteBuffer& iv,
const int skipCnt) :
StreamBufProxy(stream),
cipher_(cipher),
encBufferCnt_(0),
encBufferOff_(0),
decBufferCnt_(0),
decBufferOff_(0),
key_(key),
iv_(iv),
initEncrypt(false),
initDecrypt(false),
skipCnt_(skipCnt)
{
StartPosForIV_ = StreamBufProxy::seekoff(std::streamoff(0), std::ios_base::cur, std::ios_base::in);
}
CryptoStreamBuf::~CryptoStreamBuf()
{
//flush decBuffer when its size is BLK_SIZE
if (decBufferCnt_ > 0) {
unsigned char block[BLK_SIZE];
auto ret = cipher_->Decrypt(block, static_cast<int>(decBufferCnt_), decBuffer_, static_cast<int>(decBufferCnt_));
decBufferCnt_ = 0;
if (ret < 0) {
return;
}
xsputn_with_skip(reinterpret_cast<char *>(block), ret);
}
}
std::streamsize CryptoStreamBuf::xsgetn(char * _Ptr, std::streamsize _Count)
{
const std::streamsize startCount = _Count;
std::streamsize readCnt;
unsigned char block[BLK_SIZE];
//update iv base the pos
if (!initEncrypt) {
auto currPos = StreamBufProxy::seekoff(std::streamoff(0), std::ios_base::cur, std::ios_base::in);
currPos -= StartPosForIV_;
auto blkOff = currPos / BLK_SIZE;
auto blkIdx = currPos % BLK_SIZE;
auto iv = SymmetricCipher::IncCTRCounter(iv_, blkOff);
cipher_->EncryptInit(key_, iv);
encBufferCnt_ = 0;
encBufferOff_ = 0;
if (blkIdx > 0) {
StreamBufProxy::seekpos(blkOff * BLK_SIZE, std::ios_base::in);
readCnt = StreamBufProxy::xsgetn(reinterpret_cast<char *>(block), BLK_SIZE);
auto ret = cipher_->Encrypt(encBuffer_, static_cast<int>(readCnt), block, static_cast<int>(readCnt));
if (ret < 0) {
return -1;
}
encBufferCnt_ = ret - blkIdx;
encBufferOff_ = blkIdx;
}
initEncrypt = true;
}
//read from inner encBuffer_ first
readCnt = read_from_encrypted_buffer(_Ptr, _Count);
if (readCnt > 0) {
_Count -= readCnt;
_Ptr += readCnt;
}
//read from streambuf by BLK_SIZE
while (_Count > 0) {
readCnt = StreamBufProxy::xsgetn(reinterpret_cast<char *>(block), BLK_SIZE);
if (readCnt <= 0)
break;
if (_Count < readCnt) {
auto ret = cipher_->Encrypt(encBuffer_, static_cast<int>(readCnt), block, static_cast<int>(readCnt));
if (ret < 0) {
return -1;
}
encBufferCnt_ = ret;
encBufferOff_ = 0;
break;
}
else {
auto ret = cipher_->Encrypt(reinterpret_cast<unsigned char *>(_Ptr), static_cast<int>(readCnt), block, static_cast<int>(readCnt));
if (ret < 0) {
return -1;
}
_Count -= ret;
_Ptr += ret;
}
}
//read from inner encBuffer_ again
readCnt = read_from_encrypted_buffer(_Ptr, _Count);
if (readCnt > 0) {
_Count -= readCnt;
_Ptr += readCnt;
}
return startCount - _Count;
}
std::streamsize CryptoStreamBuf::read_from_encrypted_buffer(char * _Ptr, std::streamsize _Count)
{
const std::streamsize startCount = _Count;
if (_Count > 0 && encBufferCnt_ > 0) {
auto cnt = std::min(_Count, encBufferCnt_);
memcpy(_Ptr, encBuffer_ + encBufferOff_, static_cast<size_t>(cnt));
_Ptr += cnt;
_Count -= cnt;
encBufferCnt_ -= cnt;
encBufferOff_ += cnt;
}
return startCount - _Count;
}
std::streampos CryptoStreamBuf::seekoff(off_type _Off, std::ios_base::seekdir _Way, std::ios_base::openmode _Mode)
{
if (_Mode & std::ios_base::in) {
initEncrypt = false;
}
if (_Mode & std::ios_base::out) {
initDecrypt = false;
}
return StreamBufProxy::seekoff(_Off, _Way, _Mode);
}
std::streampos CryptoStreamBuf::seekpos(pos_type _Pos, std::ios_base::openmode _Mode)
{
if (_Mode & std::ios_base::in) {
initEncrypt = false;
}
if (_Mode & std::ios_base::out) {
initDecrypt = false;
}
return StreamBufProxy::seekpos(_Pos, _Mode);
}
std::streamsize CryptoStreamBuf::xsputn(const char *_Ptr, std::streamsize _Count)
{
const std::streamsize startCount = _Count;
unsigned char block[BLK_SIZE * 2];
std::streamsize writeCnt;
//update iv
if (!initDecrypt) {
cipher_->DecryptInit(key_, iv_);
decBufferCnt_ = 0;
decBufferOff_ = 0;
initDecrypt = true;
}
//append to decBuffer first
if (decBufferCnt_ > 0) {
writeCnt = std::min(_Count, (BLK_SIZE - decBufferCnt_));
memcpy(decBuffer_ + decBufferOff_, _Ptr, static_cast<int>(writeCnt));
decBufferOff_ += writeCnt;
decBufferCnt_ += writeCnt;
_Ptr += writeCnt;
_Count -= writeCnt;
}
//flush decBuffer when its size is BLK_SIZE
if (decBufferCnt_ == BLK_SIZE) {
auto ret = cipher_->Decrypt(block, static_cast<int>(BLK_SIZE), decBuffer_, static_cast<int>(BLK_SIZE));
if (ret < 0) {
return -1;
}
decBufferCnt_ = 0;
decBufferOff_ = 0;
writeCnt = xsputn_with_skip(reinterpret_cast<char *>(block), BLK_SIZE);
if (writeCnt != BLK_SIZE) {
//Todo Save decrypted data
return startCount - _Count;
}
}
auto blkOff = _Count / BLK_SIZE;
auto blkIdx = _Count % BLK_SIZE;
//decrypt by BLK_SIZE
for (auto i = std::streamsize(0); i < blkOff; i++) {
auto ret = cipher_->Decrypt(block, static_cast<int>(BLK_SIZE), reinterpret_cast<const unsigned char *>(_Ptr), static_cast<int>(BLK_SIZE));
if (ret < 0) {
return -1;
}
_Ptr += BLK_SIZE;
_Count -= BLK_SIZE;
writeCnt = xsputn_with_skip(reinterpret_cast<char *>(block), BLK_SIZE);
if (writeCnt != BLK_SIZE) {
//Todo Save decrypted data
return startCount - _Count;
}
}
//save to decBuffer and decrypt next time
if (blkIdx > 0) {
memcpy(decBuffer_, _Ptr, static_cast<int>(blkIdx));
_Ptr += blkIdx;
_Count -= blkIdx;
decBufferCnt_ = blkIdx;
decBufferOff_ = blkIdx;
}
return startCount - _Count;
}
std::streamsize CryptoStreamBuf::xsputn_with_skip(const char *_Ptr, std::streamsize _Count)
{
const std::streamsize startCount = _Count;
if (skipCnt_ > 0) {
auto min = std::min(skipCnt_, _Count);
skipCnt_ -= min;
_Count -= min;
_Ptr += min;
}
if (_Count > 0) {
_Count -= StreamBufProxy::xsputn(_Ptr, _Count);
}
return startCount - _Count;
} | YifuLiu/AliOS-Things | components/oss/src/encryption/CryptoStreamBuf.cc | C++ | apache-2.0 | 7,824 |
/*
* 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.
*/
#pragma once
#include <alibabacloud/oss/encryption/Cipher.h>
#include "../utils/StreamBuf.h"
namespace AlibabaCloud
{
namespace OSS
{
class CryptoStreamBuf : public StreamBufProxy
{
public:
static const std::streamsize BLK_SIZE = 16;
CryptoStreamBuf(std::iostream& stream,
const std::shared_ptr<SymmetricCipher>& cipher,
const ByteBuffer& key, const ByteBuffer& iv,
const int skipCnt = 0);
~CryptoStreamBuf();
protected:
std::streamsize xsgetn(char * _Ptr, std::streamsize _Count);
std::streamsize xsputn(const char *_Ptr, std::streamsize _Count);
std::streampos seekoff(off_type _Off, std::ios_base::seekdir _Way, std::ios_base::openmode _Mode = std::ios_base::in | std::ios_base::out);
std::streampos seekpos(pos_type _Pos, std::ios_base::openmode _Mode = std::ios_base::in | std::ios_base::out);
private:
std::streamsize read_from_encrypted_buffer(char * _Ptr, std::streamsize _Count);
std::streamsize xsputn_with_skip(const char *_Ptr, std::streamsize _Count);
std::shared_ptr<SymmetricCipher> cipher_;
unsigned char encBuffer_[BLK_SIZE * 2];
std::streamsize encBufferCnt_;
std::streamsize encBufferOff_;
unsigned char decBuffer_[BLK_SIZE * 2];
std::streamsize decBufferCnt_;
std::streamsize decBufferOff_;
ByteBuffer key_;
ByteBuffer iv_;
bool initEncrypt;
bool initDecrypt;
std::streamsize skipCnt_; // for decrypt, must be less BLK_SIZE
std::streampos StartPosForIV_;
};
}
}
| YifuLiu/AliOS-Things | components/oss/src/encryption/CryptoStreamBuf.h | C++ | apache-2.0 | 2,278 |
/*
* 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/oss/encryption/EncryptionMaterials.h>
#include <alibabacloud/oss/encryption/Cipher.h>
#include <map>
#include <string>
#include "utils/Utils.h"
using namespace AlibabaCloud::OSS;
EncryptionMaterials::~EncryptionMaterials()
{
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
SimpleRSAEncryptionMaterials::SimpleRSAEncryptionMaterials(const std::string& publicKey, const std::string& privateKey):
SimpleRSAEncryptionMaterials(publicKey, privateKey, std::map< std::string, std::string>())
{
}
SimpleRSAEncryptionMaterials::SimpleRSAEncryptionMaterials(const std::string& publicKey, const std::string& privateKey,
const std::map<std::string, std::string>& description):
publicKey_(publicKey),
description_(description)
{
encryptionMaterials_.push_back(RSAEncryptionMaterial(std::pair<std::string, std::string>(publicKey, privateKey), description));
}
SimpleRSAEncryptionMaterials::~SimpleRSAEncryptionMaterials()
{
}
void SimpleRSAEncryptionMaterials::addEncryptionMaterial(const std::string& publicKey, const std::string& privateKey,
const std::map<std::string, std::string>& description)
{
encryptionMaterials_.push_back(RSAEncryptionMaterial(std::pair<std::string, std::string>(publicKey, privateKey), description));
}
int SimpleRSAEncryptionMaterials::EncryptCEK(ContentCryptoMaterial& contentCryptoMaterial)
{
auto cipher = AsymmetricCipher::CreateRSA_NONEImpl();
cipher->setPublicKey(publicKey_);
auto encrptedKey = cipher->Encrypt(contentCryptoMaterial.ContentKey());
auto encrptedKeyIV = cipher->Encrypt(contentCryptoMaterial.ContentIV());
if (encrptedKey.empty() || encrptedKeyIV.empty()) {
return -1;
}
contentCryptoMaterial.setDescription(description_);
contentCryptoMaterial.setKeyWrapAlgorithm(cipher->Name());
contentCryptoMaterial.setEncryptedContentKey(encrptedKey);
contentCryptoMaterial.setEncryptedContentIV(encrptedKeyIV);
return 0;
}
int SimpleRSAEncryptionMaterials::DecryptCEK(ContentCryptoMaterial& contentCryptoMaterial)
{
auto cipher = AsymmetricCipher::CreateRSA_NONEImpl();
auto keyWarpAlgo = ToLower(contentCryptoMaterial.KeyWrapAlgorithm().c_str());
auto cipherName = ToLower(cipher->Name().c_str());
if (keyWarpAlgo != cipherName) {
return -1;
}
int index = findIndexByDescription(contentCryptoMaterial.Description());
if (index < 0) {
return -1;
}
const std::string& privateKey = encryptionMaterials_[index].first.second;
cipher->setPrivateKey(privateKey);
auto key = cipher->Decrypt(contentCryptoMaterial.EncryptedContentKey());
auto iv = cipher->Decrypt(contentCryptoMaterial.EncryptedContentIV());
if (key.empty() || iv.empty()) {
return -1;
}
contentCryptoMaterial.setContentKey(key);
contentCryptoMaterial.setContentIV(iv);
return 0;
}
int SimpleRSAEncryptionMaterials::findIndexByDescription(const std::map<std::string, std::string>& description)
{
bool found = false;
int index = 0;
for (const auto& item : encryptionMaterials_) {
if (item.second == description) {
found = true;
break;
}
index++;
}
return found ? index: -1;
}
| YifuLiu/AliOS-Things | components/oss/src/encryption/EncryptionMaterials.cc | C++ | apache-2.0 | 4,059 |
/*
* 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 <fstream>
#include <alibabacloud/oss/OssEncryptionClient.h>
#include "../auth/SimpleCredentialsProvider.h"
#include "../encryption/CryptoModule.h"
#include "utils/Utils.h"
#include "../utils/FileSystemUtils.h"
#include "../resumable/ResumableDownloader.h"
#include "../resumable/ResumableUploader.h"
using namespace AlibabaCloud::OSS;
///////////////////////////////////////////////////////////////////////////////////////////////////////
namespace AlibabaCloud
{
namespace OSS
{
#if !defined(DISABLE_RESUAMABLE)
static GetObjectRequest ConvertToGetObjectRequest(const DownloadObjectRequest& request)
{
auto gRequest = GetObjectRequest(request.Bucket(), request.Key(), request.ModifiedSinceConstraint(), request.UnmodifiedSinceConstraint(), request.MatchingETagsConstraint(), request.NonmatchingETagsConstraint(), request.ResponseHeaderParameters());
if (request.RangeIsSet()) {
gRequest.setRange(request.RangeStart(), request.RangeEnd());
}
if (request.TransferProgress().Handler) {
gRequest.setTransferProgress(request.TransferProgress());
}
if (request.RequestPayer() == RequestPayer::Requester) {
gRequest.setRequestPayer(request.RequestPayer());
}
if (request.TrafficLimit() != 0) {
gRequest.setTrafficLimit(request.TrafficLimit());
}
if (!request.VersionId().empty()) {
gRequest.setVersionId(request.VersionId());
}
gRequest.setResponseStreamFactory([&]() {return std::make_shared<std::fstream>(request.FilePath(), std::ios_base::out | std::ios_base::in | std::ios_base::trunc | std::ios_base::binary); });
return gRequest;
}
static PutObjectRequest ConvertToPutObjectRequest(const UploadObjectRequest& request)
{
std::shared_ptr<std::iostream> content = std::make_shared<std::fstream>(request.FilePath(), std::ios::in | std::ios::binary);
PutObjectRequest pRequest(request.Bucket(), request.Key(), content, request.MetaData());
if (request.TransferProgress().Handler) {
pRequest.setTransferProgress(request.TransferProgress());
}
if (request.RequestPayer() == RequestPayer::Requester) {
pRequest.setRequestPayer(request.RequestPayer());
}
if (request.TrafficLimit() != 0) {
pRequest.setTrafficLimit(request.TrafficLimit());
}
return pRequest;
}
class EncryptionResumableDownloader : public ResumableDownloader
{
public:
EncryptionResumableDownloader(const DownloadObjectRequest& request, const ObjectMetaData& meta,
const OssEncryptionClient* enClient, const OssClientImpl *client, uint64_t objectSize)
: ResumableDownloader(request, client, objectSize)
, encryptionClient_(enClient)
, metaData_(meta)
{
//16 bytes alignment
partSize_ = (partSize_ >> 4) << 4;
}
protected:
virtual GetObjectOutcome GetObjectWrap(const GetObjectRequest &request) const
{
return encryptionClient_->GetObjectInternal(request, metaData_);
}
private:
const OssEncryptionClient* encryptionClient_;
const ObjectMetaData& metaData_;
};
class EncryptionResumableUploader : public ResumableUploader
{
public:
EncryptionResumableUploader(const UploadObjectRequest& request,
const OssEncryptionClient* enClient, const OssClientImpl *client)
: ResumableUploader(request, client)
, encryptionClient_(enClient)
{
//16 bytes alignment
partSize_ = (partSize_ >> 4) << 4;
}
protected:
virtual void initRecordInfo()
{
ResumableUploader::initRecordInfo();
encryptionCheckData_ = cryptoContext_.ContentMaterial().ContentIV();
}
virtual void buildRecordInfo(const Json::Value& value)
{
ResumableUploader::buildRecordInfo(value);
ContentCryptoMaterial material;
material.setEncryptedContentKey(Base64Decode(value["encryption-key"].asString()));
material.setEncryptedContentIV(Base64Decode(value["encryption-iv"].asString()));
material.setKeyWrapAlgorithm(value["encryption-wrap-alg"].asString());
material.setDescription(JsonStringToMap(value["encryption-matdesc"].asString()));
encryptionClient_->encryptionMaterials_->DecryptCEK(material);
material.setCipherName(value["encryption-cek-alg"].asString());
cryptoContext_.setUploadId(value["uploadID"].asString());
cryptoContext_.setDataSize(value["size"].asInt64());
cryptoContext_.setPartSize(value["partSize"].asInt64());
cryptoContext_.setContentMaterial(material);
encryptionCheckData_ = Base64Decode(value["encryption-check-data"].asString());
}
virtual void dumpRecordInfo(Json::Value& value)
{
ResumableUploader::dumpRecordInfo(value);
const ByteBuffer& buff1 = cryptoContext_.ContentMaterial().EncryptedContentKey();
value["encryption-key"] = Base64Encode((const char*)buff1.data(), buff1.size());
const ByteBuffer& buff2 = cryptoContext_.ContentMaterial().EncryptedContentIV();
value["encryption-iv"] = Base64Encode((const char*)buff2.data(), buff2.size());
value["encryption-cek-alg"] = cryptoContext_.ContentMaterial().CipherName();
value["encryption-wrap-alg"] = cryptoContext_.ContentMaterial().KeyWrapAlgorithm();
value["encryption-matdesc"] = MapToJsonString(cryptoContext_.ContentMaterial().Description());
const ByteBuffer& buff3 = cryptoContext_.ContentMaterial().ContentIV();
value["encryption-check-data"] = Base64Encode((const char*)buff3.data(), buff3.size());
}
virtual int validateRecord()
{
int ret = ResumableUploader::validateRecord();
if (ret != 0) {
return ret;
}
if (cryptoContext_.ContentMaterial().ContentKey().empty()||
cryptoContext_.ContentMaterial().ContentIV().empty() ||
cryptoContext_.ContentMaterial().CipherName().empty()) {
return -2;
}
if (encryptionCheckData_ != cryptoContext_.ContentMaterial().ContentIV()) {
return -2;
}
return 0;
}
virtual InitiateMultipartUploadOutcome InitiateMultipartUploadWrap(const InitiateMultipartUploadRequest &request) const
{
cryptoContext_.setPartSize(static_cast<int64_t>(partSize_));
cryptoContext_.setDataSize(static_cast<int64_t>(objectSize_));
return encryptionClient_->InitiateMultipartUpload(request, cryptoContext_);
}
virtual PutObjectOutcome UploadPartWrap(const UploadPartRequest &request) const
{
return encryptionClient_->UploadPart(request, cryptoContext_);
}
virtual ListPartsOutcome ListPartsWrap(const ListPartsRequest &request) const
{
return encryptionClient_->ListParts(request);
}
virtual CompleteMultipartUploadOutcome CompleteMultipartUploadWrap(const CompleteMultipartUploadRequest &request) const
{
return encryptionClient_->CompleteMultipartUpload(request, cryptoContext_);
}
private:
const OssEncryptionClient* encryptionClient_;
mutable MultipartUploadCryptoContext cryptoContext_;
ByteBuffer encryptionCheckData_;
};
#endif
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
OssEncryptionClient::OssEncryptionClient(const std::string& endpoint, const std::string& accessKeyId, const std::string& accessKeySecret,
const ClientConfiguration& configuration,
const std::shared_ptr<EncryptionMaterials>& encryptionMaterials, const CryptoConfiguration& cryptoConfig):
OssEncryptionClient(endpoint, accessKeyId, accessKeySecret, "", configuration, encryptionMaterials, cryptoConfig)
{
}
OssEncryptionClient::OssEncryptionClient(const std::string& endpoint, const std::string& accessKeyId, const std::string& accessKeySecret, const std::string& securityToken,
const ClientConfiguration& configuration, const std::shared_ptr<EncryptionMaterials>& encryptionMaterials, const CryptoConfiguration& cryptoConfig):
OssClient(endpoint, std::make_shared<SimpleCredentialsProvider>(accessKeyId, accessKeySecret, securityToken), configuration),
encryptionMaterials_(encryptionMaterials),
cryptoConfig_(cryptoConfig)
{
}
OssEncryptionClient::OssEncryptionClient(const std::string &endpoint,
const std::shared_ptr<CredentialsProvider>& credentialsProvider, const ClientConfiguration& configuration,
const std::shared_ptr<EncryptionMaterials>& encryptionMaterials, const CryptoConfiguration& cryptoConfig) :
OssClient(endpoint, credentialsProvider, configuration),
encryptionMaterials_(encryptionMaterials),
cryptoConfig_(cryptoConfig)
{
}
OssEncryptionClient::~OssEncryptionClient()
{
}
GetObjectOutcome OssEncryptionClient::GetObjectInternal(const GetObjectRequest& request, const ObjectMetaData& meta) const
{
if (meta.hasUserHeader("client-side-encryption-key")) {
auto module = CryptoModule::CreateCryptoModule(encryptionMaterials_, cryptoConfig_);
return module->GetObjectSecurely(client_, request, meta);
}
else {
return client_->GetObject(request);
}
}
GetObjectOutcome OssEncryptionClient::GetObject(const GetObjectRequest& request) const
{
const auto& reqeustBase = static_cast<const OssRequest &>(request);
int ret = reqeustBase.validate();
if (ret != 0) {
return GetObjectOutcome(OssError("ValidateError", request.validateMessage(ret)));
}
HeadObjectRequest hRequest(request.Bucket(), request.Key());
if (request.RequestPayer() == RequestPayer::Requester) {
hRequest.setRequestPayer(request.RequestPayer());
}
if (!request.VersionId().empty()) {
hRequest.setVersionId(request.VersionId());
}
auto outcome = client_->HeadObject(hRequest);
if (!outcome.isSuccess()) {
return GetObjectOutcome(outcome.error());
}
return GetObjectInternal(request, outcome.result());
}
GetObjectOutcome OssEncryptionClient::GetObject(const std::string &bucket, const std::string &key, const std::shared_ptr<std::iostream> &content) const
{
GetObjectRequest request(bucket, key);
request.setResponseStreamFactory([=]() { return content; });
return GetObject(request);
}
GetObjectOutcome OssEncryptionClient::GetObject(const std::string &bucket, const std::string &key, const std::string &fileToSave) const
{
GetObjectRequest request(bucket, key);
request.setResponseStreamFactory([=]() {return std::make_shared<std::fstream>(fileToSave, std::ios_base::out | std::ios_base::trunc | std::ios::binary); });
return GetObject(request);
}
PutObjectOutcome OssEncryptionClient::PutObject(const PutObjectRequest& request) const
{
const auto& reqeustBase = static_cast<const OssRequest &>(request);
int ret = reqeustBase.validate();
if (ret != 0) {
return PutObjectOutcome(OssError("ValidateError", request.validateMessage(ret)));
}
auto module = CryptoModule::CreateCryptoModule(encryptionMaterials_, cryptoConfig_);
return module->PutObjectSecurely(client_, request);
}
PutObjectOutcome OssEncryptionClient::PutObject(const std::string &bucket, const std::string &key, const std::shared_ptr<std::iostream> &content) const
{
return PutObject(PutObjectRequest(bucket, key, content));
}
PutObjectOutcome OssEncryptionClient::PutObject(const std::string &bucket, const std::string &key, const std::string &fileToUpload) const
{
std::shared_ptr<std::iostream> content = std::make_shared<std::fstream>(fileToUpload, std::ios::in | std::ios::binary);
return PutObject(PutObjectRequest(bucket, key, content));
}
AppendObjectOutcome OssEncryptionClient::AppendObject(const AppendObjectRequest& request) const
{
UNUSED_PARAM(request);
return AppendObjectOutcome(OssError("EncryptionClientError", "Not Support this operation."));
}
/*MultipartUpload*/
InitiateMultipartUploadOutcome OssEncryptionClient::InitiateMultipartUpload(const InitiateMultipartUploadRequest& request, MultipartUploadCryptoContext& ctx) const
{
auto module = CryptoModule::CreateCryptoModule(encryptionMaterials_, cryptoConfig_);
return module->InitiateMultipartUploadSecurely(client_, request, ctx);
}
PutObjectOutcome OssEncryptionClient::UploadPart(const UploadPartRequest& request, const MultipartUploadCryptoContext& ctx) const
{
const auto& reqeustBase = static_cast<const OssRequest &>(request);
int ret = reqeustBase.validate();
if (ret != 0) {
return PutObjectOutcome(OssError("ValidateError", request.validateMessage(ret)));
}
auto module = CryptoModule::CreateCryptoModule(encryptionMaterials_, cryptoConfig_);
return module->UploadPartSecurely(client_, request, ctx);
}
UploadPartCopyOutcome OssEncryptionClient::UploadPartCopy(const UploadPartCopyRequest& request, const MultipartUploadCryptoContext& ctx) const
{
UNUSED_PARAM(request);
UNUSED_PARAM(ctx);
return UploadPartCopyOutcome(OssError("EncryptionClientError", "Not Support this operation."));
}
CompleteMultipartUploadOutcome OssEncryptionClient::CompleteMultipartUpload(const CompleteMultipartUploadRequest& request, const MultipartUploadCryptoContext& ctx) const
{
UNUSED_PARAM(ctx);
return OssClient::CompleteMultipartUpload(request);
}
#if !defined(DISABLE_RESUAMABLE)
/*Resumable Operation*/
PutObjectOutcome OssEncryptionClient::ResumableUploadObject(const UploadObjectRequest& request) const
{
const auto& reqeustBase = static_cast<const OssResumableBaseRequest &>(request);
int code = reqeustBase.validate();
if (code != 0) {
return PutObjectOutcome(OssError("ValidateError", reqeustBase.validateMessage(code)));
}
if (request.ObjectSize() <= request.PartSize()) {
auto pRequest = ConvertToPutObjectRequest(request);
return PutObject(pRequest);
}
else {
EncryptionResumableUploader uploader(request, this, client_.get());
return uploader.Upload();
}
}
CopyObjectOutcome OssEncryptionClient::ResumableCopyObject(const MultiCopyObjectRequest& request) const
{
UNUSED_PARAM(request);
return CopyObjectOutcome(OssError("EncryptionClientError", "Not Support this operation."));
}
GetObjectOutcome OssEncryptionClient::ResumableDownloadObject(const DownloadObjectRequest& request) const
{
HeadObjectRequest hRequest(request.Bucket(), request.Key());
if (request.RequestPayer() == RequestPayer::Requester) {
hRequest.setRequestPayer(request.RequestPayer());
}
if (!request.VersionId().empty()) {
hRequest.setVersionId(request.VersionId());
}
auto hOutcome = client_->HeadObject(hRequest);
if (!hOutcome.isSuccess()) {
return GetObjectOutcome(hOutcome.error());
}
auto objectSize = static_cast<uint64_t>(hOutcome.result().ContentLength());
if (objectSize <= request.PartSize()) {
auto gRequest = ConvertToGetObjectRequest(request);
auto gOutcome = GetObjectInternal(gRequest, hOutcome.result());
if (gOutcome.isSuccess()) {
gOutcome.result().setContent(nullptr);
}
return gOutcome;
}
else {
const auto& reqeustBase = static_cast<const OssResumableBaseRequest &>(request);
int code = reqeustBase.validate();
if (code != 0) {
return GetObjectOutcome(OssError("ValidateError", reqeustBase.validateMessage(code)));
}
if (hOutcome.result().UserMetaData().find("client-side-encryption-key") != hOutcome.result().UserMetaData().end()) {
EncryptionResumableDownloader downloader(request, hOutcome.result(), this, client_.get(), objectSize);
return downloader.Download();
}
else {
ResumableDownloader downloader(request, client_.get(), objectSize);
return downloader.Download();
}
}
}
#endif
/*Aysnc APIs*/
void OssEncryptionClient::GetObjectAsync(const GetObjectRequest& request, const GetObjectAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, GetObject(request), context);
};
client_->asyncExecute(new Runnable(fn));
}
void OssEncryptionClient::PutObjectAsync(const PutObjectRequest& request, const PutObjectAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, PutObject(request), context);
};
client_->asyncExecute(new Runnable(fn));
}
void OssEncryptionClient::UploadPartAsync(const UploadPartRequest& request, const UploadPartAsyncHandler& handler, const MultipartUploadCryptoContext& cryptoCtx, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, cryptoCtx, context]()
{
handler(this, request, UploadPart(request, cryptoCtx), context);
};
client_->asyncExecute(new Runnable(fn));
}
void OssEncryptionClient::UploadPartCopyAsync(const UploadPartCopyRequest& request, const UploadPartCopyAsyncHandler& handler, const MultipartUploadCryptoContext& cryptoCtx, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, cryptoCtx, context]()
{
handler(this, request, UploadPartCopy(request, cryptoCtx), context);
};
client_->asyncExecute(new Runnable(fn));
}
/*Callable APIs*/
GetObjectOutcomeCallable OssEncryptionClient::GetObjectCallable(const GetObjectRequest& request) const
{
auto task = std::make_shared<std::packaged_task<GetObjectOutcome()>>(
[this, request]()
{
return GetObject(request);
});
client_->asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
PutObjectOutcomeCallable OssEncryptionClient::PutObjectCallable(const PutObjectRequest& request) const
{
auto task = std::make_shared<std::packaged_task<PutObjectOutcome()>>(
[this, request]()
{
return PutObject(request);
});
client_->asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
PutObjectOutcomeCallable OssEncryptionClient::UploadPartCallable(const UploadPartRequest& request, const MultipartUploadCryptoContext& cryptoCtx) const
{
auto task = std::make_shared<std::packaged_task<PutObjectOutcome()>>(
[this, request, cryptoCtx]()
{
return UploadPart(request, cryptoCtx);
});
client_->asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
UploadPartCopyOutcomeCallable OssEncryptionClient::UploadPartCopyCallable(const UploadPartCopyRequest& request, const MultipartUploadCryptoContext& cryptoCtx) const
{
auto task = std::make_shared<std::packaged_task<UploadPartCopyOutcome()>>(
[this, request, cryptoCtx]()
{
return UploadPartCopy(request, cryptoCtx);
});
client_->asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
/*Generate URL*/
GetObjectOutcome OssEncryptionClient::GetObjectByUrl(const GetObjectByUrlRequest& request) const
{
UNUSED_PARAM(request);
return GetObjectOutcome(OssError("EncryptionClientError", "Not Support this operation."));
}
PutObjectOutcome OssEncryptionClient::PutObjectByUrl(const PutObjectByUrlRequest& request) const
{
UNUSED_PARAM(request);
return PutObjectOutcome(OssError("EncryptionClientError", "Not Support this operation."));
} | YifuLiu/AliOS-Things | components/oss/src/encryption/OssEncryptionClient.cc | C++ | apache-2.0 | 20,577 |
/*
* 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 <curl/curl.h>
#include <cassert>
#include <sstream>
#include <vector>
#include <mutex>
#include <condition_variable>
#include <atomic>
#include <algorithm>
#include <utils/Crc64.h>
#include <alibabacloud/oss/client/Error.h>
#include <alibabacloud/oss/client/RateLimiter.h>
#include "../utils/LogUtils.h"
#include "utils/Utils.h"
#ifdef TAG
#undef TAG
#endif
using namespace AlibabaCloud::OSS;
namespace AlibabaCloud
{
namespace OSS
{
const char * TAG = "CurlHttpClient";
////////////////////////////////////////////////////////////////////////////////////////////
template< typename RESOURCE_TYPE>
class ResourceManager_
{
public:
ResourceManager_() : m_shutdown(false) {}
RESOURCE_TYPE Acquire()
{
std::unique_lock<std::mutex> locker(m_queueLock);
while(!m_shutdown.load() && m_resources.size() == 0)
{
m_semaphore.wait(locker, [&](){ return m_shutdown.load() || m_resources.size() > 0; });
}
assert(!m_shutdown.load());
RESOURCE_TYPE resource = m_resources.back();
m_resources.pop_back();
return resource;
}
bool HasResourcesAvailable()
{
std::lock_guard<std::mutex> locker(m_queueLock);
return m_resources.size() > 0 && !m_shutdown.load();
}
void Release(RESOURCE_TYPE resource)
{
std::unique_lock<std::mutex> locker(m_queueLock);
m_resources.push_back(resource);
locker.unlock();
m_semaphore.notify_one();
}
void PutResource(RESOURCE_TYPE resource)
{
m_resources.push_back(resource);
}
std::vector<RESOURCE_TYPE> ShutdownAndWait(size_t resourceCount)
{
std::vector<RESOURCE_TYPE> resources;
std::unique_lock<std::mutex> locker(m_queueLock);
m_shutdown = true;
while (m_resources.size() < resourceCount)
{
m_semaphore.wait(locker, [&]() { return m_resources.size() == resourceCount; });
}
resources = m_resources;
m_resources.clear();
return resources;
}
private:
std::vector<RESOURCE_TYPE> m_resources;
std::mutex m_queueLock;
std::condition_variable m_semaphore;
std::atomic<bool> m_shutdown;
};
class CurlContainer
{
public:
CurlContainer(unsigned maxSize = 16, long requestTimeout = 10000, long connectTimeout = 5000):
maxPoolSize_(maxSize),
requestTimeout_(requestTimeout),
connectTimeout_(connectTimeout),
poolSize_(0)
{
}
~CurlContainer()
{
for (CURL* handle : handleContainer_.ShutdownAndWait(poolSize_)) {
curl_easy_cleanup(handle);
}
}
CURL* Acquire()
{
if(!handleContainer_.HasResourcesAvailable()) {
growPool();
}
CURL* handle = handleContainer_.Acquire();
return handle;
}
void Release(CURL* handle, bool force)
{
if (handle) {
curl_easy_reset(handle);
if (force) {
CURL* newhandle = curl_easy_init();
if (newhandle) {
curl_easy_cleanup(handle);
handle = newhandle;
}
}
setDefaultOptions(handle);
handleContainer_.Release(handle);
}
}
private:
CurlContainer(const CurlContainer&) = delete;
const CurlContainer& operator = (const CurlContainer&) = delete;
CurlContainer(const CurlContainer&&) = delete;
const CurlContainer& operator = (const CurlContainer&&) = delete;
bool growPool()
{
std::lock_guard<std::mutex> locker(containerLock_);
if (poolSize_ < maxPoolSize_) {
unsigned multiplier = poolSize_ > 0 ? poolSize_ : 1;
unsigned amountToAdd = (std::min)(multiplier * 2, maxPoolSize_ - poolSize_);
unsigned actuallyAdded = 0;
for (unsigned i = 0; i < amountToAdd; ++i) {
CURL* curlHandle = curl_easy_init();
if (curlHandle) {
setDefaultOptions(curlHandle);
handleContainer_.Release(curlHandle);
++actuallyAdded;
} else {
break;
}
}
poolSize_ += actuallyAdded;
return actuallyAdded > 0;
}
return false;
}
void setDefaultOptions(CURL* handle)
{
curl_easy_setopt(handle, CURLOPT_NOSIGNAL, 1L);
curl_easy_setopt(handle, CURLOPT_TCP_NODELAY, 1);
curl_easy_setopt(handle, CURLOPT_NETRC, CURL_NETRC_IGNORED);
curl_easy_setopt(handle, CURLOPT_TIMEOUT_MS, 0L);
curl_easy_setopt(handle, CURLOPT_CONNECTTIMEOUT_MS, connectTimeout_);
curl_easy_setopt(handle, CURLOPT_LOW_SPEED_LIMIT, 1L);
curl_easy_setopt(handle, CURLOPT_LOW_SPEED_TIME, requestTimeout_ / 1000);
curl_easy_setopt(handle, CURLOPT_SSL_VERIFYPEER, 0L);
curl_easy_setopt(handle, CURLOPT_SSL_VERIFYHOST, 0L);
}
private:
ResourceManager_<CURL*> handleContainer_;
unsigned maxPoolSize_;
unsigned long requestTimeout_;
unsigned long connectTimeout_;
unsigned poolSize_;
std::mutex containerLock_;
};
/////////////////////////////////////////////////////////////////////////////////////////////
struct TransferState {
CurlHttpClient *owner;
CURL * curl;
HttpRequest *request;
HttpResponse *response;
int64_t transferred;
int64_t total;
bool firstRecvData;
std::iostream::pos_type recvBodyPos;
TransferProgressHandler progress;
void *userData;
bool enableCrc64;
uint64_t sendCrc64Value;
uint64_t recvCrc64Value;
int sendSpeed;
int recvSpeed;
};
static size_t sendBody(char *ptr, size_t size, size_t nmemb, void *userdata)
{
TransferState *state = static_cast<TransferState*>(userdata);
if (state == nullptr ||
state->request == nullptr) {
return 0;
}
std::shared_ptr<std::iostream> &content = state->request->Body();
const size_t wanted = size * nmemb;
size_t got = 0;
if (content != nullptr && wanted > 0) {
size_t read = wanted;
if (state->total > 0) {
int64_t remains = state->total - state->transferred;
if (remains < static_cast<int64_t>(wanted)) {
read = static_cast<size_t>(remains);
}
}
// TODO: ethan
content->read(ptr, read);
got = static_cast<size_t>(content->gcount());
}
state->transferred += got;
if (state->progress) {
state->progress(got, state->transferred, state->total, state->userData);
}
if (state->enableCrc64) {
state->sendCrc64Value = CRC64::CalcCRC(state->sendCrc64Value, (void *)ptr, got);
}
return got;
}
static size_t recvBody(char *ptr, size_t size, size_t nmemb, void *userdata)
{
TransferState *state = static_cast<TransferState*>(userdata);
const size_t wanted = size * nmemb;
if (state == nullptr ||
state->response == nullptr ||
wanted == 0) {
return -1;
}
if (state->firstRecvData) {
long response_code = 0;
curl_easy_getinfo(state->curl, CURLINFO_RESPONSE_CODE, &response_code);
if (response_code / 100 == 2) {
state->response->addBody(state->request->ResponseStreamFactory()());
if (state->response->Body() != nullptr) {
state->recvBodyPos = state->response->Body()->tellp();
}
OSS_LOG(LogLevel::LogDebug, TAG, "request(%p) setResponseBody, recvBodyPos:%lld",
state->request, state->recvBodyPos);
}
else {
state->response->addBody(std::make_shared<std::stringstream>());
}
state->firstRecvData = false;
}
std::shared_ptr<std::iostream> &content = state->response->Body();
if (content == nullptr || content->fail()) {
printf("error!\r\n");
return -2;
}
// TODO: ethan
content->write(ptr, static_cast<std::streamsize>(wanted));
if (content->bad()) {
return -3;
}
state->transferred += wanted;
if (state->progress) {
state->progress(wanted, state->transferred, state->total, state->userData);
}
if (state->enableCrc64) {
state->recvCrc64Value = CRC64::CalcCRC(state->recvCrc64Value, (void *)ptr, wanted);
}
return wanted;
}
static size_t recvHeaders(char *buffer, size_t size, size_t nitems, void *userdata)
{
TransferState *state = static_cast<TransferState*>(userdata);
const size_t length = nitems * size;
std::string line(buffer);
auto pos = line.find(':');
if (pos != line.npos)
{
size_t posEnd = line.rfind('\r');
if (posEnd != line.npos) {
posEnd = posEnd - pos - 2;
}
std::string name = line.substr(0, pos);
std::string value = line.substr(pos + 2, posEnd);
state->response->setHeader(name, value);
}
if (length == 2 && (buffer[0] == 0x0D) && (buffer[1] == 0x0A)) {
if (state->response->hasHeader(Http::CONTENT_LENGTH)) {
double dval;
curl_easy_getinfo(state->curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &dval);
state->total = (int64_t)dval;
}
}
return length;
}
static int debugCallback(void *handle, curl_infotype type, char *data, size_t size, void *userp)
{
UNUSED_PARAM(userp);
switch (type) {
default:
break;
case CURLINFO_TEXT:
OSS_LOG(LogLevel::LogInfo, TAG, "handle(%p)=> Info: %.*s", handle, size, data);
break;
case CURLINFO_HEADER_OUT:
OSS_LOG(LogLevel::LogDebug, TAG, "handle(%p)=> Send header: %.*s", handle, size, data);
break;
case CURLINFO_HEADER_IN:
OSS_LOG(LogLevel::LogDebug, TAG, "handle(%p)=> Recv header: %.*s", handle, size, data);
break;
}
return 0;
}
static int progressCallback(void *userdata, double dltotal, double dlnow, double ultotal, double ulnow)
{
UNUSED_PARAM(dltotal);
UNUSED_PARAM(dlnow);
UNUSED_PARAM(ultotal);
UNUSED_PARAM(ulnow);
TransferState *state = static_cast<TransferState*>(userdata);
if (state == nullptr || state->owner == nullptr) {
return 0;
}
CurlHttpClient *thiz = static_cast<CurlHttpClient *>(state->owner);
//stop by upper caller
if (!thiz->isEnable()) {
return 1;
}
//for speed update
if (thiz->sendRateLimiter_ != nullptr) {
auto rate = thiz->sendRateLimiter_->Rate();
if (rate != state->sendSpeed) {
state->sendSpeed = rate;
auto speed = static_cast<curl_off_t>(rate);
speed = speed * 1024;
curl_easy_setopt(state->curl, CURLOPT_MAX_SEND_SPEED_LARGE, speed);
}
}
if (thiz->recvRateLimiter_ != nullptr) {
auto rate = thiz->recvRateLimiter_->Rate();
if (rate != state->recvSpeed) {
state->recvSpeed = rate;
auto speed = static_cast<curl_off_t>(rate);
speed = speed * 1024;
curl_easy_setopt(state->curl, CURLOPT_MAX_RECV_SPEED_LARGE, speed);
}
}
return 0;
}
}
}
void CurlHttpClient::initGlobalState()
{
curl_global_init(CURL_GLOBAL_ALL);
}
void CurlHttpClient::cleanupGlobalState()
{
curl_global_cleanup();
}
CurlHttpClient::CurlHttpClient(const ClientConfiguration &configuration) :
HttpClient(),
curlContainer_(new CurlContainer(configuration.maxConnections,
configuration.requestTimeoutMs,
configuration.connectTimeoutMs)),
userAgent_(configuration.userAgent),
proxyScheme_(configuration.proxyScheme),
proxyHost_(configuration.proxyHost),
proxyPort_(configuration.proxyPort),
proxyUserName_(configuration.proxyUserName),
proxyPassword_(configuration.proxyPassword),
verifySSL_(configuration.verifySSL),
caPath_(configuration.caPath),
caFile_(configuration.caFile),
networkInterface_(configuration.networkInterface),
sendRateLimiter_(configuration.sendRateLimiter),
recvRateLimiter_(configuration.recvRateLimiter)
{
}
CurlHttpClient::~CurlHttpClient()
{
if (curlContainer_) {
delete curlContainer_;
}
}
std::shared_ptr<HttpResponse> CurlHttpClient::makeRequest(const std::shared_ptr<HttpRequest> &request)
{
OSS_LOG(LogLevel::LogDebug, TAG, "request(%p) enter makeRequest", request.get());
curl_slist *list = nullptr;
auto& headers = request->Headers();
for (const auto &p : headers) {
if (p.second.empty())
continue;
std::string str = p.first;
str.append(": ").append(p.second);
list = curl_slist_append(list, str.c_str());
}
// Disable Expect: 100-continue
list = curl_slist_append(list, "Expect:");
auto response = std::make_shared<HttpResponse>(request);
std::iostream::pos_type requestBodyPos = -1;
if (request->Body() != nullptr) {
requestBodyPos = request->Body()->tellg();
}
CURL * curl = curlContainer_->Acquire();
OSS_LOG(LogLevel::LogDebug, TAG, "request(%p) acquire curl handle:%p", request.get(), curl);
uint64_t initCRC64 = 0;
#ifdef ENABLE_OSS_TEST
if (headers.find("oss-test-crc64") != headers.end()) {
initCRC64 = std::strtoull(headers.at("oss-test-crc64").c_str(), nullptr, 10);
}
#endif
TransferState transferState = {
this,
curl,
request.get(),
response.get(),
0, -1,
true, -1,
request->TransferProgress().Handler,
request->TransferProgress().UserData,
request->hasCheckCrc64(), initCRC64, initCRC64,
0, 0
};
if (request->hasHeader(Http::CONTENT_LENGTH)) {
transferState.total = std::atoll(request->Header(Http::CONTENT_LENGTH).c_str());
}
std::string url = request->url().toString();
// printf("oss url : %s\n", url.c_str());
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
switch (request->method())
{
case Http::Method::Head:
curl_easy_setopt(curl, CURLOPT_NOBODY, 1);
break;
case Http::Method::Put:
curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);
break;
case Http::Method::Post:
curl_easy_setopt(curl, CURLOPT_POST, 1L);
break;
case Http::Method::Delete:
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "DELETE");
break;
case Http::Method::Get:
default:
break;
}
curl_easy_setopt(curl, CURLOPT_USERAGENT,userAgent_.c_str());
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, list);
curl_easy_setopt(curl, CURLOPT_HEADERDATA, &transferState);
curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, recvHeaders);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &transferState);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, recvBody);
curl_easy_setopt(curl, CURLOPT_READDATA, &transferState);
curl_easy_setopt(curl, CURLOPT_READFUNCTION, sendBody);
if (verifySSL_) {
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 2L);
}
if(!caPath_.empty()) {
curl_easy_setopt(curl, CURLOPT_CAPATH, caPath_.c_str());
}
if(!caFile_.empty()){
curl_easy_setopt(curl, CURLOPT_CAINFO, caFile_.c_str());
}
if (!proxyHost_.empty()) {
std::stringstream ss;
ss << Http::SchemeToString(proxyScheme_) << "://" << proxyHost_;
curl_easy_setopt(curl, CURLOPT_PROXY, ss.str().c_str());
curl_easy_setopt(curl, CURLOPT_PROXYPORT, (long) proxyPort_);
curl_easy_setopt(curl, CURLOPT_PROXYUSERNAME, proxyUserName_.c_str());
curl_easy_setopt(curl, CURLOPT_PROXYPASSWORD, proxyPassword_.c_str());
}
if (!networkInterface_.empty()) {
curl_easy_setopt(curl, CURLOPT_INTERFACE, networkInterface_.c_str());
}
//debug
if (GetLogLevelInner() >= LogLevel::LogInfo) {
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, debugCallback);
}
//Error Buffer
char errbuf[CURL_ERROR_SIZE];
curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errbuf);
errbuf[0] = 0;
//progress Callback
curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, progressCallback);
curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, &transferState);
curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0L);
//Send bytes/sec
if (sendRateLimiter_ != nullptr) {
transferState.sendSpeed = sendRateLimiter_->Rate();
auto speed = static_cast<curl_off_t>(transferState.sendSpeed);
speed = speed * 1024;
curl_easy_setopt(curl, CURLOPT_MAX_SEND_SPEED_LARGE, speed);
}
//Recv bytes/sec
if (recvRateLimiter_ != nullptr) {
transferState.recvSpeed = recvRateLimiter_->Rate();
auto speed = static_cast<curl_off_t>(transferState.recvSpeed);
speed = speed * 1024;
curl_easy_setopt(curl, CURLOPT_MAX_RECV_SPEED_LARGE, speed);
}
CURLcode res = curl_easy_perform(curl);
long response_code= 0;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);
if (res == CURLE_OK) {
response->setStatusCode(response_code);
} else {
printf("[%s]response_code: %d\n", __func__, response_code);
response->setStatusCode(res + ERROR_CURL_BASE);
switch (res) {
case 23: //CURLE_WRITE_ERROR
{
std::string msg(curl_easy_strerror(res));
if (response->Body() == nullptr) {
msg.append(". Caused by content is null.");
}
else if (response->Body()->bad()) {
msg.append(". Caused by content is in bad state(Read/writing error on i/o operation).");
}
else if (response->Body()->fail()) {
msg.append(". Caused by content is in fail state(Logical error on i/o operation).");
}
response->setStatusMsg(msg);
}
break;
default:
{
std::string msg(curl_easy_strerror(res));
msg.append(".").append(errbuf);
response->setStatusMsg(msg);
}
break;
};
}
switch (request->method())
{
case Http::Method::Put:
case Http::Method::Post:
request->setCrc64Result(transferState.sendCrc64Value);
break;
default:
request->setCrc64Result(transferState.recvCrc64Value);
break;
}
request->setTransferedBytes(transferState.transferred);
curlContainer_->Release(curl, (res != CURLE_OK));
curl_slist_free_all(list);
auto & body = response->Body();
if (body != nullptr) {
body->flush();
if (res != CURLE_OK && transferState.recvBodyPos != static_cast<std::streampos>(-1)) {
OSS_LOG(LogLevel::LogDebug, TAG, "request(%p) setResponseBody, tellp:%lld, recvBodyPos:%lld",
request.get(), body->tellp(), transferState.recvBodyPos);
body->clear();
body->seekp(transferState.recvBodyPos);
}
}
else {
response->addBody(std::make_shared<std::stringstream>());
}
if (requestBodyPos != static_cast<std::streampos>(-1)) {
request->Body()->clear();
request->Body()->seekg(requestBodyPos);
}
OSS_LOG(LogLevel::LogDebug, TAG, "request(%p) leave makeRequest, CURLcode:%d, ResponseCode:%d",
request.get(), res, response_code);
return response;
}
| YifuLiu/AliOS-Things | components/oss/src/http/CurlHttpClient.cc | C++ | apache-2.0 | 21,685 |
/*
* 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.
*/
#pragma once
#include <alibabacloud/oss/client/ClientConfiguration.h>
#include <alibabacloud/oss/http/HttpClient.h>
namespace AlibabaCloud
{
namespace OSS
{
class CurlContainer;
class RateLimiter;
class CurlHttpClient : public HttpClient
{
public:
CurlHttpClient(const ClientConfiguration &configuration);
~CurlHttpClient();
static void initGlobalState();
static void cleanupGlobalState();
virtual std::shared_ptr<HttpResponse> makeRequest(const std::shared_ptr<HttpRequest> &request) override;
private:
CurlContainer *curlContainer_;
std::string userAgent_;
Http::Scheme proxyScheme_;
std::string proxyHost_;
unsigned int proxyPort_;
std::string proxyUserName_;
std::string proxyPassword_;
bool verifySSL_;
std::string caPath_;
std::string caFile_;
std::string networkInterface_;
public:
std::shared_ptr<RateLimiter> sendRateLimiter_;
std::shared_ptr<RateLimiter> recvRateLimiter_;
};
}
}
| YifuLiu/AliOS-Things | components/oss/src/http/CurlHttpClient.h | C++ | apache-2.0 | 1,757 |
/*
* 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/oss/http/HttpClient.h>
using namespace AlibabaCloud::OSS;
HttpClient::HttpClient():
disable_(false)
{
}
HttpClient::~HttpClient()
{
}
bool HttpClient::isEnable()
{
return disable_.load() == false;
}
void HttpClient::disable()
{
disable_ = true;
requestSignal_.notify_all();
}
void HttpClient::enable()
{
disable_ = false;
}
void HttpClient::waitForRetry(long milliseconds)
{
if (milliseconds == 0)
return;
std::unique_lock<std::mutex> lck(requestLock_);
requestSignal_.wait_for(lck, std::chrono::milliseconds(milliseconds), [this] ()-> bool { return disable_.load() == true; });
}
| YifuLiu/AliOS-Things | components/oss/src/http/HttpClient.cc | C++ | apache-2.0 | 1,335 |
/*
* 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/oss/http/HttpMessage.h>
using namespace AlibabaCloud::OSS;
HttpMessage::HttpMessage() :
headers_(),
body_()
{
}
HttpMessage::HttpMessage(const HttpMessage &other) :
headers_(other.headers_),
body_(other.body_)
{
}
HttpMessage::HttpMessage(HttpMessage &&other)
{
*this = std::move(other);
}
HttpMessage& HttpMessage::operator=(const HttpMessage &other)
{
if (this != &other) {
body_ = other.body_;
headers_ = other.headers_;
}
return *this;
}
HttpMessage& HttpMessage::operator=(HttpMessage &&other)
{
if (this != &other) {
body_ = std::move(other.body_);
headers_ = std::move(other.headers_);
}
return *this;
}
void HttpMessage::addHeader(const std::string & name, const std::string & value)
{
setHeader(name, value);
}
void HttpMessage::setHeader(const std::string & name, const std::string & value)
{
headers_[name] = value;
}
void HttpMessage::removeHeader(const std::string & name)
{
headers_.erase(name);
}
bool HttpMessage::hasHeader(const std::string &name) const
{
return (headers_.find(name) != headers_.end()) ? true : false;
}
std::string HttpMessage::Header(const std::string & name) const
{
auto it = headers_.find(name);
if (it != headers_.end())
return it->second;
else
return std::string();
}
const HeaderCollection &HttpMessage::Headers() const
{
return headers_;
}
HttpMessage::~HttpMessage()
{
}
| YifuLiu/AliOS-Things | components/oss/src/http/HttpMessage.cc | C++ | apache-2.0 | 2,113 |
/*
* 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/oss/http/HttpRequest.h>
using namespace AlibabaCloud::OSS;
std::string Http::MethodToString(Method method)
{
static const char* name[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
"CONNECT", "OPTIONS", "PATCH", "TRACE"};
return name[(method - Http::Method::Get)];
}
std::string Http::SchemeToString(Scheme scheme)
{
static const char* name[] = {"http", "https"};
return name[scheme - Http::Scheme::HTTP];
}
const char* Http::ACCEPT = "Accept";
const char* Http::ACCEPT_CHARSET = "Accept-Charset";
const char* Http::ACCEPT_ENCODING = "Accept-Encoding";
const char* Http::ACCEPT_LANGUAGE = "Accept-Language";
const char* Http::AUTHORIZATION = "Authorization";
const char* Http::CACHE_CONTROL = "Cache-Control";
const char* Http::CONTENT_DISPOSITION = "Content-Disposition";
const char* Http::CONTENT_ENCODING = "Content-Encoding";
const char* Http::CONTENT_LENGTH = "Content-Length";
const char* Http::CONTENT_MD5 = "Content-MD5";
const char* Http::CONTENT_RANGE = "Content-Range";
const char* Http::CONTENT_TYPE = "Content-Type";
const char* Http::DATE = "Date";
const char* Http::EXPECT = "Expect";
const char* Http::EXPIRES = "Expires";
const char* Http::ETAG = "ETag";
const char* Http::LAST_MODIFIED = "Last-Modified";
const char* Http::RANGE = "Range";
const char* Http::USER_AGENT = "User-Agent";
HttpRequest::HttpRequest(Http::Method method) :
HttpMessage(),
method_(method),
url_(),
responseStreamFactory_(nullptr),
hasCheckCrc64_(false),
crc64Result_(0),
transferedBytes_(0)
{
}
HttpRequest::~HttpRequest()
{
}
Http::Method HttpRequest::method() const
{
return method_;
}
void HttpRequest::setMethod(Http::Method method)
{
method_ = method;
}
void HttpRequest::setUrl(const Url &url)
{
url_ = url;
}
Url HttpRequest::url()const
{
return url_;
}
| YifuLiu/AliOS-Things | components/oss/src/http/HttpRequest.cc | C++ | apache-2.0 | 2,572 |
/*
* 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/oss/http/HttpResponse.h>
namespace
{
#define INVALID_STATUS_CODE -1
}
using namespace AlibabaCloud::OSS;
HttpResponse::HttpResponse(const std::shared_ptr<HttpRequest> & request) :
HttpMessage(),
request_(request),
statusCode_(INVALID_STATUS_CODE)
{
}
HttpResponse::~HttpResponse()
{
}
const HttpRequest & HttpResponse::request() const
{
return *request_.get();
}
void HttpResponse::setStatusCode(int code)
{
statusCode_ = code;
}
int HttpResponse::statusCode() const
{
return statusCode_;
}
void HttpResponse::setStatusMsg(std::string &msg)
{
statusMsg_ = msg;
}
void HttpResponse::setStatusMsg(const char *msg)
{
statusMsg_ = msg;
}
std::string HttpResponse::statusMsg() const
{
return statusMsg_;
}
| YifuLiu/AliOS-Things | components/oss/src/http/HttpResponse.cc | C++ | apache-2.0 | 1,467 |
/*
* 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 <algorithm>
#include <sstream>
#include <alibabacloud/oss/http/Url.h>
using namespace AlibabaCloud::OSS;
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_;
}
| YifuLiu/AliOS-Things | components/oss/src/http/Url.cc | C++ | apache-2.0 | 6,559 |
/*
* 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/oss/model/AbortMultipartUploadRequest.h>
#include "utils/Utils.h"
using namespace AlibabaCloud::OSS;
AbortMultipartUploadRequest::AbortMultipartUploadRequest(
const std::string &bucket, const std::string &key, const std::string &uploadId) :
OssObjectRequest(bucket, key),
uploadId_(uploadId)
{
}
ParameterCollection AbortMultipartUploadRequest::specialParameters() const
{
ParameterCollection parameters;
parameters["uploadId"] = uploadId_;
return parameters;
}
| YifuLiu/AliOS-Things | components/oss/src/model/AbortMultipartUploadRequest.cc | C++ | apache-2.0 | 1,141 |
/*
* 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/oss/model/AppendObjectRequest.h>
#include <alibabacloud/oss/http/HttpType.h>
#include "utils/Utils.h"
using namespace AlibabaCloud::OSS;
AppendObjectRequest::AppendObjectRequest(const std::string &bucket, const std::string &key,
const std::shared_ptr<std::iostream>& content):
OssObjectRequest(bucket, key),
position_(0),
content_(content)
{
}
AppendObjectRequest::AppendObjectRequest(const std::string &bucket, const std::string &key,
const std::shared_ptr<std::iostream>& content, const ObjectMetaData &metaData):
OssObjectRequest(bucket, key),
position_(0),
content_(content),
metaData_(metaData)
{
}
void AppendObjectRequest::setPosition(uint64_t position)
{
position_ = position;
}
void AppendObjectRequest::setCacheControl(const std::string& value)
{
metaData_.addHeader(Http::CACHE_CONTROL, value);
}
void AppendObjectRequest::setContentDisposition(const std::string& value)
{
metaData_.addHeader(Http::CONTENT_DISPOSITION, value);
}
void AppendObjectRequest::setContentEncoding(const std::string& value)
{
metaData_.addHeader(Http::CONTENT_ENCODING, value);
}
void AppendObjectRequest::setContentMd5(const std::string& value)
{
metaData_.addHeader(Http::CONTENT_MD5, value);
}
void AppendObjectRequest::setExpires(uint64_t expires)
{
metaData_.addHeader(Http::EXPIRES, std::to_string(expires));
}
void AppendObjectRequest::setExpires(const std::string& value)
{
metaData_.addHeader(Http::EXPIRES, value);
}
void AppendObjectRequest::setAcl(const CannedAccessControlList& acl)
{
metaData_.addHeader("x-oss-object-acl", ToAclName(acl));
}
void AppendObjectRequest::setTagging(const std::string& value)
{
metaData_.addHeader("x-oss-tagging", value);
}
void AppendObjectRequest::setTrafficLimit(uint64_t value)
{
metaData_.addHeader("x-oss-traffic-limit", std::to_string(value));
}
std::shared_ptr<std::iostream> AppendObjectRequest::Body() const
{
return content_;
}
HeaderCollection AppendObjectRequest::specialHeaders() const
{
auto headers = metaData_.toHeaderCollection();
if (headers.find(Http::CONTENT_TYPE) == headers.end()) {
headers[Http::CONTENT_TYPE] = LookupMimeType(Key());
}
auto baseHeaders = OssObjectRequest::specialHeaders();
headers.insert(baseHeaders.begin(), baseHeaders.end());
return headers;
}
ParameterCollection AppendObjectRequest::specialParameters() const
{
ParameterCollection paramters;
paramters["append"] = "";
paramters["position"] = std::to_string(position_);
return paramters;
}
| YifuLiu/AliOS-Things | components/oss/src/model/AppendObjectRequest.cc | C++ | apache-2.0 | 3,221 |
/*
* 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/oss/model/AppendObjectResult.h>
#include "utils/Utils.h"
using namespace AlibabaCloud::OSS;
AppendObjectResult::AppendObjectResult():
OssObjectResult(),
length_(0),
crc64_(0)
{
}
AppendObjectResult::AppendObjectResult(const HeaderCollection& headers):
OssObjectResult(headers),
length_(0),
crc64_(0)
{
if (headers.find("x-oss-next-append-position") == headers.end()) {
parseDone_ = false;
} else {
length_ = std::strtoull(headers.at("x-oss-next-append-position").c_str(), nullptr, 10);
}
if (headers.find("x-oss-hash-crc64ecma") == headers.end()) {
parseDone_ = false;
} else {
crc64_ = std::strtoull(headers.at("x-oss-hash-crc64ecma").c_str(), nullptr, 10);
}
parseDone_ = true;
}
| YifuLiu/AliOS-Things | components/oss/src/model/AppendObjectResult.cc | C++ | apache-2.0 | 1,456 |
/*
* 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/oss/model/Bucket.h>
using namespace AlibabaCloud::OSS;
Bucket::~Bucket()
{
}
| YifuLiu/AliOS-Things | components/oss/src/model/Bucket.cc | C++ | apache-2.0 | 731 |
/*
* 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/oss/model/CompleteMultipartUploadRequest.h>
#include <sstream>
#include "utils/Utils.h"
#include "ModelError.h"
using namespace AlibabaCloud::OSS;
CompleteMultipartUploadRequest::CompleteMultipartUploadRequest(
const std::string &bucket, const std::string &key) :
CompleteMultipartUploadRequest(bucket, key, PartList())
{
}
CompleteMultipartUploadRequest::CompleteMultipartUploadRequest(
const std::string &bucket,
const std::string &key, const PartList &partList) :
CompleteMultipartUploadRequest(bucket, key, partList, "")
{
}
CompleteMultipartUploadRequest::CompleteMultipartUploadRequest(
const std::string &bucket, const std::string &key,
const PartList &partList, const std::string &uploadId):
OssObjectRequest(bucket, key),
partList_(partList),
uploadId_(uploadId),
encodingTypeIsSet_(false)
{
setFlags(Flags() | REQUEST_FLAG_CONTENTMD5);
}
int CompleteMultipartUploadRequest::validate() const
{
int ret = OssObjectRequest::validate();
if (ret != 0) {
return ret;
}
if(partList_.empty())
return ARG_ERROR_MULTIPARTUPLOAD_PARTLIST_EMPTY;
return 0;
}
void CompleteMultipartUploadRequest::setPartList(const PartList &partList)
{
partList_ = partList;
}
void CompleteMultipartUploadRequest::setEncodingType(const std::string &encodingType)
{
encodingType_ = encodingType;
encodingTypeIsSet_ = true;
}
void CompleteMultipartUploadRequest::setUploadId(const std::string &uploadId)
{
uploadId_ = uploadId;
}
void CompleteMultipartUploadRequest::setAcl(CannedAccessControlList acl)
{
metaData_.addHeader("x-oss-object-acl", ToAclName(acl));
}
void CompleteMultipartUploadRequest::setCallback(const std::string& callback, const std::string& callbackVar)
{
metaData_.removeHeader("x-oss-callback");
metaData_.removeHeader("x-oss-callback-var");
if (!callback.empty()) {
metaData_.addHeader("x-oss-callback", callback);
}
if (!callbackVar.empty()) {
metaData_.addHeader("x-oss-callback-var", callbackVar);
}
}
ObjectMetaData& CompleteMultipartUploadRequest::MetaData()
{
return metaData_;
}
ParameterCollection CompleteMultipartUploadRequest::specialParameters()const
{
ParameterCollection parameters;
parameters["uploadId"] = uploadId_;
if(encodingTypeIsSet_)
{
parameters["encoding-type"] = encodingType_;
}
return parameters;
}
HeaderCollection CompleteMultipartUploadRequest::specialHeaders() const
{
auto headers = metaData_.toHeaderCollection();
auto baseHeaders = OssObjectRequest::specialHeaders();
headers.insert(baseHeaders.begin(), baseHeaders.end());
return headers;
}
std::string CompleteMultipartUploadRequest::payload() const
{
std::stringstream ss;
ss << "<CompleteMultipartUpload>" << std::endl;
for (auto const &part : partList_) {
ss << "<Part>" << std::endl;
ss << " <PartNumber>";
ss << std::to_string(part.PartNumber());
ss << "</PartNumber>" << std::endl;
ss << " <ETag>";
ss << part.ETag();
ss << "</ETag>" << std::endl;
ss << "</Part>";
}
ss << "</CompleteMultipartUpload>";
return ss.str();
}
| YifuLiu/AliOS-Things | components/oss/src/model/CompleteMultipartUploadRequest.cc | C++ | apache-2.0 | 4,013 |
/*
* 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/oss/model/CompleteMultipartUploadResult.h>
#include <external/tinyxml2/tinyxml2.h>
#include "utils/Utils.h"
#include <alibabacloud/oss/http/HttpType.h>
using namespace AlibabaCloud::OSS;
using namespace tinyxml2;
CompleteMultipartUploadResult::CompleteMultipartUploadResult() :
OssObjectResult(),
crc64_(0),
content_(nullptr)
{
}
CompleteMultipartUploadResult::CompleteMultipartUploadResult(const std::string& result) :
CompleteMultipartUploadResult()
{
*this = result;
}
CompleteMultipartUploadResult::CompleteMultipartUploadResult(const std::shared_ptr<std::iostream>& result,
const HeaderCollection& headers) :
OssObjectResult(headers),
crc64_(0),
content_(nullptr)
{
std::string contentType;
if (headers.find(Http::CONTENT_TYPE) != headers.end()) {
contentType = ToLower(headers.at(Http::CONTENT_TYPE).c_str());
}
if (contentType.compare("application/json") != 0) {
std::istreambuf_iterator<char> isb(*result.get()), end;
std::string str(isb, end);
*this = str;
}
else {
content_ = result;
parseDone_ = true;
}
if (headers.find("x-oss-hash-crc64ecma") != headers.end()) {
crc64_ = std::strtoull(headers.at("x-oss-hash-crc64ecma").c_str(), nullptr, 10);
}
if (eTag_.empty() && headers.find(Http::ETAG) != headers.end()) {
eTag_ = TrimQuotes(headers.at(Http::ETAG).c_str());
}
}
CompleteMultipartUploadResult& CompleteMultipartUploadResult::operator =(const std::string& result)
{
if (result.empty()) {
parseDone_ = true;
return *this;
}
XMLDocument doc;
XMLError xml_err;
if ((xml_err = doc.Parse(result.c_str(), result.size())) == XML_SUCCESS) {
XMLElement* root = doc.RootElement();
if (root && !std::strncmp("CompleteMultipartUploadResult", root->Name(), 29)) {
XMLElement *node;
node = root->FirstChildElement("EncodingType");
if (node && node->GetText())
{
encodingType_ = node->GetText();
}
bool bEncode = false;
bEncode = !ToLower(encodingType_.c_str()).compare(0, 3, "url", 3);
node = root->FirstChildElement("Bucket");
if (node && node->GetText())
{
bucket_ = node->GetText();
}
node = root->FirstChildElement("Location");
if(node && node->GetText())
{
if (bEncode)
{
location_ = UrlDecode(node->GetText());
}
else {
location_ = node->GetText();
}
}
node = root->FirstChildElement("Key");
if(node && node->GetText())
{
if(bEncode)
{
key_ = UrlDecode(node->GetText());
}else{
key_ = node->GetText();
}
}
node = root->FirstChildElement("ETag");
if(node && node->GetText())
{
eTag_ = node->GetText();
}
parseDone_ = true;
}
}
return *this;
}
const std::string& CompleteMultipartUploadResult::Location() const
{
return location_;
}
const std::string& CompleteMultipartUploadResult::Key() const
{
return key_;
}
const std::string& CompleteMultipartUploadResult::Bucket() const
{
return bucket_;
}
const std::string& CompleteMultipartUploadResult::ETag() const
{
return eTag_;
}
const std::string& CompleteMultipartUploadResult::EncodingType() const
{
return encodingType_;
}
uint64_t CompleteMultipartUploadResult::CRC64() const
{
return crc64_;
}
const std::shared_ptr<std::iostream>& CompleteMultipartUploadResult::Content() const
{
return content_;
}
| YifuLiu/AliOS-Things | components/oss/src/model/CompleteMultipartUploadResult.cc | C++ | apache-2.0 | 4,697 |
/*
* 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/oss/model/CopyObjectRequest.h>
#include <alibabacloud/oss/http/HttpType.h>
#include "utils/Utils.h"
#include <sstream>
using namespace AlibabaCloud::OSS;
CopyObjectRequest::CopyObjectRequest(const std::string &bucket, const std::string &key):
OssObjectRequest(bucket, key),
sourceBucket_(),
sourceKey_()
{
}
CopyObjectRequest::CopyObjectRequest(const std::string &bucket, const std::string &key,
const ObjectMetaData &metaData):
OssObjectRequest(bucket, key),
sourceBucket_(),
sourceKey_(),
metaData_(metaData)
{
}
void CopyObjectRequest::setCopySource(const std::string& srcBucket,const std::string& srcKey)
{
sourceBucket_ = srcBucket;
sourceKey_ = srcKey;
}
void CopyObjectRequest::setSourceIfMatchETag(const std::string& value)
{
metaData_.addHeader("x-oss-copy-source-if-match", value);
}
void CopyObjectRequest::setSourceIfNotMatchETag(const std::string& value)
{
metaData_.addHeader("x-oss-copy-source-if-none-match", value);
}
void CopyObjectRequest::setSourceIfUnModifiedSince(const std::string& value)
{
metaData_.addHeader("x-oss-copy-source-if-unmodified-since", value);
}
void CopyObjectRequest::setSourceIfModifiedSince(const std::string& value)
{
metaData_.addHeader("x-oss-copy-source-if-modified-since", value);
}
void CopyObjectRequest::setMetadataDirective(const CopyActionList& action)
{
metaData_.addHeader("x-oss-metadata-directive", ToCopyActionName(action));
}
void CopyObjectRequest::setAcl(const CannedAccessControlList& acl)
{
metaData_.addHeader("x-oss-object-acl", ToAclName(acl));
}
void CopyObjectRequest::setTagging(const std::string& value)
{
metaData_.addHeader("x-oss-tagging", value);
}
void CopyObjectRequest::setTaggingDirective(const CopyActionList& action)
{
metaData_.addHeader("x-oss-tagging-directive", ToCopyActionName(action));
}
void CopyObjectRequest::setTrafficLimit(uint64_t value)
{
metaData_.addHeader("x-oss-traffic-limit", std::to_string(value));
}
HeaderCollection CopyObjectRequest::specialHeaders() const
{
auto headers = metaData_.toHeaderCollection();
if (headers.find(Http::CONTENT_TYPE) == headers.end()) {
headers[Http::CONTENT_TYPE] = LookupMimeType(Key());
}
std::string source;
source.append("/").append(sourceBucket_).append("/").append(UrlEncode(sourceKey_));
if (!versionId_.empty()) {
source.append("?versionId=").append(versionId_);
}
headers["x-oss-copy-source"] = source;
auto baseHeaders = OssObjectRequest::specialHeaders();
headers.insert(baseHeaders.begin(), baseHeaders.end());
return headers;
}
ParameterCollection CopyObjectRequest::specialParameters() const
{
return ParameterCollection();
}
| YifuLiu/AliOS-Things | components/oss/src/model/CopyObjectRequest.cc | C++ | apache-2.0 | 3,493 |
/*
* 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/oss/model/CopyObjectResult.h>
#include <external/tinyxml2/tinyxml2.h>
#include "utils/Utils.h"
using namespace AlibabaCloud::OSS;
using namespace tinyxml2;
CopyObjectResult::CopyObjectResult() :
OssObjectResult()
{
}
CopyObjectResult::CopyObjectResult(const std::string& data):
CopyObjectResult()
{
*this = data;
}
CopyObjectResult::CopyObjectResult(const std::shared_ptr<std::iostream>& data):
CopyObjectResult()
{
std::istreambuf_iterator<char> isb(*data.get()), end;
std::string str(isb, end);
*this = str;
}
CopyObjectResult::CopyObjectResult(const HeaderCollection& headers, const std::shared_ptr<std::iostream>& data):
OssObjectResult(headers)
{
if (headers.find("x-oss-copy-source-version-id") != headers.end()) {
sourceVersionId_ = headers.at("x-oss-copy-source-version-id");
}
std::istreambuf_iterator<char> isb(*data.get()), end;
std::string str(isb, end);
*this = str;
}
CopyObjectResult& CopyObjectResult::operator =(const std::string& data)
{
XMLDocument doc;
XMLError xml_err;
if ((xml_err = doc.Parse(data.c_str(), data.size())) == XML_SUCCESS) {
XMLElement* root = doc.RootElement();
if (root && !std::strncmp("CopyObjectResult", root->Name(), strlen("CopyObjectResult"))) {
XMLElement *node;
node = root->FirstChildElement("LastModified");
if (node && node->GetText()) {
lastModified_ = node->GetText();
}
node = root->FirstChildElement("ETag");
if (node && node->GetText()) {
etag_ = TrimQuotes(node->GetText());
}
//TODO check the result and the parse flag;
parseDone_ = true;
}
}
return *this;
}
| YifuLiu/AliOS-Things | components/oss/src/model/CopyObjectResult.cc | C++ | apache-2.0 | 2,499 |
/*
* 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/oss/model/CreateBucketRequest.h>
#include <utils/Utils.h>
using namespace AlibabaCloud::OSS;
CreateBucketRequest::CreateBucketRequest(const std::string &bucket, StorageClass storageClass):
CreateBucketRequest(bucket, storageClass, CannedAccessControlList::Default)
{
}
CreateBucketRequest::CreateBucketRequest(const std::string &bucket, StorageClass storageClass, CannedAccessControlList acl):
OssBucketRequest(bucket),
storageClass_(storageClass),
acl_(acl),
dataRedundancyType_(DataRedundancyType::NotSet)
{
}
std::string CreateBucketRequest::payload() const
{
std::string str;
str.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
str.append("<CreateBucketConfiguration>\n");
str.append("<StorageClass>");
str.append(ToStorageClassName(storageClass_));
str.append("</StorageClass>\n");
if (dataRedundancyType_ != DataRedundancyType::NotSet) {
str.append("<DataRedundancyType>");
str.append(ToDataRedundancyTypeName(dataRedundancyType_));
str.append("</DataRedundancyType>\n");
}
str.append("</CreateBucketConfiguration>");
return str;
}
HeaderCollection CreateBucketRequest::specialHeaders() const
{
if (acl_ < CannedAccessControlList::Default) {
HeaderCollection headers;
headers["x-oss-acl"] = ToAclName(acl_);
return headers;
}
return OssRequest::specialHeaders();
}
| YifuLiu/AliOS-Things | components/oss/src/model/CreateBucketRequest.cc | C++ | apache-2.0 | 2,113 |
/*
* 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/oss/model/CreateSelectObjectMetaRequest.h>
#include <sstream>
#include "ModelError.h"
#include "utils/Utils.h"
using namespace AlibabaCloud::OSS;
CreateSelectObjectMetaRequest::CreateSelectObjectMetaRequest(const std::string& bucket, const std::string& key) :
OssObjectRequest(bucket, key),
inputFormat_(nullptr),
overWriteIfExists_(false)
{
setFlags(Flags() | REQUEST_FLAG_CONTENTMD5);
}
void CreateSelectObjectMetaRequest::setOverWriteIfExists(bool overWriteIfExists)
{
overWriteIfExists_ = overWriteIfExists;
}
void CreateSelectObjectMetaRequest::setInputFormat(InputFormat& inputFormat)
{
inputFormat_ = &inputFormat;
}
std::string CreateSelectObjectMetaRequest::payload() const
{
std::stringstream ss;
if (inputFormat_->Type() == "csv") {
ss << "<CsvMetaRequest>" << std::endl;
ss << inputFormat_->toXML(0) << std::endl;
ss << "<OverwriteIfExists>" << (overWriteIfExists_ ? "true" : "false") << "</OverwriteIfExists>" << std::endl;
ss << "</CsvMetaRequest>" << std::endl;
}
else {
ss << "<JsonMetaRequest>" << std::endl;
ss << inputFormat_->toXML(0) << std::endl;
ss << "<OverwriteIfExists>" << (overWriteIfExists_ ? "true" : "false") << "</OverwriteIfExists>" << std::endl;
ss << "</JsonMetaRequest>" << std::endl;
}
return ss.str();
}
int CreateSelectObjectMetaRequest::validate() const
{
int ret = OssObjectRequest::validate();
if (ret != 0) {
return ret;
}
if (inputFormat_ == nullptr) {
return ARG_ERROR_CREATE_SELECT_OBJECT_META_NULL_POINT;
}
return 0;
}
ParameterCollection CreateSelectObjectMetaRequest::specialParameters() const
{
ParameterCollection parameters;
if (inputFormat_) {
auto type = inputFormat_->Type();
type.append("/meta");
parameters["x-oss-process"] = type;
}
return parameters;
}
| YifuLiu/AliOS-Things | components/oss/src/model/CreateSelectObjectMetaRequest.cc | C++ | apache-2.0 | 2,561 |