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.
*/
#include <alibabacloud/oss/model/PutLiveChannelRequest.h>
#include <sstream>
#include "utils/Utils.h"
#include "ModelError.h"
#include "Const.h"
using namespace AlibabaCloud::OSS;
PutLiveChannelRequest::PutLiveChannelRequest(const std::string& bucket,
const std::string& channelName, const std::string& type)
:LiveChannelRequest(bucket, channelName),
channelType_(type),
playListName_("playlist.m3u8"),
status_(LiveChannelStatus::EnabledStatus),
fragDuration_(5),
fragCount_(3),
snapshot_(false)
{
}
void PutLiveChannelRequest::setChannelType(const std::string& channelType)
{
channelType_ = channelType;
}
void PutLiveChannelRequest::setDescripition(const std::string& description)
{
description_ = description;
}
void PutLiveChannelRequest::setDestBucket(const std::string& destBucket)
{
destBucket_ = destBucket;
snapshot_ = true;
}
void PutLiveChannelRequest::setFragCount(uint64_t fragCount)
{
fragCount_ = fragCount;
}
void PutLiveChannelRequest::setFragDuration(uint64_t fragDuration)
{
fragDuration_ = fragDuration;
}
void PutLiveChannelRequest::setStatus(LiveChannelStatus status)
{
status_ = status;
}
void PutLiveChannelRequest::setInterval(uint64_t interval)
{
interval_ = interval;
snapshot_ = true;
}
void PutLiveChannelRequest::setNotifyTopic(const std::string& notifyTopic)
{
notifyTopic_ = notifyTopic;
snapshot_ = true;
}
void PutLiveChannelRequest::setRoleName(const std::string& roleName)
{
roleName_ = roleName;
snapshot_ = true;
}
void PutLiveChannelRequest::setPlayListName(const std::string& playListName)
{
playListName_ = playListName;
std::size_t pos = playListName_.find_last_of('.');
if(pos != std::string::npos)
{
std::string suffixStr = playListName_.substr(pos);
if(ToLower(suffixStr.c_str()) == ".m3u8")
{
std::string prefixStr;
if(pos > 0)
{
prefixStr = playListName_.substr(0, pos);
playListName_ = prefixStr + ".m3u8";
}
}
}
}
int PutLiveChannelRequest::validate() const
{
int ret = LiveChannelRequest::validate();
if(ret)
{
return ret;
}
if(!description_.empty() &&
description_.size() > MaxLiveChannelDescriptionLength)
{
return ARG_ERROR_LIVECHANNEL_BAD_DESCRIPTION_PARAM;
}
if(status_ != LiveChannelStatus::EnabledStatus &&
status_ != LiveChannelStatus::DisabledStatus)
{
return ARG_ERROR_LIVECHANNEL_BAD_STATUS_PARAM;
}
if(channelType_ != "HLS")
{
return ARG_ERROR_LIVECHANNEL_BAD_CHANNEL_TYPE_PARAM;
}
if(fragDuration_ < MinLiveChannelFragDuration ||
fragDuration_ > MaxLiveChannelFragDuration)
{
return ARG_ERROR_LIVECHANNEL_BAD_FRAGDURATION_PARAM;
}
if(fragCount_ < MinLiveChannelFragCount ||
fragCount_ > MaxLiveChannelFragCount)
{
return ARG_ERROR_LIVECHANNEL_BAD_FRAGCOUNT_PARAM;
}
if(!IsValidPlayListName(playListName_))
{
return ARG_ERROR_LIVECHANNEL_BAD_PALYLIST_PARAM;
}
if(snapshot_)
{
if(roleName_.empty() || notifyTopic_.empty() ||
destBucket_.empty() || !IsValidBucketName(bucket_) ||
interval_ < MinLiveChannelInterval ||
interval_ > MaxLiveChannelInterval)
{
return ARG_ERROR_LIVECHANNEL_BAD_SNAPSHOT_PARAM;
}
}
return 0;
}
std::string PutLiveChannelRequest::payload() const
{
std::stringstream ss;
ss << "<LiveChannelConfiguration>" << std::endl;
ss << " <Description>" << description_ << "</Description>" << std::endl;
ss << " <Status>" << ToLiveChannelStatusName(status_) << "</Status>" << std::endl;
ss << " <Target>" << std::endl;
ss << " <Type>" << channelType_ << "</Type>" << std::endl;
ss << " <FragDuration>" << std::to_string(fragDuration_) << "</FragDuration>" << std::endl;
ss << " <FragCount>" << std::to_string(fragCount_) << "</FragCount>" << std::endl;
ss << " <PlaylistName>" << playListName_ << "</PlaylistName>" << std::endl;
ss << " </Target>" << std::endl;
if(snapshot_)
{
ss << " <Snapshot>" << std::endl;
ss << " <RoleName>" << roleName_ << "</RoleName>" << std::endl;
ss << " <DestBucket>" << destBucket_ << "</DestBucket>" << std::endl;
ss << " <NotifyTopic>" << notifyTopic_ << "</NotifyTopic>" << std::endl;
ss << " <Interval>" << std::to_string(interval_) << "</Interval>" << std::endl;
ss << " </Snapshot>" << std::endl;
}
ss << "</LiveChannelConfiguration>" << std::endl;
return ss.str();
}
ParameterCollection PutLiveChannelRequest::specialParameters() const
{
ParameterCollection collection;
collection["live"] = "";
return collection;
}
| YifuLiu/AliOS-Things | components/oss/src/model/PutLiveChannelRequest.cc | C++ | apache-2.0 | 5,712 |
/*
* 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/PutLiveChannelResult.h>
#include <external/tinyxml2/tinyxml2.h>
#include <alibabacloud/oss/model/Bucket.h>
#include <alibabacloud/oss/model/Owner.h>
#include "utils/Utils.h"
using namespace AlibabaCloud::OSS;
using namespace tinyxml2;
PutLiveChannelResult::PutLiveChannelResult():
OssResult()
{
}
PutLiveChannelResult::PutLiveChannelResult(const std::string& result):
PutLiveChannelResult()
{
*this = result;
}
PutLiveChannelResult::PutLiveChannelResult(const std::shared_ptr<std::iostream>& result):
PutLiveChannelResult()
{
std::istreambuf_iterator<char> isb(*result.get()), end;
std::string str(isb, end);
*this = str;
}
PutLiveChannelResult& PutLiveChannelResult::operator =(const std::string& result)
{
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("CreateLiveChannelResult", root->Name(), 23)) {
XMLElement *node;
XMLElement* publishNode = root->FirstChildElement("PublishUrls");
if(publishNode && (node = publishNode->FirstChildElement("Url"))){
publishUrl_ = node->GetText();
}
XMLElement* playNode = root->FirstChildElement("PlayUrls");
if(playNode && (node = playNode->FirstChildElement("Url"))){
playUrl_ = node->GetText();
}
}
parseDone_ = true;
}
return *this;
}
const std::string& PutLiveChannelResult::PublishUrl() const
{
return publishUrl_;
}
const std::string& PutLiveChannelResult::PlayUrl() const
{
return playUrl_;
}
| YifuLiu/AliOS-Things | components/oss/src/model/PutLiveChannelResult.cc | C++ | apache-2.0 | 2,352 |
/*
* 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/PutLiveChannelStatusRequest.h>
#include <sstream>
#include "utils/Utils.h"
#include "ModelError.h"
using namespace AlibabaCloud::OSS;
PutLiveChannelStatusRequest::PutLiveChannelStatusRequest(const std::string& bucket, const std::string& channelName)
:LiveChannelRequest(bucket, channelName),
status_(LiveChannelStatus::EnabledStatus)
{
}
PutLiveChannelStatusRequest::PutLiveChannelStatusRequest(const std::string& bucket,
const std::string& channelName, LiveChannelStatus status)
:LiveChannelRequest(bucket, channelName),
status_(status)
{
}
ParameterCollection PutLiveChannelStatusRequest::specialParameters() const
{
ParameterCollection collection;
collection["live"] = "";
collection["status"] = ToLiveChannelStatusName(status_);
return collection;
}
void PutLiveChannelStatusRequest::setStatus(LiveChannelStatus status)
{
status_ = status;
}
int PutLiveChannelStatusRequest::validate() const
{
int ret = LiveChannelRequest::validate();
if (ret)
{
return ret;
}
if(status_ != LiveChannelStatus::EnabledStatus &&
status_ != LiveChannelStatus::DisabledStatus)
{
return ARG_ERROR_LIVECHANNEL_BAD_STATUS_PARAM;
}
return 0;
}
| YifuLiu/AliOS-Things | components/oss/src/model/PutLiveChannelStatusRequest.cc | C++ | apache-2.0 | 1,898 |
/*
* 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/PutObjectByUrlRequest.h>
#include <sstream>
#include <iostream>
using namespace AlibabaCloud::OSS;
PutObjectByUrlRequest::PutObjectByUrlRequest(
const std::string &url,
const std::shared_ptr<std::iostream> &content) :
PutObjectByUrlRequest(url, content, ObjectMetaData())
{
}
PutObjectByUrlRequest::PutObjectByUrlRequest(
const std::string &url,
const std::shared_ptr<std::iostream> &content,
const ObjectMetaData &metaData) :
ServiceRequest(),
content_(content),
metaData_(metaData)
{
setPath(url);
setFlags(Flags()|REQUEST_FLAG_PARAM_IN_PATH|REQUEST_FLAG_CHECK_CRC64);
}
HeaderCollection PutObjectByUrlRequest::Headers() const
{
auto headers = metaData_.toHeaderCollection();
if (headers.find(Http::DATE) == headers.end()) {
headers[Http::DATE] = "";
}
return headers;
}
ParameterCollection PutObjectByUrlRequest::Parameters() const
{
return ParameterCollection();
}
std::shared_ptr<std::iostream> PutObjectByUrlRequest::Body() const
{
return content_;
}
| YifuLiu/AliOS-Things | components/oss/src/model/PutObjectByUrlRequest.cc | C++ | apache-2.0 | 1,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/PutObjectRequest.h>
#include <alibabacloud/oss/http/HttpType.h>
#include "utils/Utils.h"
#include "ModelError.h"
#include <sstream>
using namespace AlibabaCloud::OSS;
PutObjectRequest::PutObjectRequest(const std::string &bucket, const std::string &key,
const std::shared_ptr<std::iostream> &content) :
OssObjectRequest(bucket, key),
content_(content)
{
setFlags(Flags() | REQUEST_FLAG_CHECK_CRC64);
}
PutObjectRequest::PutObjectRequest(const std::string &bucket, const std::string &key,
const std::shared_ptr<std::iostream> &content, const ObjectMetaData &metaData) :
OssObjectRequest(bucket, key),
content_(content),
metaData_(metaData)
{
setFlags(Flags() | REQUEST_FLAG_CHECK_CRC64);
}
void PutObjectRequest::setCacheControl(const std::string &value)
{
metaData_.addHeader(Http::CACHE_CONTROL, value);
}
void PutObjectRequest::setContentDisposition(const std::string &value)
{
metaData_.addHeader(Http::CONTENT_DISPOSITION, value);
}
void PutObjectRequest::setContentEncoding(const std::string &value)
{
metaData_.addHeader(Http::CONTENT_ENCODING, value);
}
void PutObjectRequest::setContentMd5(const std::string &value)
{
metaData_.addHeader(Http::CONTENT_MD5, value);
}
void PutObjectRequest::setExpires(const std::string &value)
{
metaData_.addHeader(Http::EXPIRES, value);
}
void PutObjectRequest::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);
}
}
void PutObjectRequest::setTagging(const std::string& value)
{
metaData_.addHeader("x-oss-tagging", value);
}
void PutObjectRequest::setTrafficLimit(uint64_t value)
{
metaData_.addHeader("x-oss-traffic-limit", std::to_string(value));
}
ObjectMetaData &PutObjectRequest::MetaData()
{
return metaData_;
}
std::shared_ptr<std::iostream> PutObjectRequest::Body() const
{
return content_;
}
HeaderCollection PutObjectRequest::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;
}
int PutObjectRequest::validate() const
{
int ret = OssObjectRequest::validate();
if (ret != 0) {
return ret;
}
if (content_ == nullptr) {
return ARG_ERROR_REQUEST_BODY_NULLPTR;
}
if (content_->bad()) {
return ARG_ERROR_REQUEST_BODY_BAD_STATE;
}
if (content_->fail()) {
return ARG_ERROR_REQUEST_BODY_FAIL_STATE;
}
return 0;
}
| YifuLiu/AliOS-Things | components/oss/src/model/PutObjectRequest.cc | C++ | apache-2.0 | 3,724 |
/*
* 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/PutObjectResult.h>
#include "utils/Utils.h"
#include <alibabacloud/oss/http/HttpType.h>
using namespace AlibabaCloud::OSS;
PutObjectResult::PutObjectResult():
OssObjectResult(),
content_(nullptr)
{
}
PutObjectResult::PutObjectResult(const HeaderCollection& header, const std::shared_ptr<std::iostream>& content):
OssObjectResult(header)
{
if (header.find(Http::ETAG) != header.end())
{
eTag_ = TrimQuotes(header.at(Http::ETAG).c_str());
}
if (header.find("x-oss-hash-crc64ecma") != header.end()) {
crc64_ = std::strtoull(header.at("x-oss-hash-crc64ecma").c_str(), nullptr, 10);
}
if (content != nullptr && content->peek() != EOF) {
content_ = content;
}
}
PutObjectResult::PutObjectResult(const HeaderCollection & header):
PutObjectResult(header, nullptr)
{
}
const std::string& PutObjectResult::ETag() const
{
return eTag_;
}
uint64_t PutObjectResult::CRC64()
{
return crc64_;
}
const std::shared_ptr<std::iostream>& PutObjectResult::Content() const
{
return content_;
}
| YifuLiu/AliOS-Things | components/oss/src/model/PutObjectResult.cc | C++ | apache-2.0 | 1,787 |
/*
* 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/RestoreObjectRequest.h>
#include <utils/Utils.h>
#include <sstream>
using namespace AlibabaCloud::OSS;
RestoreObjectRequest::RestoreObjectRequest(const std::string &bucket, const std::string &key)
:OssObjectRequest(bucket,key),
days_(1U),
tierTypeIsSet_(false)
{
}
void RestoreObjectRequest::setDays(uint32_t days)
{
days_ = days;
}
void RestoreObjectRequest::setTierType(TierType type)
{
tierType_ = type;
tierTypeIsSet_ = true;
}
std::string RestoreObjectRequest::payload() const
{
std::stringstream ss;
if (tierTypeIsSet_) {
ss << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << std::endl;
ss << "<RestoreRequest>" << std::endl;
ss << "<Days>" << std::to_string(days_) << "</Days>" << std::endl;
ss << "<JobParameters><Tier>" << ToTierTypeName(tierType_) << "</Tier></JobParameters>" << std::endl;
ss << "</RestoreRequest>" << std::endl;
}
return ss.str();
}
ParameterCollection RestoreObjectRequest::specialParameters() const
{
auto parameters = OssObjectRequest::specialParameters();
parameters["restore"]="";
return parameters;
}
| YifuLiu/AliOS-Things | components/oss/src/model/RestoreObjectRequest.cc | C++ | apache-2.0 | 1,794 |
/*
* 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/RestoreObjectResult.h>
using namespace AlibabaCloud::OSS;
RestoreObjectResult::RestoreObjectResult():
OssObjectResult()
{
}
RestoreObjectResult::RestoreObjectResult(const HeaderCollection& header):
OssObjectResult(header)
{
}
| YifuLiu/AliOS-Things | components/oss/src/model/RestoreObjectResult.cc | C++ | apache-2.0 | 924 |
/*
* 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/SelectObjectRequest.h>
#include <iostream>
#include <sstream>
#include <cstring>
#include "ModelError.h"
#include "utils/Utils.h"
#include "../utils/LogUtils.h"
#include "../utils/Crc32.h"
#include "../utils/StreamBuf.h"
#define FRAME_HEADER_LEN (12+8)
using namespace AlibabaCloud::OSS;
struct SelectObjectFrame {
int frame_type;
int init_crc32;
int32_t header_len;
int32_t tail_len;
int32_t payload_remains;
uint8_t tail[4];
uint8_t header[FRAME_HEADER_LEN];
uint8_t end_frame[256];
uint32_t end_frame_size;
uint32_t payload_crc32;
};
class SelectObjectStreamBuf : public StreamBufProxy
{
public:
SelectObjectStreamBuf(std::iostream& stream, int initCrc32) :
StreamBufProxy(stream),
lastStatus_(0)
{
// init frame
frame_.init_crc32 = initCrc32;
frame_.header_len = 0;
frame_.tail_len = 0;
frame_.payload_remains = 0;
frame_.end_frame_size = 0;
};
int LastStatus()
{
return lastStatus_;
}
protected:
int selectObjectDepackFrame(const char *ptr, int len, int *frame_type, int *payload_len, char **payload_buf, SelectObjectFrame *frame)
{
int remain = len;
//Version | Frame - Type | Payload Length | Header Checksum | Payload | Payload Checksum
//<1 byte> <--3 bytes--> <-- 4 bytes --> <------4 bytes--> <variable><----4bytes------>
//Payload
//<offset | data>
//<8 types><variable>
// header
if (frame->header_len < FRAME_HEADER_LEN) {
int copy = FRAME_HEADER_LEN - frame->header_len;
copy = ((remain > copy) ? copy : remain);
memcpy(frame->header + frame->header_len, ptr, copy);
frame->header_len += copy;
ptr += copy;
remain -= copy;
// if deal with header done
if (frame->header_len == FRAME_HEADER_LEN) {
uint32_t payload_length;
// calculation payload length
payload_length = frame->header[4];
payload_length = (payload_length << 8) | frame->header[5];
payload_length = (payload_length << 8) | frame->header[6];
payload_length = (payload_length << 8) | frame->header[7];
frame->payload_remains = payload_length - 8;
frame->payload_crc32 = CRC32::CalcCRC(frame->init_crc32, frame->header + 12, 8);
}
}
// payload
if (frame->payload_remains > 0) {
int copy = (frame->payload_remains > remain) ? remain : frame->payload_remains;
uint32_t type;
type = frame->header[1];
type = (type << 8) | frame->header[2];
type = (type << 8) | frame->header[3];
*frame_type = type;
*payload_len = copy;
*payload_buf = (char *)ptr;
remain -= copy;
frame->payload_remains -= copy;
frame->payload_crc32 = CRC32::CalcCRC(frame->payload_crc32, ptr, copy);
return len - remain;
}
// tail
if (frame->tail_len < 4) {
int copy = 4 - frame->tail_len;
copy = (copy > remain ? remain : copy);
memcpy(frame->tail + frame->tail_len, ptr, copy);
frame->tail_len += copy;
remain -= copy;
*frame_type = 0;
}
return len - remain;
}
int selectObjectTransferContent(SelectObjectFrame *frame, const char *ptr, int wanted) {
int remain = wanted;
char *payload_buf;
// the actual length of the write
int result = 0;
// deal with the whole buffer
while (remain > 0) {
int frame_type = 0, payload_len = 0;
int ret = selectObjectDepackFrame(ptr, remain, &frame_type, &payload_len, &payload_buf, frame);
switch (frame_type)
{
case 0x800001:
int temp;
temp = static_cast<int>(StreamBufProxy::xsputn(payload_buf, payload_len));
if (temp < 0) {
return temp;
}
result += temp;
break;
case 0x800004: //Continuous Frame
break;
case 0x800005: //Select object End Frame
{
int32_t copy = sizeof(frame->end_frame) - frame->end_frame_size;
copy = (copy > payload_len) ? payload_len : copy;
if (copy > 0) {
memcpy(frame->end_frame + frame->end_frame_size, ptr, copy);
frame->end_frame_size += copy;
}
}
break;
default:
// get payload checksum
if (frame->tail_len == 4) {
// compare check sum
uint32_t payload_crc32;
payload_crc32 = frame->tail[0];
payload_crc32 = (payload_crc32 << 8) | frame->tail[1];
payload_crc32 = (payload_crc32 << 8) | frame->tail[2];
payload_crc32 = (payload_crc32 << 8) | frame->tail[3];
if (payload_crc32 != 0 && payload_crc32 != frame->payload_crc32) {
// CRC32 Checksum failed
return -1;
}
// reset to get next frame
frame->header_len = 0;
frame->tail_len = 0;
frame->payload_remains = 0;
frame->end_frame_size = 0;
}
break;
}
ptr += ret;
remain -= ret;
}
return result;
}
std::streamsize xsputn(const char *ptr, std::streamsize count)
{
int result = selectObjectTransferContent(&frame_, ptr, static_cast<int>(count));
if (result < 0) {
if (result == -1) {
lastStatus_ = ARG_ERROR_SELECT_OBJECT_CHECK_SUM_FAILED;
}
return static_cast<std::streamsize>(result);
}
return count;
}
private:
SelectObjectFrame frame_;
int lastStatus_;
};
/////////////////////////////////////////////////////////////
SelectObjectRequest::SelectObjectRequest(const std::string& bucket, const std::string& key) :
GetObjectRequest(bucket, key),
expressionType_(ExpressionType::SQL),
skipPartialDataRecord_(false),
maxSkippedRecordsAllowed_(0),
inputFormat_(nullptr),
outputFormat_(nullptr),
streamBuffer_(nullptr),
upperContent_(nullptr)
{
setResponseStreamFactory(ResponseStreamFactory());
// close CRC Checksum
int flag = Flags();
flag |= REQUEST_FLAG_CONTENTMD5;
flag &= ~REQUEST_FLAG_CHECK_CRC64;
setFlags(flag);
}
void SelectObjectRequest::setResponseStreamFactory(const IOStreamFactory& factory)
{
upperResponseStreamFactory_ = factory;
ServiceRequest::setResponseStreamFactory([=]() {
streamBuffer_ = nullptr;
auto content = upperResponseStreamFactory_();
if (!outputFormat_->OutputRawData()) {
int initCrc32 = 0;
#ifdef ENABLE_OSS_TEST
if (!!(Flags() & 0x20000000)) {
const char* TAG = "SelectObjectClient";
OSS_LOG(LogLevel::LogDebug, TAG, "Payload checksum fail.");
initCrc32 = 1;
}
#endif // ENABLE_OSS_TEST
streamBuffer_ = std::make_shared<SelectObjectStreamBuf>(*content, initCrc32);
}
upperContent_ = content;
return content;
});
}
uint64_t SelectObjectRequest::MaxSkippedRecordsAllowed() const
{
return maxSkippedRecordsAllowed_;
}
void SelectObjectRequest::setSkippedRecords(bool skipPartialDataRecord, uint64_t maxSkippedRecords)
{
skipPartialDataRecord_ = skipPartialDataRecord;
maxSkippedRecordsAllowed_ = maxSkippedRecords;
}
void SelectObjectRequest::setExpression(const std::string& expression, ExpressionType type)
{
expressionType_ = type;
expression_ = expression;
}
void SelectObjectRequest::setInputFormat(InputFormat& inputFormat)
{
inputFormat_ = &inputFormat;
}
void SelectObjectRequest::setOutputFormat(OutputFormat& OutputFormat)
{
outputFormat_ = &OutputFormat;
}
int SelectObjectRequest::validate() const
{
int ret = GetObjectRequest::validate();
if (ret != 0) {
return ret;
}
if (expressionType_ != ExpressionType::SQL) {
return ARG_ERROR_SELECT_OBJECT_NOT_SQL_EXPRESSION;
}
if (inputFormat_ == nullptr || outputFormat_ == nullptr) {
return ARG_ERROR_SELECT_OBJECT_NULL_POINT;
}
ret = inputFormat_->validate();
if (ret != 0) {
return ret;
}
ret = outputFormat_->validate();
if (ret != 0) {
return ret;
}
// check type
if (inputFormat_->Type() != outputFormat_->Type()) {
return ARG_ERROR_SELECT_OBJECT_PROCESS_NOT_SAME;
}
return 0;
}
std::string SelectObjectRequest::payload() const
{
std::stringstream ss;
ss << "<SelectRequest>" << std::endl;
// Expression
ss << "<Expression>" << Base64Encode(expression_) << "</Expression>" << std::endl;
// input format
ss << inputFormat_->toXML(1) << std::endl;
// output format
ss << outputFormat_->toXML() << std::endl;
// options
ss << "<Options>" << std::endl;
ss << "<SkipPartialDataRecord>" << (skipPartialDataRecord_ ? "true" : "false") << "</SkipPartialDataRecord>" << std::endl;
ss << "<MaxSkippedRecordsAllowed>" << std::to_string(MaxSkippedRecordsAllowed()) << "</MaxSkippedRecordsAllowed>" << std::endl;
ss << "</Options>" << std::endl;
ss << "</SelectRequest>" << std::endl;
return ss.str();
}
int SelectObjectRequest::dispose() const
{
int ret = 0;
if (streamBuffer_ != nullptr) {
auto buf = std::static_pointer_cast<SelectObjectStreamBuf>(streamBuffer_);
ret = buf->LastStatus();
streamBuffer_ = nullptr;
}
upperContent_ = nullptr;
return ret;
}
ParameterCollection SelectObjectRequest::specialParameters() const
{
auto parameters = GetObjectRequest::specialParameters();
if (inputFormat_) {
auto type = inputFormat_->Type();
type.append("/select");
parameters["x-oss-process"] = type;
}
return parameters;
}
| YifuLiu/AliOS-Things | components/oss/src/model/SelectObjectRequest.cc | C++ | apache-2.0 | 11,028 |
/*
* 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/SetBucketAclRequest.h>
#include "utils/Utils.h"
using namespace AlibabaCloud::OSS;
SetBucketAclRequest::SetBucketAclRequest(const std::string &bucket, CannedAccessControlList acl) :
OssBucketRequest(bucket),
acl_(acl)
{
}
void SetBucketAclRequest::setAcl(CannedAccessControlList acl)
{
acl_ = acl;
}
HeaderCollection SetBucketAclRequest::specialHeaders() const
{
HeaderCollection headers;
if (acl_ < CannedAccessControlList::Default) {
headers["x-oss-acl"] = ToAclName(acl_);
}
return headers;
}
ParameterCollection SetBucketAclRequest::specialParameters() const
{
ParameterCollection parameters;
parameters["acl"] = "";
return parameters;
}
| YifuLiu/AliOS-Things | components/oss/src/model/SetBucketAclRequest.cc | C++ | apache-2.0 | 1,358 |
/*
* 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/SetBucketCorsRequest.h>
#include "utils/Utils.h"
#include "ModelError.h"
#include <sstream>
#include <set>
#include <alibabacloud/oss/Const.h>
using namespace AlibabaCloud::OSS;
SetBucketCorsRequest::SetBucketCorsRequest(const std::string &bucket) :
OssBucketRequest(bucket)
{
}
void SetBucketCorsRequest::addCORSRule(const CORSRule &rule)
{
ruleList_.push_back(rule);
}
void SetBucketCorsRequest::setCORSRules(const CORSRuleList &rules)
{
ruleList_ = rules;
}
std::string SetBucketCorsRequest::payload() const
{
std::stringstream ss;
ss << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << std::endl;
ss << "<CORSConfiguration>" << std::endl;
for (const auto &rule : ruleList_)
{
ss << " <CORSRule>" << std::endl;
for (const auto &origin : rule.AllowedOrigins())
ss << " <AllowedOrigin>" << origin << "</AllowedOrigin>" << std::endl;
for (const auto &method : rule.AllowedMethods())
ss << " <AllowedMethod>" << method << "</AllowedMethod>" << std::endl;
for (const auto &header : rule.AllowedHeaders())
ss << " <AllowedHeader>" << header << "</AllowedHeader>" << std::endl;
for (const auto &header : rule.ExposeHeaders())
ss << " <ExposeHeader>" << header << "</ExposeHeader>" << std::endl;
if (rule.MaxAgeSeconds() > 0)
ss << " <MaxAgeSeconds>" << std::to_string(rule.MaxAgeSeconds()) << "</MaxAgeSeconds>" << std::endl;
ss << " </CORSRule>" << std::endl;
}
ss << "</CORSConfiguration>" << std::endl;
return ss.str();
}
ParameterCollection SetBucketCorsRequest::specialParameters() const
{
ParameterCollection parameters;
parameters["cors"] = "";
return parameters;
}
static int CountOfAsterisk(const CORSAllowedList &items)
{
int count = 0;
for (auto const&item : items) {
count += item.compare("*") ? 0 : 1;
}
return count;
}
static bool InAllowedMethods(const CORSAllowedList &items)
{
static std::set<std::string> allowedMethods =
{
"GET" , "PUT" , "DELETE", "POST", "HEAD"
};
//if (items.empty())
// return false;
for (auto const&item : items) {
if (allowedMethods.find(Trim(item.c_str())) == allowedMethods.end()) {
return false;
}
}
return true;
}
int SetBucketCorsRequest::validate() const
{
int ret = OssBucketRequest::validate();
if (ret) return ret;
if (ruleList_.size() > BucketCorsRuleLimit)
return ARG_ERROR_CORS_RULE_LIMIT;
for (auto const &rule : ruleList_) {
if (rule.AllowedOrigins().empty())
return ARG_ERROR_CORS_ALLOWEDORIGINS_EMPTY;
if (CountOfAsterisk(rule.AllowedOrigins()) > 1)
return ARG_ERROR_CORS_ALLOWEDORIGINS_ASTERISK_COUNT;
if (rule.AllowedMethods().empty())
return ARG_ERROR_CORS_ALLOWEDMETHODS_EMPTY;
if (!InAllowedMethods(rule.AllowedMethods()))
return ARG_ERROR_CORS_ALLOWEDMETHODS_VALUE;
if (CountOfAsterisk(rule.AllowedHeaders()) > 1)
return ARG_ERROR_CORS_ALLOWEDHEADERS_ASTERISK_COUNT;
if (CountOfAsterisk(rule.ExposeHeaders()) > 0)
return ARG_ERROR_CORS_EXPOSEHEADERS_ASTERISK_COUNT;
if ((rule.MaxAgeSeconds() != CORSRule::UNSET_AGE_SEC) &&
(rule.MaxAgeSeconds() < 0 || rule.MaxAgeSeconds() > 999999999)) {
return ARG_ERROR_CORS_MAXAGESECONDS_RANGE;
}
}
return 0;
}
| YifuLiu/AliOS-Things | components/oss/src/model/SetBucketCorsRequest.cc | C++ | apache-2.0 | 4,167 |
/*
* 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/SetBucketEncryptionRequest.h>
#include "utils/Utils.h"
#include <sstream>
using namespace AlibabaCloud::OSS;
SetBucketEncryptionRequest::SetBucketEncryptionRequest(const std::string& bucket, SSEAlgorithm sse, const std::string& key):
OssBucketRequest(bucket),
SSEAlgorithm_(sse),
KMSMasterKeyID_(key)
{
setFlags(Flags() | REQUEST_FLAG_CONTENTMD5);
}
void SetBucketEncryptionRequest::setSSEAlgorithm(SSEAlgorithm sse)
{
SSEAlgorithm_ = sse;
}
void SetBucketEncryptionRequest::setKMSMasterKeyID(const std::string& key)
{
KMSMasterKeyID_ = key;
}
ParameterCollection SetBucketEncryptionRequest::specialParameters() const
{
ParameterCollection parameters;
parameters["encryption"] = "";
return parameters;
}
std::string SetBucketEncryptionRequest::payload() const
{
std::stringstream ss;
ss << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << std::endl;
ss << "<ServerSideEncryptionRule>" << std::endl;
ss << " <ApplyServerSideEncryptionByDefault>" << std::endl;
ss << "<SSEAlgorithm>" << ToSSEAlgorithmName(SSEAlgorithm_) << "</SSEAlgorithm>" << std::endl;
ss << "<KMSMasterKeyID>" << KMSMasterKeyID_ << "</KMSMasterKeyID>" << std::endl;
ss << "</ApplyServerSideEncryptionByDefault>" << std::endl;
ss << "</ServerSideEncryptionRule>" << std::endl;
return ss.str();
}
| YifuLiu/AliOS-Things | components/oss/src/model/SetBucketEncryptionRequest.cc | C++ | apache-2.0 | 2,003 |
/*
* 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/SetBucketInventoryConfigurationRequest.h>
#include "utils/Utils.h"
#include <sstream>
using namespace AlibabaCloud::OSS;
SetBucketInventoryConfigurationRequest::SetBucketInventoryConfigurationRequest(const std::string& bucket) :
SetBucketInventoryConfigurationRequest(bucket, InventoryConfiguration())
{
}
SetBucketInventoryConfigurationRequest::SetBucketInventoryConfigurationRequest(const std::string& bucket, const InventoryConfiguration& conf) :
OssBucketRequest(bucket),
inventoryConfiguration_(conf)
{
setFlags(Flags() | REQUEST_FLAG_CONTENTMD5);
}
void SetBucketInventoryConfigurationRequest::setInventoryConfiguration(InventoryConfiguration conf)
{
inventoryConfiguration_ = conf;
}
ParameterCollection SetBucketInventoryConfigurationRequest::specialParameters() const
{
ParameterCollection parameters;
parameters["inventory"] = "";
parameters["inventoryId"] = inventoryConfiguration_.Id();
return parameters;
}
std::string SetBucketInventoryConfigurationRequest::payload() const
{
std::stringstream ss;
ss << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << std::endl;
ss << "<InventoryConfiguration>" << std::endl;
ss << " <Id>" << inventoryConfiguration_.Id() << "</Id>" << std::endl;
ss << " <IsEnabled>" << (inventoryConfiguration_.IsEnabled() ? "true" : "false") << "</IsEnabled>" << std::endl;
if (!inventoryConfiguration_.Filter().Prefix().empty()) {
ss << " <Filter>" << std::endl;
ss << " <Prefix>" << inventoryConfiguration_.Filter().Prefix() << "</Prefix>" << std::endl;
ss << " </Filter>" << std::endl;
}
bool hasEncryption = inventoryConfiguration_.Destination().OSSBucketDestination().Encryption().hasSSEKMS() ||
inventoryConfiguration_.Destination().OSSBucketDestination().Encryption().hasSSEOSS();
ss << " <Destination>" << std::endl;
ss << " <OSSBucketDestination>" << std::endl;
ss << " <Format>" << ToInventoryFormatName(inventoryConfiguration_.Destination().OSSBucketDestination().Format()) << "</Format>" << std::endl;
ss << " <AccountId>" << inventoryConfiguration_.Destination().OSSBucketDestination().AccountId() << "</AccountId>" << std::endl;
ss << " <RoleArn>" << inventoryConfiguration_.Destination().OSSBucketDestination().RoleArn() << "</RoleArn>" << std::endl;
ss << " <Bucket>" << ToInventoryBucketFullName(inventoryConfiguration_.Destination().OSSBucketDestination().Bucket()) << "</Bucket>" << std::endl;
ss << " <Prefix>" << inventoryConfiguration_.Destination().OSSBucketDestination().Prefix() << "</Prefix>" << std::endl;
if (hasEncryption) {
ss << " <Encryption>" << std::endl;
if (inventoryConfiguration_.Destination().OSSBucketDestination().Encryption().hasSSEKMS()) {
ss << " <SSE-KMS>" << std::endl;
ss << " <KeyId>" << inventoryConfiguration_.Destination().OSSBucketDestination().Encryption().SSEKMS().KeyId() << "</KeyId>" << std::endl;
ss << " </SSE-KMS>" << std::endl;
}
if (inventoryConfiguration_.Destination().OSSBucketDestination().Encryption().hasSSEOSS()) {
ss << " <SSE-OSS>" << std::endl;
ss << " </SSE-OSS>" << std::endl;
}
ss << " </Encryption>" << std::endl;
}
ss << " </OSSBucketDestination>" << std::endl;
ss << " </Destination>" << std::endl;
ss << " <Schedule>" << std::endl;
ss << " <Frequency>" << ToInventoryFrequencyName(inventoryConfiguration_.Schedule()) << "</Frequency>" << std::endl;
ss << " </Schedule>" << std::endl;
ss << " <IncludedObjectVersions>" << ToInventoryIncludedObjectVersionsName(inventoryConfiguration_.IncludedObjectVersions()) << "</IncludedObjectVersions>" << std::endl;
if (!inventoryConfiguration_.OptionalFields().empty()) {
ss << " <OptionalFields>" << std::endl;
for (const auto& field : inventoryConfiguration_.OptionalFields()) {
ss << " <Field>" << ToInventoryOptionalFieldName(field) << "</Field>" << std::endl;
}
ss << " </OptionalFields>" << std::endl;
}
ss << "</InventoryConfiguration>" << std::endl;
return ss.str();
} | YifuLiu/AliOS-Things | components/oss/src/model/SetBucketInventoryConfigurationRequest.cc | C++ | apache-2.0 | 4,832 |
/*
* 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/SetBucketLifecycleRequest.h>
#include <alibabacloud/oss/Const.h>
#include <sstream>
#include <utils/Utils.h>
#include "ModelError.h"
using namespace AlibabaCloud::OSS;
SetBucketLifecycleRequest::SetBucketLifecycleRequest(const std::string& bucket) :
OssBucketRequest(bucket)
{
setFlags(Flags() | REQUEST_FLAG_CONTENTMD5);
}
std::string SetBucketLifecycleRequest::payload() const
{
std::stringstream ss;
ss << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << std::endl;
ss << "<LifecycleConfiguration>" << std::endl;
for (auto const &rule : lifecycleRules_)
{
ss << " <Rule>" << std::endl;
ss << " <ID>" << rule.ID() << "</ID>" << std::endl;
ss << " <Prefix>" << rule.Prefix() << "</Prefix>" << std::endl;
for (const auto& tag : rule.Tags())
{
ss << " <Tag><Key>" << tag.Key() << "</Key><Value>" << tag.Value() << "</Value></Tag>" << std::endl;
}
ss << " <Status>" << ToRuleStatusName(rule.Status()) << "</Status>" << std::endl;
if (rule.hasExpiration())
{
ss << " <Expiration>" << std::endl;
if (rule.Expiration().Days() > 0) {
ss << " <Days>" << std::to_string(rule.Expiration().Days()) << "</Days>" << std::endl;
}
else if (!rule.Expiration().CreatedBeforeDate().empty()){
ss << " <CreatedBeforeDate>" << rule.Expiration().CreatedBeforeDate() << "</CreatedBeforeDate>" << std::endl;
}
if (rule.ExpiredObjectDeleteMarker()) {
ss << " <ExpiredObjectDeleteMarker>true</ExpiredObjectDeleteMarker>" << std::endl;
}
ss << " </Expiration>" << std::endl;
}
for (auto const & transition: rule.TransitionList())
{
ss << " <Transition>" << std::endl;
if (transition.Expiration().Days() > 0) {
ss << " <Days>" << std::to_string(transition.Expiration().Days()) << "</Days>" << std::endl;
}
else {
ss << " <CreatedBeforeDate>" << transition.Expiration().CreatedBeforeDate() << "</CreatedBeforeDate>" << std::endl;
}
ss << " <StorageClass>" << ToStorageClassName(transition.StorageClass()) << "</StorageClass>" << std::endl;
ss << " </Transition>" << std::endl;
}
if (rule.hasAbortMultipartUpload())
{
ss << " <AbortMultipartUpload>" << std::endl;
if (rule.AbortMultipartUpload().Days() > 0) {
ss << " <Days>" << std::to_string(rule.AbortMultipartUpload().Days()) << "</Days>" << std::endl;
}
else {
ss << " <CreatedBeforeDate>" << rule.AbortMultipartUpload().CreatedBeforeDate() << "</CreatedBeforeDate>" << std::endl;
}
ss << " </AbortMultipartUpload>" << std::endl;
}
if (rule.hasNoncurrentVersionExpiration())
{
ss << " <NoncurrentVersionExpiration>" << std::endl;
ss << " <NoncurrentDays>" << std::to_string(rule.NoncurrentVersionExpiration().Days()) << "</NoncurrentDays>" << std::endl;
ss << " </NoncurrentVersionExpiration>" << std::endl;
}
for (auto const & transition : rule.NoncurrentVersionTransitionList())
{
ss << " <NoncurrentVersionTransition>" << std::endl;
if (transition.Expiration().Days() > 0) {
ss << " <NoncurrentDays>" << std::to_string(transition.Expiration().Days()) << "</NoncurrentDays>" << std::endl;
}
ss << " <StorageClass>" << ToStorageClassName(transition.StorageClass()) << "</StorageClass>" << std::endl;
ss << " </NoncurrentVersionTransition>" << std::endl;
}
ss << " </Rule>" << std::endl;
}
ss << "</LifecycleConfiguration>" << std::endl;
return ss.str();
}
ParameterCollection SetBucketLifecycleRequest::specialParameters() const
{
ParameterCollection parameters;
parameters["lifecycle"] = "";
return parameters;
}
int SetBucketLifecycleRequest::validate() const
{
int ret;
if ((ret = OssBucketRequest::validate()) != 0) {
return ret;
}
if (lifecycleRules_.size() > LifecycleRuleLimit) {
return ARG_ERROR_LIFECYCLE_RULE_LIMIT;
}
if (lifecycleRules_.empty()) {
return ARG_ERROR_LIFECYCLE_RULE_EMPTY;
}
for (auto const &rule : lifecycleRules_) {
//no config rule
if (!rule.hasAbortMultipartUpload() &&
!rule.hasExpiration() &&
!rule.hasTransitionList() &&
!rule.hasNoncurrentVersionExpiration() &&
!rule.hasNoncurrentVersionTransitionList()) {
return ARG_ERROR_LIFECYCLE_RULE_CONFIG_EMPTY;
}
if (rule.Prefix().empty() && lifecycleRules_.size() > 1) {
return ARG_ERROR_LIFECYCLE_RULE_ONLY_ONE_FOR_BUCKET;
}
}
return 0;
}
| YifuLiu/AliOS-Things | components/oss/src/model/SetBucketLifecycleRequest.cc | C++ | apache-2.0 | 5,826 |
/*
* 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/SetBucketLoggingRequest.h>
#include <sstream>
#include <utils/Utils.h>
#include "ModelError.h"
using namespace AlibabaCloud::OSS;
SetBucketLoggingRequest::SetBucketLoggingRequest(const std::string& bucket) :
SetBucketLoggingRequest(bucket, "", "")
{
}
SetBucketLoggingRequest::SetBucketLoggingRequest(const std::string& bucket,
const std::string& targetBucket, const std::string& targetPrefix) :
OssBucketRequest(bucket),
targetBucket_(targetBucket),
targetPrefix_(targetPrefix)
{
setFlags(Flags() | REQUEST_FLAG_CONTENTMD5);
}
std::string SetBucketLoggingRequest::payload() const
{
std::stringstream ss;
ss << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << std::endl;
ss << "<BucketLoggingStatus>" << std::endl;
ss << "<LoggingEnabled>" << std::endl;
ss << "<TargetBucket>" << targetBucket_ << "</TargetBucket>" << std::endl;
ss << "<TargetPrefix>" << targetPrefix_ << "</TargetPrefix>" << std::endl;
ss << "</LoggingEnabled>" << std::endl;
ss << "</BucketLoggingStatus>" << std::endl;
return ss.str();
}
ParameterCollection SetBucketLoggingRequest::specialParameters() const
{
ParameterCollection parameters;
parameters["logging"] = "";
return parameters;
}
int SetBucketLoggingRequest::validate() const
{
int ret;
if ((ret = OssBucketRequest::validate()) != 0 ) {
return ret;
}
if (!IsValidBucketName(targetBucket_)) {
return ARG_ERROR_BUCKET_NAME;
}
if (!IsValidLoggingPrefix(targetPrefix_)) {
return ARG_ERROR_LOGGING_TARGETPREFIX_INVALID;
}
return 0;
}
| YifuLiu/AliOS-Things | components/oss/src/model/SetBucketLoggingRequest.cc | C++ | apache-2.0 | 2,332 |
/*
* 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/SetBucketPaymentRequest.h>
#include <sstream>
#include "utils/Utils.h"
using namespace AlibabaCloud::OSS;
SetBucketRequestPaymentRequest::SetBucketRequestPaymentRequest(const std::string& bucket) :
SetBucketRequestPaymentRequest(bucket, RequestPayer::NotSet)
{
}
SetBucketRequestPaymentRequest::SetBucketRequestPaymentRequest(const std::string& bucket,
RequestPayer payer) :
OssBucketRequest(bucket),
payer_(payer)
{
setFlags(Flags() | REQUEST_FLAG_CONTENTMD5);
}
std::string SetBucketRequestPaymentRequest::payload() const
{
std::stringstream ss;
ss << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << std::endl;
ss << "<RequestPaymentConfiguration>" << std::endl;
ss << "<Payer>" << ToRequestPayerName(payer_) << "</Payer>" << std::endl;
ss << "</RequestPaymentConfiguration>" << std::endl;
return ss.str();
}
ParameterCollection SetBucketRequestPaymentRequest::specialParameters() const
{
ParameterCollection parameters;
parameters["requestPayment"] = "";
return parameters;
}
| YifuLiu/AliOS-Things | components/oss/src/model/SetBucketPaymentRequest.cc | C++ | apache-2.0 | 1,703 |
/*
* 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/SetBucketPolicyRequest.h>
#include <sstream>
using namespace AlibabaCloud::OSS;
SetBucketPolicyRequest::SetBucketPolicyRequest(const std::string& bucket) :
SetBucketPolicyRequest(bucket, "")
{
}
SetBucketPolicyRequest::SetBucketPolicyRequest(const std::string& bucket,
const std::string& policy) :
OssBucketRequest(bucket),
policy_(policy)
{
setFlags(Flags() | REQUEST_FLAG_CONTENTMD5);
}
std::string SetBucketPolicyRequest::payload() const
{
return policy_;
}
ParameterCollection SetBucketPolicyRequest::specialParameters() const
{
ParameterCollection parameters;
parameters["policy"] = "";
return parameters;
}
| YifuLiu/AliOS-Things | components/oss/src/model/SetBucketPolicyRequest.cc | C++ | apache-2.0 | 1,316 |
/*
* 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/SetBucketQosInfoRequest.h>
using namespace AlibabaCloud::OSS;
SetBucketQosInfoRequest::SetBucketQosInfoRequest(const std::string& bucket) :
SetBucketQosInfoRequest(bucket, QosConfiguration())
{
}
SetBucketQosInfoRequest::SetBucketQosInfoRequest(const std::string& bucket, const QosConfiguration& qos) :
OssBucketRequest(bucket),
qosInfo_(qos)
{
setFlags(Flags() | REQUEST_FLAG_CONTENTMD5);
}
std::string SetBucketQosInfoRequest::payload() const
{
std::string str;
str.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
str.append("<QoSConfiguration>\n");
str.append("<TotalUploadBandwidth>");
str.append(std::to_string(qosInfo_.TotalUploadBandwidth()));
str.append("</TotalUploadBandwidth>\n");
str.append("<IntranetUploadBandwidth>");
str.append(std::to_string(qosInfo_.IntranetUploadBandwidth()));
str.append("</IntranetUploadBandwidth>\n");
str.append("<ExtranetUploadBandwidth>");
str.append(std::to_string(qosInfo_.ExtranetUploadBandwidth()));
str.append("</ExtranetUploadBandwidth>\n");
str.append("<TotalDownloadBandwidth>");
str.append(std::to_string(qosInfo_.TotalDownloadBandwidth()));
str.append("</TotalDownloadBandwidth>\n");
str.append("<IntranetDownloadBandwidth>");
str.append(std::to_string(qosInfo_.IntranetDownloadBandwidth()));
str.append("</IntranetDownloadBandwidth>\n");
str.append("<ExtranetDownloadBandwidth>");
str.append(std::to_string(qosInfo_.ExtranetDownloadBandwidth()));
str.append("</ExtranetDownloadBandwidth>\n");
str.append("<TotalQps>");
str.append(std::to_string(qosInfo_.TotalQps()));
str.append("</TotalQps>\n");
str.append("<IntranetQps>");
str.append(std::to_string(qosInfo_.IntranetQps()));
str.append("</IntranetQps>\n");
str.append("<ExtranetQps>");
str.append(std::to_string(qosInfo_.ExtranetQps()));
str.append("</ExtranetQps>\n");
str.append("</QoSConfiguration>");
return str;
}
ParameterCollection SetBucketQosInfoRequest::specialParameters() const
{
ParameterCollection parameters;
parameters["qosInfo"] = "";
return parameters;
}
| YifuLiu/AliOS-Things | components/oss/src/model/SetBucketQosInfoRequest.cc | C++ | apache-2.0 | 2,806 |
/*
* 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/SetBucketRefererRequest.h>
#include <sstream>
using namespace AlibabaCloud::OSS;
SetBucketRefererRequest::SetBucketRefererRequest(const std::string& bucket) :
OssBucketRequest(bucket),
allowEmptyReferer_(true)
{
setFlags(Flags() | REQUEST_FLAG_CONTENTMD5);
}
SetBucketRefererRequest::SetBucketRefererRequest(const std::string& bucket, const RefererList& refererList) :
SetBucketRefererRequest(bucket, refererList, true)
{
}
SetBucketRefererRequest::SetBucketRefererRequest(const std::string& bucket, const RefererList& refererList,
bool allowEmptyReferer) :
OssBucketRequest(bucket),
allowEmptyReferer_(allowEmptyReferer),
refererList_(refererList)
{
setFlags(Flags() | REQUEST_FLAG_CONTENTMD5);
}
std::string SetBucketRefererRequest::payload() const
{
std::stringstream ss;
ss << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << std::endl;
ss << "<RefererConfiguration>" << std::endl;
ss << " <AllowEmptyReferer>" << (allowEmptyReferer_ ? "true" : "false") << "</AllowEmptyReferer>" << std::endl;
ss << " <RefererList>" << std::endl;
for (const auto &referer : refererList_) {
ss << " <Referer>" << referer << "</Referer>" << std::endl;
}
ss << " </RefererList>" << std::endl;
ss << "</RefererConfiguration>" << std::endl;
return ss.str();
}
ParameterCollection SetBucketRefererRequest::specialParameters() const
{
ParameterCollection parameters;
parameters["referer"] = "";
return parameters;
}
| YifuLiu/AliOS-Things | components/oss/src/model/SetBucketRefererRequest.cc | C++ | apache-2.0 | 2,224 |
/*
* 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/SetBucketStorageCapacityRequest.h>
#include "utils/Utils.h"
#include "ModelError.h"
#include <sstream>
using namespace AlibabaCloud::OSS;
SetBucketStorageCapacityRequest::SetBucketStorageCapacityRequest(const std::string &bucket, int64_t storageCapacity) :
OssBucketRequest(bucket),
storageCapacity_(storageCapacity)
{
setFlags(Flags() | REQUEST_FLAG_CONTENTMD5);
}
ParameterCollection SetBucketStorageCapacityRequest::specialParameters() const
{
ParameterCollection parameters;
parameters["qos"] = "";
return parameters;
}
std::string SetBucketStorageCapacityRequest::payload() const
{
std::stringstream ss;
ss << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << std::endl;
ss << "<BucketUserQos>" << std::endl;
ss << " <StorageCapacity>" << std::to_string(storageCapacity_) << "</StorageCapacity>" << std::endl;
ss << "</BucketUserQos>" << std::endl;
return ss.str();
}
int SetBucketStorageCapacityRequest::validate() const
{
int ret;
if ((ret = OssBucketRequest::validate()) != 0) {
return ret;
}
if (storageCapacity_ < 0)
return ARG_ERROR_STORAGECAPACITY_INVALID;
return 0;
}
| YifuLiu/AliOS-Things | components/oss/src/model/SetBucketStorageCapacityRequest.cc | C++ | apache-2.0 | 1,895 |
/*
* 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/SetBucketTaggingRequest.h>
#include <alibabacloud/oss/Const.h>
#include "utils/Utils.h"
#include "ModelError.h"
#include <sstream>
using namespace AlibabaCloud::OSS;
SetBucketTaggingRequest::SetBucketTaggingRequest(const std::string& bucket) :
SetBucketTaggingRequest(bucket, Tagging())
{
}
SetBucketTaggingRequest::SetBucketTaggingRequest(const std::string& bucket, const Tagging& tagging) :
OssBucketRequest(bucket),
tagging_(tagging)
{
setFlags(Flags() | REQUEST_FLAG_CONTENTMD5);
}
void SetBucketTaggingRequest::setTagging(const Tagging& tagging)
{
tagging_ = tagging;
}
std::string SetBucketTaggingRequest::payload() const
{
std::stringstream ss;
ss << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << std::endl;
ss << "<Tagging>" << std::endl;
ss << " <TagSet>" << std::endl;
for (const auto& tag : tagging_.Tags()) {
ss << " <Tag><Key>" << tag.Key() << "</Key><Value>" << tag.Value() << "</Value></Tag>" << std::endl;
}
ss << " </TagSet>" << std::endl;
ss << "</Tagging>" << std::endl;
return ss.str();
}
ParameterCollection SetBucketTaggingRequest::specialParameters() const
{
ParameterCollection parameters;
parameters["tagging"] = "";
return parameters;
}
int SetBucketTaggingRequest::validate() const
{
int ret;
if ((ret = OssBucketRequest::validate()) != 0) {
return ret;
}
if (tagging_.Tags().empty() || tagging_.Tags().size() > MaxTagSize) {
return ARG_ERROR_TAGGING_TAGS_LIMIT;
}
for (const auto& tag : tagging_.Tags()) {
if (!IsValidTagKey(tag.Key()))
return ARG_ERROR_TAGGING_TAG_KEY_LIMIT;
if (!IsValidTagValue(tag.Value()))
return ARG_ERROR_TAGGING_TAG_VALUE_LIMIT;
}
return 0;
} | YifuLiu/AliOS-Things | components/oss/src/model/SetBucketTaggingRequest.cc | C++ | apache-2.0 | 2,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.
*/
#include <alibabacloud/oss/model/SetBucketVersioningRequest.h>
#include <sstream>
#include <utils/Utils.h>
#include "ModelError.h"
using namespace AlibabaCloud::OSS;
SetBucketVersioningRequest::SetBucketVersioningRequest(const std::string& bucket, VersioningStatus status) :
OssBucketRequest(bucket),
status_(status)
{
}
void SetBucketVersioningRequest::setStatus(VersioningStatus status)
{
status_ = status;
}
std::string SetBucketVersioningRequest::payload() const
{
std::stringstream ss;
ss << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << std::endl;
ss << "<VersioningConfiguration>" << std::endl;
ss << "<Status>" << ToVersioningStatusName(status_) << "</Status>" << std::endl;
ss << "</VersioningConfiguration>" << std::endl;
return ss.str();
}
ParameterCollection SetBucketVersioningRequest::specialParameters() const
{
ParameterCollection parameters;
parameters["versioning"] = "";
return parameters;
}
| YifuLiu/AliOS-Things | components/oss/src/model/SetBucketVersioningRequest.cc | C++ | apache-2.0 | 1,645 |
/*
* 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/SetBucketWebsiteRequest.h>
#include <sstream>
#include <utils/Utils.h>
#include "ModelError.h"
using namespace AlibabaCloud::OSS;
SetBucketWebsiteRequest::SetBucketWebsiteRequest(const std::string& bucket) :
OssBucketRequest(bucket),
indexDocumentIsSet_(false),
errorDocumentIsSet_(false)
{
setFlags(Flags() | REQUEST_FLAG_CONTENTMD5);
}
std::string SetBucketWebsiteRequest::payload() const
{
std::stringstream ss;
ss << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << std::endl;
ss << "<WebsiteConfiguration>" << std::endl;
ss << " <IndexDocument>" << std::endl;
ss << " <Suffix>" << indexDocument_ << "</Suffix>" << std::endl;
ss << " </IndexDocument>" << std::endl;
if (errorDocumentIsSet_) {
ss << " <ErrorDocument>" << std::endl;
ss << " <Key>" << errorDocument_ << "</Key>" << std::endl;
ss << " </ErrorDocument>" << std::endl;
}
ss << "</WebsiteConfiguration>" << std::endl;
return ss.str();
}
ParameterCollection SetBucketWebsiteRequest::specialParameters() const
{
ParameterCollection parameters;
parameters["website"] = "";
return parameters;
}
static bool IsValidWebpage(const std::string &webpage)
{
const std::string pageSuffix = ".html";
return (webpage.size() > pageSuffix.size()) &&
(webpage.substr(webpage.size() - 5).compare(".html") == 0);
}
int SetBucketWebsiteRequest::validate() const
{
int ret = OssBucketRequest::validate();
if (ret != 0)
return ret;
if (indexDocument_.empty())
return ARG_ERROR_WEBSITE_INDEX_DOCCUMENT_EMPTY;
if (!IsValidWebpage(indexDocument_))
return ARG_ERROR_WEBSITE_INDEX_DOCCUMENT_NAME_INVALID;
if (errorDocumentIsSet_ && !IsValidWebpage(errorDocument_))
return ARG_ERROR_WEBSITE_ERROR_DOCCUMENT_NAME_INVALID;
return 0;
}
| YifuLiu/AliOS-Things | components/oss/src/model/SetBucketWebsiteRequest.cc | C++ | apache-2.0 | 2,597 |
/*
* 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/SetObjectAclRequest.h>
#include <alibabacloud/oss/http/HttpType.h>
#include "utils/Utils.h"
using namespace AlibabaCloud::OSS;
SetObjectAclRequest::SetObjectAclRequest(const std::string &bucket, const std::string &key) :
OssObjectRequest(bucket,key),
hasSetAcl_(false)
{
}
SetObjectAclRequest::SetObjectAclRequest(const std::string &bucket
,const std::string &key, CannedAccessControlList acl) :
OssObjectRequest(bucket,key),
acl_(acl),
hasSetAcl_(true)
{
}
void SetObjectAclRequest::setAcl(CannedAccessControlList acl)
{
acl_ = acl;
hasSetAcl_ = true;
}
HeaderCollection SetObjectAclRequest::specialHeaders() const
{
auto headers = OssObjectRequest::specialHeaders();
if (hasSetAcl_) {
headers["x-oss-object-acl"] = ToAclName(acl_);
}
return headers;
}
ParameterCollection SetObjectAclRequest::specialParameters() const
{
auto parameters = OssObjectRequest::specialParameters();
parameters["acl"] = "";
return parameters;
}
| YifuLiu/AliOS-Things | components/oss/src/model/SetObjectAclRequest.cc | C++ | apache-2.0 | 1,656 |
/*
* 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/SetObjectAclResult.h>
using namespace AlibabaCloud::OSS;
SetObjectAclResult::SetObjectAclResult():
OssObjectResult()
{
}
SetObjectAclResult::SetObjectAclResult(const HeaderCollection& header):
OssObjectResult(header)
{
}
| YifuLiu/AliOS-Things | components/oss/src/model/SetObjectAclResult.cc | C++ | apache-2.0 | 921 |
/*
* 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/SetObjectTaggingRequest.h>
#include <alibabacloud/oss/Const.h>
#include "utils/Utils.h"
#include "ModelError.h"
#include <sstream>
using namespace AlibabaCloud::OSS;
SetObjectTaggingRequest::SetObjectTaggingRequest(const std::string& bucket, const std::string& key):
OssObjectRequest(bucket, key)
{
setFlags(Flags() | REQUEST_FLAG_CONTENTMD5);
}
SetObjectTaggingRequest::SetObjectTaggingRequest(const std::string& bucket, const std::string& key,
const Tagging& tagging):
OssObjectRequest(bucket, key),
tagging_(tagging)
{
setFlags(Flags() | REQUEST_FLAG_CONTENTMD5);
}
void SetObjectTaggingRequest::setTagging(const Tagging& tagging)
{
tagging_ = tagging;
}
std::string SetObjectTaggingRequest::payload() const
{
std::stringstream ss;
ss << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << std::endl;
ss << "<Tagging>" << std::endl;
ss << " <TagSet>" << std::endl;
for (const auto& tag : tagging_.Tags()) {
ss << " <Tag><Key>"<< tag.Key() <<"</Key><Value>" << tag.Value() << "</Value></Tag>" << std::endl;
}
ss << " </TagSet>" << std::endl;
ss << "</Tagging>" << std::endl;
return ss.str();
}
ParameterCollection SetObjectTaggingRequest::specialParameters() const
{
auto parameters = OssObjectRequest::specialParameters();
parameters["tagging"] = "";
return parameters;
}
int SetObjectTaggingRequest::validate() const
{
int ret;
if ((ret = OssObjectRequest::validate()) != 0) {
return ret;
}
if (tagging_.Tags().empty() || tagging_.Tags().size() > MaxTagSize) {
return ARG_ERROR_TAGGING_TAGS_LIMIT;
}
for (const auto& tag : tagging_.Tags()) {
if (!IsValidTagKey(tag.Key()))
return ARG_ERROR_TAGGING_TAG_KEY_LIMIT;
if (!IsValidTagValue(tag.Value()))
return ARG_ERROR_TAGGING_TAG_VALUE_LIMIT;
}
return 0;
} | YifuLiu/AliOS-Things | components/oss/src/model/SetObjectTaggingRequest.cc | C++ | apache-2.0 | 2,642 |
/*
* 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/Tagging.h>
#include "utils/Utils.h"
#include <sstream>
using namespace AlibabaCloud::OSS;
std::string Tagging::toQueryParameters()
{
std::string sep;
std::stringstream ss;
for (const auto& tag : tagSet_)
{
if (tag.Key().empty())
continue;
if (tag.Value().empty())
ss << sep << UrlEncode(tag.Key());
else
ss << sep << UrlEncode(tag.Key()) << "=" << UrlEncode(tag.Value());
sep = "&";
}
return ss.str();
}
| YifuLiu/AliOS-Things | components/oss/src/model/Tagging.cc | C++ | apache-2.0 | 1,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.
*/
#include <alibabacloud/oss/model/UploadPartCopyRequest.h>
#include <sstream>
#include "utils/Utils.h"
#include "ModelError.h"
#include <alibabacloud/oss/Const.h>
using namespace AlibabaCloud::OSS;
using std::stringstream;
UploadPartCopyRequest::UploadPartCopyRequest(const std::string &bucket, const std::string &key) :
UploadPartCopyRequest(bucket, key, std::string(), std::string(), std::string(), 0)
{
}
UploadPartCopyRequest::UploadPartCopyRequest(const std::string &bucket, const std::string &key,
const std::string &srcBucket, const std::string &srcKey) :
UploadPartCopyRequest(bucket, key, srcBucket, srcKey, std::string(), 0)
{
}
UploadPartCopyRequest::UploadPartCopyRequest(const std::string &bucket, const std::string &key,
const std::string &srcBucket, const std::string &srcKey,
const std::string &uploadId, int partNumber):
OssObjectRequest(bucket, key),
uploadId_(uploadId),
sourceBucket_(srcBucket),
sourceKey_(srcKey),
partNumber_(partNumber),
sourceRangeIsSet_(false),
sourceIfMatchETagIsSet_(false),
sourceIfNotMatchETagIsSet_(false),
sourceIfModifiedSinceIsSet_(false),
sourceIfUnModifiedSinceIsSet_(false),
trafficLimit_(0)
{
}
UploadPartCopyRequest::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) :
OssObjectRequest(bucket, key),
uploadId_(uploadId),
sourceBucket_(srcBucket),
sourceKey_(srcKey),
partNumber_(partNumber),
sourceRangeIsSet_(false),
trafficLimit_(0)
{
if (!sourceIfMatchETag.empty()) {
sourceIfMatchETag_ = sourceIfMatchETag;
sourceIfMatchETagIsSet_ = true;
}
else {
sourceIfMatchETagIsSet_ = false;
}
if (!sourceIfNotMatchETag.empty()) {
sourceIfNotMatchETag_ = sourceIfNotMatchETag;
sourceIfNotMatchETagIsSet_ = true;
}
else {
sourceIfNotMatchETagIsSet_ = false;
}
if (!sourceIfModifiedSince.empty()) {
sourceIfModifiedSince_ = sourceIfModifiedSince;
sourceIfModifiedSinceIsSet_ = true;
}
else {
sourceIfModifiedSinceIsSet_ = false;
}
if (!sourceIfUnModifiedSince.empty()) {
sourceIfUnModifiedSince_ = sourceIfUnModifiedSince;
sourceIfUnModifiedSinceIsSet_ = true;
}
else {
sourceIfUnModifiedSinceIsSet_ = false;
}
}
void UploadPartCopyRequest::setPartNumber(uint32_t partNumber)
{
partNumber_ = partNumber;
}
void UploadPartCopyRequest::setUploadId(const std::string &uploadId)
{
uploadId_ = uploadId;
}
void UploadPartCopyRequest::SetCopySource(const std::string& srcBucket, const std::string& srcKey)
{
sourceBucket_ = srcBucket;
sourceKey_ = srcKey;
}
void UploadPartCopyRequest::setCopySourceRange(uint64_t begin, uint64_t end)
{
sourceRange_[0] = begin;
sourceRange_[1] = end;
sourceRangeIsSet_ = true;
}
void UploadPartCopyRequest::SetSourceIfMatchETag(const std::string& value)
{
sourceIfMatchETag_ = value;
sourceIfMatchETagIsSet_ = true;
}
void UploadPartCopyRequest::SetSourceIfNotMatchETag(const std::string& value)
{
sourceIfNotMatchETag_ = value;
sourceIfNotMatchETagIsSet_ = true;
}
void UploadPartCopyRequest::SetSourceIfModifiedSince(const std::string& value)
{
sourceIfModifiedSince_ = value;
sourceIfModifiedSinceIsSet_ = true;
}
void UploadPartCopyRequest::SetSourceIfUnModifiedSince(const std::string& value)
{
sourceIfUnModifiedSince_ = value;
sourceIfUnModifiedSinceIsSet_ = true;
}
void UploadPartCopyRequest::setTrafficLimit(uint64_t value)
{
trafficLimit_ = value;
}
ParameterCollection UploadPartCopyRequest::specialParameters() const
{
ParameterCollection parameters;
parameters["partNumber"] = std::to_string(partNumber_);
parameters["uploadId"] = uploadId_;
return parameters;
}
HeaderCollection UploadPartCopyRequest::specialHeaders() const
{
auto headers = OssObjectRequest::specialHeaders();
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;
if (sourceRangeIsSet_) {
std::string range("bytes=");
range.append(std::to_string(sourceRange_[0])).append("-");
if (sourceRange_[1] > 0){
range.append(std::to_string(sourceRange_[1]));
}
headers["x-oss-copy-source-range"] = range;
}
if(sourceIfMatchETagIsSet_) {
headers["x-oss-copy-source-if-match"] = sourceIfMatchETag_;
}
if(sourceIfNotMatchETagIsSet_) {
headers["x-oss-copy-source-if-none-match"] = sourceIfNotMatchETag_;
}
if(sourceIfModifiedSinceIsSet_) {
headers["x-oss-copy-source-if-modified-since"] = sourceIfModifiedSince_;
}
if (sourceIfUnModifiedSinceIsSet_) {
headers["x-oss-copy-source-if-unmodified-since"] = sourceIfUnModifiedSince_;
}
if (trafficLimit_ != 0) {
headers["x-oss-traffic-limit"] = std::to_string(trafficLimit_);
}
return headers;
}
int UploadPartCopyRequest::validate() const
{
int ret = OssObjectRequest::validate();
if (ret != 0){
return ret;
}
if (!IsValidBucketName(sourceBucket_)) {
return ARG_ERROR_BUCKET_NAME;
}
if (!IsValidObjectKey(sourceKey_)) {
return ARG_ERROR_OBJECT_NAME;
}
if (sourceRangeIsSet_ &&
((sourceRange_[1] < sourceRange_[0]) ||
((sourceRange_[1] - sourceRange_[0] + 1) > MaxFileSize))) {
return ARG_ERROR_MULTIPARTUPLOAD_PARTSIZE_RANGE;
}
if(!(partNumber_ > 0 && partNumber_ < PartNumberUpperLimit)){
return ARG_ERROR_MULTIPARTUPLOAD_PARTNUMBER_RANGE;
}
return 0;
}
| YifuLiu/AliOS-Things | components/oss/src/model/UploadPartCopyRequest.cc | C++ | apache-2.0 | 6,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.
*/
#include <alibabacloud/oss/model/UploadPartCopyResult.h>
#include <alibabacloud/oss/model/Owner.h>
#include <external/tinyxml2/tinyxml2.h>
#include "utils/Utils.h"
using namespace AlibabaCloud::OSS;
using namespace tinyxml2;
static const std::string EMPTY;
UploadPartCopyResult::UploadPartCopyResult() :
OssObjectResult()
{
}
UploadPartCopyResult::UploadPartCopyResult(const std::string& result):
UploadPartCopyResult()
{
*this = result;
}
UploadPartCopyResult::UploadPartCopyResult(const std::shared_ptr<std::iostream>& result,
const HeaderCollection &headers):
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(*result.get()), end;
std::string str(isb, end);
*this = str;
}
UploadPartCopyResult& UploadPartCopyResult::operator =(
const std::string& result)
{
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("CopyPartResult", root->Name(), 14)) {
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());
}
parseDone_ = true;
}
}
return *this;
}
const std::string& UploadPartCopyResult::LastModified() const
{
return lastModified_;
}
const std::string& UploadPartCopyResult::ETag() const
{
return eTag_;
}
| YifuLiu/AliOS-Things | components/oss/src/model/UploadPartCopyResult.cc | C++ | apache-2.0 | 2,513 |
/*
* 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.
*/
#include <alibabacloud/oss/model/UploadPartRequest.h>
#include <alibabacloud/oss/http/HttpType.h>
#include "utils/Utils.h"
#include "ModelError.h"
#include <alibabacloud/oss/Const.h>
using namespace AlibabaCloud::OSS;
UploadPartRequest::UploadPartRequest(const std::string &bucket, const std::string &key,
const std::shared_ptr<std::iostream> &content) :
UploadPartRequest(bucket, key, 0, "", content)
{
}
UploadPartRequest::UploadPartRequest(const std::string &bucket, const std::string &key,
int partNumber, const std::string &uploadId,
const std::shared_ptr<std::iostream> &content) :
OssObjectRequest(bucket, key),
partNumber_(partNumber),
uploadId_(uploadId),
content_(content),
contentLengthIsSet_(false),
trafficLimit_(0),
userAgent_()
{
setFlags(Flags() | REQUEST_FLAG_CHECK_CRC64);
}
void UploadPartRequest::setPartNumber(int partNumber)
{
partNumber_ = partNumber;
}
void UploadPartRequest::setUploadId(const std::string &uploadId)
{
uploadId_ = uploadId;
}
void UploadPartRequest::setConetent(const std::shared_ptr<std::iostream> &content)
{
content_ = content;
}
void UploadPartRequest::setContentLength(uint64_t length)
{
contentLength_ = length;
contentLengthIsSet_ = true;
}
void UploadPartRequest::setTrafficLimit(uint64_t value)
{
trafficLimit_ = value;
}
void UploadPartRequest::setUserAgent(const std::string& ua)
{
userAgent_ = ua;
}
int UploadPartRequest::PartNumber() const
{
return partNumber_;
}
std::shared_ptr<std::iostream> UploadPartRequest::Body() const
{
return content_;
}
HeaderCollection UploadPartRequest::specialHeaders() const
{
auto headers = OssObjectRequest::specialHeaders();
headers[Http::CONTENT_TYPE] = "";
if (contentLengthIsSet_) {
headers[Http::CONTENT_LENGTH] = std::to_string(contentLength_);
}
if (trafficLimit_ != 0) {
headers["x-oss-traffic-limit"] = std::to_string(trafficLimit_);
}
if (!userAgent_.empty()) {
headers[Http::USER_AGENT] = userAgent_;
}
return headers;
}
ParameterCollection UploadPartRequest::specialParameters() const
{
ParameterCollection parameters;
parameters["partNumber"] = std::to_string(partNumber_);
parameters["uploadId"] = uploadId_;
return parameters;
}
int UploadPartRequest::validate() const
{
int ret = OssObjectRequest::validate();
if (ret)
{
return ret;
}
if (content_ == nullptr) {
return ARG_ERROR_REQUEST_BODY_NULLPTR;
}
if (content_->bad()) {
return ARG_ERROR_REQUEST_BODY_BAD_STATE;
}
if (content_->fail()) {
return ARG_ERROR_REQUEST_BODY_FAIL_STATE;
}
if (!(partNumber_ > 0 && partNumber_ < PartNumberUpperLimit)) {
return ARG_ERROR_MULTIPARTUPLOAD_PARTNUMBER_RANGE;
}
uint64_t partSize;
if (contentLengthIsSet_) {
partSize = contentLength_;
}
else {
partSize = GetIOStreamLength(*content_);
}
if (partSize > MaxFileSize) {
return ARG_ERROR_MULTIPARTUPLOAD_PARTSIZE_RANGE;
}
return 0;
}
| YifuLiu/AliOS-Things | components/oss/src/model/UploadPartRequest.cc | C++ | apache-2.0 | 3,730 |
/*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#include "OssClient.h"
#include "iostream"
#include "fstream"
#include "string.h"
#include "oss_app.h"
#if !ESP_PLATFORM
#include "aos/vfs.h"
#endif
#include "fcntl.h"
#ifdef USE_SD_FOR_OSS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <signal.h>
#include "aos/kernel.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "ulog/ulog.h"
int sd_fd;
#endif
using namespace AlibabaCloud::OSS;
static void ProgressCallback(size_t increment, int64_t transfered, int64_t total, void* userData)
{
// std::cout << "ProgressCallback[" << userData << "] => " <<
// increment <<" ," << transfered << "," << total << std::endl;
}
static int64_t getFileSize(const std::string& file)
{
std::fstream f(file, std::ios::in | std::ios::binary);
f.seekg(0, f.end);
int64_t size = f.tellg();
f.close();
return size;
}
extern "C"{
#ifdef USE_SD_FOR_OSS
int sd_file_open(char * read_file)
{
struct stat s;
const char file[30]={0};
if(!read_file){
memcpy(file,"/sdcard/test.h264",strlen("/sdcard/test.h264"));
}
else{
memcpy(file,read_file,strlen(read_file));
}
LOG("open file %s",file);
sd_fd = open(file, O_RDONLY);
if (sd_fd < 0) {
LOG("Failed to open file %s\r\n", file);
return -1;
}
stat(file,&s);
return s.st_size;
}
int sd_file_close(void)
{
close(sd_fd);
}
void sd_file_read(unsigned char * buf,int read_size)
{
int rc, i;
rc = read(sd_fd, buf, read_size);
if (rc < 0) {
LOG("Failed to read file\r\n");
}
return;
}
#endif
extern Url g_ags_url;
std::string g_url;
char *oss_upload_local_file(char *keyId, char *keySecret, char *endPoint, char *bucketName, char *localfilepath)
{
/* 初始化OSS账号信息 */
std::string AccessKeyId;
std::string AccessKeySecret;
std::string Endpoint;
std::string BucketName;
/* yourObjectName表示上传文件到OSS时需要指定包含文件后缀在内的完整路径,例如abc/efg/123.jpg */
std::string ObjectName ;
// char *pfile_path,file_path[256];
if((keyId == NULL)||(keySecret == NULL)||(endPoint == NULL)||(bucketName == NULL)||(localfilepath == NULL))
{
return NULL;
}
AccessKeyId = keyId;
AccessKeySecret = keySecret;
Endpoint = endPoint;
BucketName = bucketName;
#if OSS_DEBUG
std::cout << "Input_AccessKeyId:" << AccessKeyId <<std::endl;
std::cout << "Input_AccessKeySecret:" << AccessKeySecret <<std::endl;
std::cout << "Input_Endpoint:" << Endpoint <<std::endl;
std::cout << "Input_BucketName:" << BucketName <<std::endl;
#endif
// memset(file_path,0,256);
// pfile_path = localfilepath;
// strncpy(file_path,&pfile_path[1],strlen(pfile_path)-1);
ObjectName = localfilepath;
#ifdef USE_SD_FOR_OSS
int file_total_size;
char *alloc_file_content;
std::string sContent;
/* 初始化网络等资源 */
InitializeSdk();
ClientConfiguration conf;
OssClient client(Endpoint, AccessKeyId, AccessKeySecret, conf);
/* 上传文件 */
#if OSS_DEBUG
std::cout << "objectfile_path:" << ObjectName <<std::endl;
std::cout << "localfile_path:" << localfilepath <<std::endl;
#endif
file_total_size = sd_file_open(localfilepath);
if(file_total_size > READ_SD_SIZE_MAX){
LOG("---SD open file size too Large %d > 10K",file_total_size);
sd_file_close();
ShutdownSdk();
return NULL;
}
LOG("SD open file size <%d>.",file_total_size);
alloc_file_content = (unsigned char *) aos_malloc(file_total_size);
if(!alloc_file_content){
LOG("malloc err");
aos_free(alloc_file_content);
sd_file_close();
ShutdownSdk();
return NULL;
}
sd_file_read(alloc_file_content,file_total_size);
sContent = alloc_file_content;
std::shared_ptr<std::iostream> content = std::make_shared<std::stringstream>();
*content << sContent;
PutObjectRequest request(BucketName, ObjectName, content);
TransferProgress progressCallback = { ProgressCallback };
request.setTransferProgress(progressCallback);
auto outcome = client.PutObject(request);
g_url = g_ags_url.toString();
std::cout << "oss ->url:" << g_url << std::endl;
if (!outcome.isSuccess()) {
/* 异常处理 */
std::cout << "PutObject fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
aos_free(alloc_file_content);
sd_file_close();
ShutdownSdk();
return NULL;
}
// std::cout << __FUNCTION__ << " success, ETag:" << outcome.result().ETag() << std::endl;
/* 释放网络等资源 */
aos_free(alloc_file_content);
sd_file_close();
ShutdownSdk();
return g_url.c_str();
#else
/* 初始化网络等资源 */
InitializeSdk();
ClientConfiguration conf;
OssClient client(Endpoint, AccessKeyId, AccessKeySecret, conf);
//OssClient client(Endpoint, AccessKeyId, AccessKeySecret,SecretToken, conf);
/* 上传文件 */
auto fileSize = getFileSize(localfilepath);
#if OSS_DEBUG
std::cout << "objectfile_path:" << ObjectName <<std::endl;
std::cout << "localfile_path:" << localfilepath <<std::endl;
std::cout << "localfile_path size:" << fileSize <<std::endl;
#endif
std::shared_ptr<std::iostream> content = std::make_shared<std::fstream>(localfilepath, std::ios::in | std::ios::binary);
PutObjectRequest request(BucketName, ObjectName, content);
TransferProgress progressCallback = { ProgressCallback };
request.setTransferProgress(progressCallback);
auto outcome = client.PutObject(request);
g_url = g_ags_url.toString();
// std::cout << "oss ->url:" << g_url << std::endl;
if (!outcome.isSuccess()) {
/* 异常处理 */
std::cout << "PutObject fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
ShutdownSdk();
return NULL;
}
// std::cout << __FUNCTION__ << " success, ETag:" << outcome.result().ETag() << std::endl;
/* 释放网络等资源 */
ShutdownSdk();
return g_url.c_str();
#endif
}
char *oss_upload_file(char *keyId, char *keySecret, char *endPoint, char *bucketName, char *localfilepath, char *objectName)
{
/* 初始化OSS账号信息 */
std::string AccessKeyId;
std::string AccessKeySecret;
std::string Endpoint;
std::string BucketName;
/* yourObjectName表示上传文件到OSS时需要指定包含文件后缀在内的完整路径,例如abc/efg/123.jpg */
std::string ObjectName ;
if((keyId == NULL)||(keySecret == NULL)||(endPoint == NULL)||(bucketName == NULL)||(localfilepath == NULL))
{
return NULL;
}
AccessKeyId = keyId;
AccessKeySecret = keySecret;
Endpoint = endPoint;
BucketName = bucketName;
ObjectName = objectName;
#if OSS_DEBUG
std::cout << "Input_AccessKeyId:" << AccessKeyId <<std::endl;
std::cout << "Input_AccessKeySecret:" << AccessKeySecret <<std::endl;
std::cout << "Input_Endpoint:" << Endpoint <<std::endl;
std::cout << "Input_BucketName:" << BucketName <<std::endl;
#endif
#ifdef USE_SD_FOR_OSS
int file_total_size;
char *alloc_file_content;
std::string sContent;
/* 初始化网络等资源 */
InitializeSdk();
ClientConfiguration conf;
OssClient client(Endpoint, AccessKeyId, AccessKeySecret, conf);
/* 上传文件 */
#if OSS_DEBUG
std::cout << "objectfile_path:" << ObjectName <<std::endl;
std::cout << "localfile_path:" << localfilepath <<std::endl;
#endif
file_total_size = sd_file_open(localfilepath);
if(file_total_size > READ_SD_SIZE_MAX){
LOG("---SD open file size too Large %d > 10K",file_total_size);
sd_file_close();
ShutdownSdk();
return NULL;
}
LOG("SD open file size <%d>.",file_total_size);
alloc_file_content = (unsigned char *) aos_malloc(file_total_size);
if(!alloc_file_content){
LOG("malloc err");
aos_free(alloc_file_content);
sd_file_close();
ShutdownSdk();
return NULL;
}
sd_file_read(alloc_file_content,file_total_size);
sContent = alloc_file_content;
std::shared_ptr<std::iostream> content = std::make_shared<std::stringstream>();
*content << sContent;
PutObjectRequest request(BucketName, ObjectName, content);
TransferProgress progressCallback = { ProgressCallback };
request.setTransferProgress(progressCallback);
auto outcome = client.PutObject(request);
g_url = g_ags_url.toString();
// std::cout << "oss ->url:" << g_url << std::endl;
if (!outcome.isSuccess()) {
/* 异常处理 */
std::cout << "PutObject fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
aos_free(alloc_file_content);
sd_file_close();
ShutdownSdk();
return NULL;
}
// std::cout << __FUNCTION__ << " success, ETag:" << outcome.result().ETag() << std::endl;
/* 释放网络等资源 */
aos_free(alloc_file_content);
sd_file_close();
ShutdownSdk();
return g_url.c_str();
#else
/* 初始化网络等资源 */
InitializeSdk();
ClientConfiguration conf;
OssClient client(Endpoint, AccessKeyId, AccessKeySecret, conf);
//OssClient client(Endpoint, AccessKeyId, AccessKeySecret,SecretToken, conf);
/* 上传文件 */
auto fileSize = getFileSize(localfilepath);
#if OSS_DEBUG
std::cout << "objectfile_path:" << ObjectName <<std::endl;
std::cout << "localfile_path:" << localfilepath <<std::endl;
std::cout << "localfile_path size:" << fileSize <<std::endl;
#endif
std::shared_ptr<std::iostream> content = std::make_shared<std::fstream>(localfilepath, std::ios::in | std::ios::binary);
PutObjectRequest request(BucketName, ObjectName, content);
TransferProgress progressCallback = { ProgressCallback };
request.setTransferProgress(progressCallback);
auto outcome = client.PutObject(request);
g_url = g_ags_url.toString();
// std::cout << "oss ->url:" << g_url << std::endl;
if (!outcome.isSuccess()) {
/* 异常处理 */
std::cout << "PutObject fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
ShutdownSdk();
return NULL;
}
// std::cout << __FUNCTION__ << " success, ETag:" << outcome.result().ETag() << std::endl;
/* 释放网络等资源 */
ShutdownSdk();
return g_url.c_str();
#endif
}
char *oss_upload_local_content(char *keyId, char *keySecret, char *endPoint, char *bucketName, char *scontent, int32_t contentLen, char *ossFilePath)
{
/* 初始化OSS账号信息 */
std::string AccessKeyId;
std::string AccessKeySecret;
std::string Endpoint;
std::string BucketName;
/* yourObjectName表示上传文件到OSS时需要指定包含文件后缀在内的完整路径,例如abc/efg/123.jpg */
std::string ObjectName ;
std::string sContent;
if((keyId == NULL)||(keySecret == NULL)||(endPoint == NULL)||(bucketName == NULL))
{
return NULL;
}
AccessKeyId = keyId;
AccessKeySecret = keySecret;
Endpoint = endPoint;
BucketName = bucketName;
if(scontent == NULL){
sContent = "Welcome to HaaS";
}
else{
sContent = scontent;
}
#if OSS_DEBUG
std::cout << "Input_AccessKeyId:" << AccessKeyId <<std::endl;
std::cout << "Input_AccessKeySecret:" << AccessKeySecret <<std::endl;
std::cout << "Input_Endpoint:" << Endpoint <<std::endl;
std::cout << "Input_BucketName:" << BucketName <<std::endl;
#endif
/* 初始化网络等资源 */
InitializeSdk();
ClientConfiguration conf;
OssClient client(Endpoint, AccessKeyId, AccessKeySecret, conf);
/* 上传文件 */
std::shared_ptr<std::iostream> content = std::make_shared<std::stringstream>();
(*content).write(scontent, contentLen);
ObjectName = ossFilePath;
// std::cout << "objectfile_path:" << ObjectName <<std::endl;
PutObjectRequest request(BucketName, ObjectName, content);
TransferProgress progressCallback = { ProgressCallback };
request.setTransferProgress(progressCallback);
auto outcome = client.PutObject(request);
g_url = g_ags_url.toString();
// std::cout << "oss ->url:" << g_url << std::endl;
if (!outcome.isSuccess()) {
/* 异常处理 */
std::cout << "PutObject fail: " <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
ShutdownSdk();
return NULL;
}
// std::cout << __FUNCTION__ << " success, ETag:" << outcome.result().ETag() << std::endl;
/* 释放网络等资源 */
ShutdownSdk();
return g_url.c_str();
}
char *oss_download_file(char *keyId, char *keySecret, char *endPoint, char *bucketName, char *objectName, char * localfilepath)
{
/* 初始化OSS账号信息 */
std::string AccessKeyId;
std::string AccessKeySecret;
std::string Endpoint;
std::string BucketName;
/* yourObjectName表示上传文件到OSS时需要指定包含文件后缀在内的完整路径,例如abc/efg/123.jpg */
std::string ObjectName ;
/*设置下载文件的文件名*/
std::string FileNametoSave = "yourFileName";
if((keyId == NULL)||(keySecret == NULL)||(endPoint == NULL)||(bucketName == NULL)||(localfilepath == NULL))
{
return NULL;
}
AccessKeyId = keyId;
AccessKeySecret = keySecret;
Endpoint = endPoint;
BucketName = bucketName;
ObjectName = objectName;
#if ESP_PLATFORM
int fp = open(localfilepath, O_RDWR | O_CREAT | O_TRUNC);
#else
int fp = aos_open(localfilepath, O_RDWR | O_CREAT | O_TRUNC);
#endif
if (fp < 0) {
std::cout <<"open file fail\n";
return NULL;
}
/*初始化网络等资源*/
InitializeSdk();
ClientConfiguration conf;
OssClient client(Endpoint, AccessKeyId, AccessKeySecret, conf);
/*获取文件到本地内存。*/
GetObjectRequest request(BucketName, ObjectName);
auto outcome = client.GetObject(request);
if (outcome.isSuccess()) {
std::cout << "getObjectToBuffer" << " success, Content-Length:" << outcome.result().Metadata().ContentLength() << std::endl;
/*通过read接口读取数据。*/
auto& stream = outcome.result().Content();
char buffer[256];
while (stream->good()) {
stream->read(buffer, 256);
auto count = stream->gcount();
/*根据实际情况处理数据。*/
#if ESP_PLATFORM
int ret = write(fp, buffer, count);
if (ret <= 0) {
close(fp);
fp = -1;
return NULL;
}
#else
int ret = aos_write(fp, buffer, count);
if (ret <= 0) {
aos_close(fp);
fp = -1;
return NULL;
}
#endif
}
}
else {
/*异常处理。*/
std::cout << "getObjectToBuffer fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
ShutdownSdk();
return NULL;
}
if (fp >= 0) {
#if ESP_PLATFORM
close(fp);
#else
aos_close(fp);
#endif
}
/*释放网络等资源*/
ShutdownSdk();
return NULL;
}
//cplusplus
}
| YifuLiu/AliOS-Things | components/oss/src/oss_app.cpp | C++ | apache-2.0 | 16,199 |
/*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#ifndef SSH_ERLANGSHEN_OSS_APP_H
#define SSH_ERLANGSHEN_OSS_APP_H
#include <string.h>
#ifdef __cplusplus
extern "C" {
#endif
char *oss_upload_local_file(char *keyId, char *keySecret, char *endPoint, char *bucketName, char *localfilepath);
char *oss_upload_local_content(char *keyId, char *keySecret, char *endPoint, char *bucketName, char *scontent,
int32_t contentLen, char *ossFilePath);
char *oss_upload_file(char *keyId, char *keySecret, char *endPoint, char *bucketName, char *localfilepath,
char *objectName);
char *oss_download_file(char *keyId, char *keySecret, char *endPoint, char *bucketName, char *objectName,
char *localfilepath);
#ifdef __cplusplus
}
#endif
#endif // OSS_APP_H
| YifuLiu/AliOS-Things | components/oss/src/oss_app.h | C | apache-2.0 | 839 |
/*
* 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/DownloadObjectRequest.h>
#include <alibabacloud/oss/Const.h>
#include <sstream>
#include <fstream>
#include "../model/ModelError.h"
#include "../utils/FileSystemUtils.h"
using namespace AlibabaCloud::OSS;
DownloadObjectRequest::DownloadObjectRequest(const std::string &bucket, const std::string &key,
const std::string &filePath, const std::string &checkpointDir,
const uint64_t partSize, const uint32_t threadNum):
OssResumableBaseRequest(bucket, key, checkpointDir, partSize, threadNum),
rangeIsSet_(false),
filePath_(filePath)
{
tempFilePath_ = filePath + ".temp";
}
DownloadObjectRequest::DownloadObjectRequest(const std::string &bucket, const std::string &key,
const std::string &filePath, const std::string &checkpointDir) :
DownloadObjectRequest(bucket, key, filePath, checkpointDir, DefaultPartSize, DefaultResumableThreadNum)
{}
DownloadObjectRequest::DownloadObjectRequest(const std::string &bucket, const std::string &key,
const std::string &filePath) :
DownloadObjectRequest(bucket, key, filePath, "", DefaultPartSize, DefaultResumableThreadNum)
{}
//wstring
DownloadObjectRequest::DownloadObjectRequest(const std::string &bucket, const std::string &key,
const std::wstring &filePath, const std::wstring &checkpointDir,
const uint64_t partSize, const uint32_t threadNum) :
OssResumableBaseRequest(bucket, key, checkpointDir, partSize, threadNum),
rangeIsSet_(false),
filePathW_(filePath)
{
tempFilePathW_ = filePath + L".temp";
}
DownloadObjectRequest::DownloadObjectRequest(const std::string &bucket, const std::string &key,
const std::wstring &filePath, const std::wstring &checkpointDir) :
DownloadObjectRequest(bucket, key, filePath, checkpointDir, DefaultPartSize, DefaultResumableThreadNum)
{}
DownloadObjectRequest::DownloadObjectRequest(const std::string &bucket, const std::string &key,
const std::wstring &filePath) :
DownloadObjectRequest(bucket, key, filePath, L"", DefaultPartSize, DefaultResumableThreadNum)
{}
void DownloadObjectRequest::setRange(int64_t start, int64_t end)
{
range_[0] = start;
range_[1] = end;
rangeIsSet_ = true;
}
void DownloadObjectRequest::setModifiedSinceConstraint(const std::string &value)
{
modifiedSince_ = value;
}
void DownloadObjectRequest::setUnmodifiedSinceConstraint(const std::string &value)
{
unmodifiedSince_ = value;
}
void DownloadObjectRequest::setMatchingETagConstraints(const std::vector<std::string> &values)
{
matchingETags_ = values;
}
void DownloadObjectRequest::setNonmatchingETagConstraints(const std::vector<std::string> &values)
{
nonmatchingETags_ = values;
}
void DownloadObjectRequest::addResponseHeaders(RequestResponseHeader header, const std::string &value)
{
static const char *ResponseHeader[] = {
"response-content-type", "response-content-language",
"response-expires", "response-cache-control",
"response-content-disposition", "response-content-encoding" };
responseHeaderParameters_[ResponseHeader[header - RequestResponseHeader::ContentType]] = value;
}
int DownloadObjectRequest::validate() const
{
auto ret = OssResumableBaseRequest::validate();
if (ret != 0) {
return ret;
}
if (rangeIsSet_ && (range_[0] < 0 || range_[1] < -1 || (range_[1] > -1 && range_[1] < range_[0]))) {
return ARG_ERROR_INVALID_RANGE;
}
#if !defined(_WIN32)
if (!filePathW_.empty()) {
return ARG_ERROR_PATH_NOT_SUPPORT_WSTRING_TYPE;
}
#endif
if (filePath_.empty() && filePathW_.empty()) {
return ARG_ERROR_DOWNLOAD_FILE_PATH_EMPTY;
}
//path and checkpoint must be same type.
if ((!filePath_.empty() && !checkpointDirW_.empty()) ||
(!filePathW_.empty() && !checkpointDir_.empty())) {
return ARG_ERROR_PATH_NOT_SAME_TYPE;
}
//check tmpfilePath is available
auto stream = GetFstreamByPath(tempFilePath_, tempFilePathW_, std::ios::out | std::ios::app);
if (!stream->is_open()) {
return ARG_ERROR_OPEN_DOWNLOAD_TEMP_FILE;
}
stream->close();
return 0;
}
| YifuLiu/AliOS-Things | components/oss/src/resumable/DownloadObjectRequest.cc | C++ | apache-2.0 | 4,907 |
/*
* 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/MultiCopyObjectRequest.h>
#include <alibabacloud/oss/Const.h>
#include <sstream>
#include "../utils/FileSystemUtils.h"
#include "utils/Utils.h"
#include "../model/ModelError.h"
using namespace AlibabaCloud::OSS;
static const std::string strEmpty = "";
MultiCopyObjectRequest::MultiCopyObjectRequest(const std::string &bucket, const std::string &key,
const std::string &srcBucket, const std::string &srcKey) :
MultiCopyObjectRequest(bucket, key, srcBucket, srcKey, "", DefaultPartSize, DefaultResumableThreadNum)
{}
MultiCopyObjectRequest::MultiCopyObjectRequest(const std::string &bucket, const std::string &key,
const std::string &srcBucket, const std::string &srcKey,
const std::string &checkpointDir) :
MultiCopyObjectRequest(bucket, key, srcBucket, srcKey, checkpointDir, DefaultPartSize, DefaultResumableThreadNum)
{}
MultiCopyObjectRequest::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(bucket, key, srcBucket, srcKey, checkpointDir, DefaultPartSize, DefaultResumableThreadNum, meta)
{}
MultiCopyObjectRequest::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& meta):
MultiCopyObjectRequest(bucket, key, srcBucket, srcKey, checkpointDir, partSize, threadNum)
{
metaData_ = meta;
}
MultiCopyObjectRequest::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) :
OssResumableBaseRequest(bucket, key, checkpointDir, partSize, threadNum),
srcBucket_(srcBucket),
srcKey_(srcKey)
{
setCopySource(srcBucket, srcKey);
}
//wstring
MultiCopyObjectRequest::MultiCopyObjectRequest(const std::string &bucket, const std::string &key,
const std::string &srcBucket, const std::string &srcKey,
const std::wstring &checkpointDir) :
MultiCopyObjectRequest(bucket, key, srcBucket, srcKey, checkpointDir, DefaultPartSize, DefaultResumableThreadNum)
{}
MultiCopyObjectRequest::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(bucket, key, srcBucket, srcKey, checkpointDir, DefaultPartSize, DefaultResumableThreadNum, meta)
{}
MultiCopyObjectRequest::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& meta) :
MultiCopyObjectRequest(bucket, key, srcBucket, srcKey, checkpointDir, partSize, threadNum)
{
metaData_ = meta;
}
MultiCopyObjectRequest::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) :
OssResumableBaseRequest(bucket, key, checkpointDir, partSize, threadNum),
srcBucket_(srcBucket),
srcKey_(srcKey)
{
setCopySource(srcBucket, srcKey);
}
void MultiCopyObjectRequest::setCopySource(const std::string& srcBucket, const std::string& srcObject)
{
std::stringstream ssDesc;
ssDesc << "/" << srcBucket << "/" << srcObject;
std::string value = ssDesc.str();
metaData_.addHeader("x-oss-copy-source", value);
}
void MultiCopyObjectRequest::setSourceIfMatchEtag(const std::string& value)
{
metaData_.addHeader("x-oss-copy-source-if-match", value);
}
const std::string& MultiCopyObjectRequest::SourceIfMatchEtag() const
{
if (metaData_.HttpMetaData().find("x-oss-copy-source-if-match") != metaData_.HttpMetaData().end()) {
return metaData_.HttpMetaData().at("x-oss-copy-source-if-match");
}
return strEmpty;
}
void MultiCopyObjectRequest::setSourceIfNotMatchEtag(const std::string& value)
{
metaData_.addHeader("x-oss-copy-source-if-none-match", value);
}
const std::string& MultiCopyObjectRequest::SourceIfNotMatchEtag() const
{
if (metaData_.HttpMetaData().find("x-oss-copy-source-if-none-match") != metaData_.HttpMetaData().end()) {
return metaData_.HttpMetaData().at("x-oss-copy-source-if-none-match");
}
return strEmpty;
}
void MultiCopyObjectRequest::setSourceIfUnModifiedSince(const std::string& value)
{
metaData_.addHeader("x-oss-copy-source-if-unmodified-since", value);
}
const std::string& MultiCopyObjectRequest::SourceIfUnModifiedSince() const
{
if (metaData_.HttpMetaData().find("x-oss-copy-source-if-unmodified-since") != metaData_.HttpMetaData().end()) {
return metaData_.HttpMetaData().at("x-oss-copy-source-if-unmodified-since");
}
return strEmpty;
}
void MultiCopyObjectRequest::setSourceIfModifiedSince(const std::string& value)
{
metaData_.addHeader("x-oss-copy-source-if-modified-since", value);
}
const std::string& MultiCopyObjectRequest::SourceIfModifiedSince() const
{
if (metaData_.HttpMetaData().find("x-oss-copy-source-if-modified-since") != metaData_.HttpMetaData().end()) {
return metaData_.HttpMetaData().at("x-oss-copy-source-if-modified-since");
}
return strEmpty;
}
void MultiCopyObjectRequest::setMetadataDirective(const CopyActionList& action)
{
metaData_.addHeader("x-oss-metadata-directive", ToCopyActionName(action));
}
void MultiCopyObjectRequest::setAcl(const CannedAccessControlList& acl)
{
metaData_.addHeader("x-oss-object-acl", ToAclName(acl));
}
int MultiCopyObjectRequest::validate() const
{
auto ret = OssResumableBaseRequest::validate();
if (ret != 0) {
return ret;
}
return 0;
}
| YifuLiu/AliOS-Things | components/oss/src/resumable/MultiCopyObjectRequest.cc | C++ | apache-2.0 | 6,859 |
/*
* 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 <string>
#include <algorithm>
#ifdef _WIN32
#include <codecvt>
#endif
#include <alibabacloud/oss/Const.h>
#include "ResumableBaseWorker.h"
#include "../utils/FileSystemUtils.h"
#include "utils/Utils.h"
using namespace AlibabaCloud::OSS;
ResumableBaseWorker::ResumableBaseWorker(uint64_t objectSize, uint64_t partSize) :
hasRecord_(false),
objectSize_(objectSize),
consumedSize_(0),
partSize_(partSize)
{
}
int ResumableBaseWorker::validate(OssError& err)
{
genRecordPath();
if (hasRecordPath()) {
if (0 != loadRecord()) {
removeRecordFile();
}
}
if (hasRecord_) {
if (0 != validateRecord()) {
removeRecordFile();
if (0 != prepare(err)) {
return -1;
}
}
}
else {
if (0 != prepare(err)) {
return -1;
}
}
return 0;
}
void ResumableBaseWorker::determinePartSize()
{
uint64_t partSize = partSize_;
uint64_t objectSize = objectSize_;
uint64_t partCount = (objectSize - 1) / partSize + 1;
while (partCount > PartNumberUpperLimit) {
partSize = partSize * 2;
partCount = (objectSize - 1) / partSize + 1;
}
partSize_ = partSize;
}
bool ResumableBaseWorker::hasRecordPath()
{
return !(recordPath_.empty() && recordPathW_.empty());
}
void ResumableBaseWorker::removeRecordFile()
{
if (!recordPath_.empty()) {
RemoveFile(recordPath_);
}
#ifdef _WIN32
if (!recordPathW_.empty()) {
RemoveFile(recordPathW_);
}
#endif
}
#ifdef _WIN32
std::string ResumableBaseWorker::toString(const std::wstring& str)
{
std::wstring_convert<std::codecvt_utf8<wchar_t>> conv;
return conv.to_bytes(str);
}
std::wstring ResumableBaseWorker::toWString(const std::string& str)
{
std::wstring_convert<std::codecvt_utf8<wchar_t>> conv;
return conv.from_bytes(str);
}
#else
std::string ResumableBaseWorker::toString(const std::wstring& str)
{
UNUSED_PARAM(str);
return "";
}
std::wstring ResumableBaseWorker::toWString(const std::string& str)
{
UNUSED_PARAM(str);
return L"";
}
#endif
| YifuLiu/AliOS-Things | components/oss/src/resumable/ResumableBaseWorker.cc | C++ | apache-2.0 | 2,780 |
/*
* 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 <fstream>
#include <mutex>
#include <alibabacloud/oss/OssError.h>
#include <alibabacloud/oss/OssRequest.h>
#include "../OssClientImpl.h"
namespace AlibabaCloud
{
namespace OSS
{
class ResumableBaseWorker
{
public:
ResumableBaseWorker(uint64_t objectSize, uint64_t partSize);
protected:
virtual int validate(OssError& err);
virtual void determinePartSize();
virtual void genRecordPath() = 0;
virtual int loadRecord() = 0;
virtual int prepare(OssError& err) = 0;
virtual int validateRecord() = 0;
virtual bool hasRecordPath();
virtual void removeRecordFile();
std::string toString(const std::wstring& str);
std::wstring toWString(const std::string& str);
bool hasRecord_;
std::string recordPath_;
std::wstring recordPathW_;
std::mutex lock_;
uint64_t objectSize_;
uint64_t consumedSize_;
uint64_t partSize_;
};
}
} | YifuLiu/AliOS-Things | components/oss/src/resumable/ResumableBaseWorker.h | C++ | apache-2.0 | 1,629 |
/*
* 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 <algorithm>
#include <set>
#include <alibabacloud/oss/model/UploadPartCopyRequest.h>
#include <alibabacloud/oss/model/InitiateMultipartUploadRequest.h>
#include <alibabacloud/oss/model/CompleteMultipartUploadRequest.h>
#include <alibabacloud/oss/Const.h>
#include "utils/Utils.h"
#include "../utils/LogUtils.h"
#include "../utils/FileSystemUtils.h"
#include "../external/json/json.h"
//#include "OssClientImpl.h"
#include "../model/ModelError.h"
#include "ResumableCopier.h"
using namespace AlibabaCloud::OSS;
CopyObjectOutcome ResumableCopier::Copy()
{
OssError err;
if (0 != validate(err)) {
return CopyObjectOutcome(err);
}
PartList partsToUploadCopy;
PartList partsCopied;
if (getPartsToUploadCopy(err, partsCopied, partsToUploadCopy) != 0) {
return CopyObjectOutcome(err);
}
std::vector<UploadPartCopyOutcome> outcomes;
std::vector<std::thread> threadPool;
for (uint32_t i = 0; i < request_.ThreadNum(); i++) {
threadPool.emplace_back(std::thread([&]() {
Part part;
while (true) {
{
std::lock_guard<std::mutex> lck(lock_);
if (partsToUploadCopy.empty())
break;
part = partsToUploadCopy.front();
partsToUploadCopy.erase(partsToUploadCopy.begin());
}
if (!client_->isEnableRequest())
break;
uint64_t offset = partSize_ * (part.PartNumber() - 1);
uint64_t length = part.Size();
auto uploadPartCopyReq = UploadPartCopyRequest(request_.Bucket(), request_.Key(), request_.SrcBucket(), request_.SrcKey(),
uploadID_, part.PartNumber(),
request_.SourceIfMatchEtag(), request_.SourceIfNotMatchEtag(),
request_.SourceIfModifiedSince(), request_.SourceIfUnModifiedSince());
uploadPartCopyReq.setCopySourceRange(offset, offset + length - 1);
if (request_.RequestPayer() == RequestPayer::Requester) {
uploadPartCopyReq.setRequestPayer(request_.RequestPayer());
}
if (request_.TrafficLimit() != 0) {
uploadPartCopyReq.setTrafficLimit(request_.TrafficLimit());
}
if (!request_.VersionId().empty()) {
uploadPartCopyReq.setVersionId(request_.VersionId());
}
auto outcome = client_->UploadPartCopy(uploadPartCopyReq);
#ifdef ENABLE_OSS_TEST
if (!!(request_.Flags() & 0x40000000) && (part.PartNumber() == 2 || part.PartNumber() == 4)) {
const char* TAG = "ResumableCopyObjectClient";
OSS_LOG(LogLevel::LogDebug, TAG, "NO.%d part data copy failed!", part.PartNumber());
outcome = UploadPartCopyOutcome();
}
#endif // ENABLE_OSS_TEST
//lock
{
std::lock_guard<std::mutex> lck(lock_);
if (outcome.isSuccess()) {
part.eTag_ = outcome.result().ETag();
partsCopied.push_back(part);
}
outcomes.push_back(outcome);
if (outcome.isSuccess()) {
auto process = request_.TransferProgress();
if (process.Handler) {
consumedSize_ += length;
process.Handler((size_t)length, consumedSize_, objectSize_, process.UserData);
}
}
}
}
}));
}
for (auto& worker : threadPool) {
if (worker.joinable()) {
worker.join();
}
}
for (const auto& outcome : outcomes) {
if (!outcome.isSuccess()) {
return CopyObjectOutcome(outcome.error());
}
}
if (!client_->isEnableRequest()) {
return CopyObjectOutcome(OssError("ClientError:100002", "Disable all requests by upper."));
}
// sort partsCopied
std::sort(partsCopied.begin(), partsCopied.end(), [](const Part& a, const Part& b)
{
return a.PartNumber() < b.PartNumber();
});
CompleteMultipartUploadRequest completeMultipartUploadReq(request_.Bucket(), request_.Key(), partsCopied, uploadID_);
if (request_.MetaData().HttpMetaData().find("x-oss-object-acl")
!= request_.MetaData().HttpMetaData().end()) {
std::string aclName = request_.MetaData().HttpMetaData().at("x-oss-object-acl");
completeMultipartUploadReq.setAcl(ToAclType(aclName.c_str()));
}
if (!request_.EncodingType().empty()) {
completeMultipartUploadReq.setEncodingType(request_.EncodingType());
}
if (request_.RequestPayer() == RequestPayer::Requester) {
completeMultipartUploadReq.setRequestPayer(request_.RequestPayer());
}
auto compOutcome = client_->CompleteMultipartUpload(completeMultipartUploadReq);
if (!compOutcome.isSuccess()) {
return CopyObjectOutcome(compOutcome.error());
}
removeRecordFile();
CopyObjectResult result;
HeadObjectRequest hRequest(request_.Bucket(), request_.Key());
if (request_.RequestPayer() == RequestPayer::Requester) {
hRequest.setRequestPayer(request_.RequestPayer());
}
if (!compOutcome.result().VersionId().empty()) {
hRequest.setVersionId(compOutcome.result().VersionId());
}
auto hOutcome = client_->HeadObject(HeadObjectRequest(hRequest));
if (hOutcome.isSuccess()) {
result.setLastModified(hOutcome.result().LastModified());
}
result.setEtag(compOutcome.result().ETag());
result.setRequestId(compOutcome.result().RequestId());
result.setVersionId(compOutcome.result().VersionId());
return CopyObjectOutcome(result);
}
int ResumableCopier::prepare(OssError& err)
{
determinePartSize();
ObjectMetaData metaData(request_.MetaData());
if (metaData.HttpMetaData().find("x-oss-metadata-directive") == metaData.HttpMetaData().end() ||
(metaData.HttpMetaData().find("x-oss-metadata-directive") != metaData.HttpMetaData().end() &&
metaData.HttpMetaData().at("x-oss-metadata-directive") == "COPY")) {
HeadObjectRequest hRequest(request_.SrcBucket(), request_.SrcKey());
if (request_.RequestPayer() == RequestPayer::Requester) {
hRequest.setRequestPayer(request_.RequestPayer());
}
if (!request_.VersionId().empty()) {
hRequest.setVersionId(request_.VersionId());
}
auto headObjectOutcome = client_->HeadObject(hRequest);
if (!headObjectOutcome.isSuccess()) {
err = headObjectOutcome.error();
return -1;
}
auto& meta = metaData.UserMetaData();
meta = headObjectOutcome.result().UserMetaData();
}
auto initMultipartUploadReq = InitiateMultipartUploadRequest(request_.Bucket(), request_.Key(), metaData);
if (!request_.EncodingType().empty()) {
initMultipartUploadReq.setEncodingType(request_.EncodingType());
}
if (request_.RequestPayer() == RequestPayer::Requester) {
initMultipartUploadReq.setRequestPayer(request_.RequestPayer());
}
auto outcome = client_->InitiateMultipartUpload(initMultipartUploadReq);
if (!outcome.isSuccess()) {
err = outcome.error();
return -1;
}
//init record_
uploadID_ = outcome.result().UploadId();
if (hasRecordPath()) {
initRecord(uploadID_);
Json::Value root;
root["opType"] = record_.opType;
root["uploadID"] = record_.uploadID;
root["srcBucket"] = record_.srcBucket;
root["srcKey"] = record_.srcKey;
root["bucket"] = record_.bucket;
root["key"] = record_.key;
root["mtime"] = record_.mtime;
root["size"] = record_.size;
root["partSize"] = record_.partSize;
std::stringstream ss;
ss << root;
std::string md5Sum = ComputeContentETag(ss);
root["md5Sum"] = md5Sum;
auto recordStream = GetFstreamByPath(recordPath_, recordPathW_, std::ios::out);
if (recordStream->is_open()) {
*recordStream << root;
recordStream->close();
}
}
return 0;
}
int ResumableCopier::validateRecord()
{
auto record = record_;
if (record.size != objectSize_ || record.mtime != request_.ObjectMtime()) {
return ARG_ERROR_COPY_SRC_OBJECT_MODIFIED;
}
Json::Value root;
root["opType"] = record.opType;
root["uploadID"] = record.uploadID;
root["srcBucket"] = record.srcBucket;
root["srcKey"] = record.srcKey;
root["bucket"] = record.bucket;
root["key"] = record.key;
root["mtime"] = record.mtime;
root["size"] = record.size;
root["partSize"] = record.partSize;
std::stringstream recordStream;
recordStream << root;
std::string md5Sum = ComputeContentETag(recordStream);
if (md5Sum != record.md5Sum) {
return ARG_ERROR_COPY_RECORD_INVALID;
}
return 0;
}
int ResumableCopier::loadRecord()
{
if (hasRecordPath()) {
auto recordStream = GetFstreamByPath(recordPath_, recordPathW_, std::ios::in);
if (recordStream->is_open()) {
Json::Value root;
Json::CharReaderBuilder rbuilder;
std::string errMsg;
if (!Json::parseFromStream(rbuilder, *recordStream, &root, &errMsg))
{
return ARG_ERROR_PARSE_COPY_RECORD_FILE;
}
record_.opType = root["opType"].asString();
record_.uploadID = root["uploadID"].asString();
record_.srcBucket = root["srcBucket"].asString();
record_.srcKey = root["srcKey"].asString();
record_.bucket = root["bucket"].asString();
record_.key = root["key"].asString();
record_.size = root["size"].asUInt64();
record_.mtime = root["mtime"].asString();
record_.partSize = root["partSize"].asUInt64();
record_.md5Sum = root["md5Sum"].asString();
partSize_ = record_.partSize;
uploadID_ = record_.uploadID;
hasRecord_ = true;
recordStream->close();
}
}
return 0;
}
void ResumableCopier::genRecordPath()
{
recordPath_ = "";
recordPathW_ = L"";
if (!request_.hasCheckpointDir()) {
return;
}
std::stringstream ss;
ss << "oss://" << request_.SrcBucket() << "/" << request_.SrcKey();
if (!request_.VersionId().empty()) {
ss << "?versionId=" << request_.VersionId();
}
auto srcPath = ss.str();
ss.str("");
ss << "oss://" << request_.Bucket() << "/" << request_.Key();
auto destPath = ss.str();
auto safeFileName = ComputeContentETag(srcPath) + "--" + ComputeContentETag(destPath);
if (!request_.CheckpointDirW().empty()) {
recordPathW_ = request_.CheckpointDirW() + WPATH_DELIMITER + toWString(safeFileName);
}
else {
recordPath_ = request_.CheckpointDir() + PATH_DELIMITER + safeFileName;
}
}
int ResumableCopier::getPartsToUploadCopy(OssError &err, PartList &partsCopied, PartList &partsToUploadCopy)
{
std::set<uint64_t> partNumbersUploaded;
if (hasRecord_) {
uint32_t marker = 0;
auto listPartsRequest = ListPartsRequest(request_.Bucket(), request_.Key(), uploadID_);
if (!request_.EncodingType().empty()) {
listPartsRequest.setEncodingType(request_.EncodingType());
}
if (request_.RequestPayer() == RequestPayer::Requester) {
listPartsRequest.setRequestPayer(request_.RequestPayer());
}
while (true) {
listPartsRequest.setPartNumberMarker(marker);
auto outcome = client_->ListParts(listPartsRequest);
if (!outcome.isSuccess()) {
err = outcome.error();
return -1;
}
auto parts = outcome.result().PartList();
for (auto iter = parts.begin(); iter != parts.end(); iter++) {
partNumbersUploaded.insert(iter->PartNumber());
partsCopied.emplace_back(*iter);
consumedSize_ += iter->Size();
}
if (outcome.result().IsTruncated()) {
marker = outcome.result().NextPartNumberMarker();
}
else {
break;
}
}
}
int32_t partCount = (int32_t)((objectSize_ - 1) / partSize_ + 1);
for (int32_t i = 0; i < partCount; i++) {
Part part;
part.partNumber_ = i + 1;
if (i == partCount - 1) {
part.size_ = objectSize_ - partSize_ * (partCount - 1);
}
else {
part.size_ = partSize_;
}
auto iterNum = partNumbersUploaded.find(part.PartNumber());
if (iterNum == partNumbersUploaded.end()) {
partsToUploadCopy.push_back(part);
}
}
return 0;
}
void ResumableCopier::initRecord(const std::string &uploadID)
{
record_.opType = "ResumableCopy";
record_.uploadID = uploadID;
record_.srcBucket = request_.SrcBucket();
record_.srcKey = request_.SrcKey();
record_.bucket = request_.Bucket();
record_.key = request_.Key();
record_.mtime = request_.ObjectMtime();
record_.size = objectSize_;
record_.partSize = partSize_;
}
| YifuLiu/AliOS-Things | components/oss/src/resumable/ResumableCopier.cc | C++ | apache-2.0 | 14,174 |
/*
* 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 "ResumableBaseWorker.h"
namespace AlibabaCloud
{
namespace OSS
{
struct MultiCopyRecord {
std::string opType;
std::string uploadID;
std::string srcBucket;
std::string srcKey;
std::string bucket;
std::string key;
std::string mtime;
uint64_t size;
uint64_t partSize;
std::string md5Sum;
};
class ResumableCopier : public ResumableBaseWorker
{
public:
ResumableCopier(const MultiCopyObjectRequest &request, const OssClientImpl *client, uint64_t objectSize)
:ResumableBaseWorker(objectSize, request.PartSize()), request_(request), client_(client)
{
}
CopyObjectOutcome Copy();
protected:
void genRecordPath();
int loadRecord();
int validateRecord();
int prepare(OssError& err);
void initRecord(const std::string &uploadID);
int getPartsToUploadCopy(OssError &err, PartList &partsCopied, PartList &partsToUpload);
const MultiCopyObjectRequest request_;
MultiCopyRecord record_;
const OssClientImpl *client_;
std::string uploadID_;
};
}
}
| YifuLiu/AliOS-Things | components/oss/src/resumable/ResumableCopier.h | C++ | apache-2.0 | 1,874 |
/*
* 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 <algorithm>
#include <set>
#include <alibabacloud/oss/Const.h>
#include "utils/Utils.h"
#include "utils/Crc64.h"
#include "../utils/LogUtils.h"
#include "../utils/FileSystemUtils.h"
#include "../external/json/json.h"
//#include "OssClientImpl.h"
#include "ResumableDownloader.h"
#include "../model/ModelError.h"
using namespace AlibabaCloud::OSS;
GetObjectOutcome ResumableDownloader::Download()
{
OssError err;
if (0 != validate(err)) {
return GetObjectOutcome(err);
}
PartRecordList partsToDownload;
if (getPartsToDownload(err, partsToDownload) != 0) {
return GetObjectOutcome(err);
}
//task queue
PartRecordList downloadedParts;
if (hasRecord_) {
downloadedParts = record_.parts;
}
std::vector<GetObjectOutcome> outcomes;
std::vector<std::thread> threadPool;
for (uint32_t i = 0; i < request_.ThreadNum(); i++) {
threadPool.emplace_back(std::thread([&]() {
PartRecord part;
while (true) {
{
std::lock_guard<std::mutex> lck(lock_);
if (partsToDownload.empty())
break;
part = partsToDownload.front();
partsToDownload.erase(partsToDownload.begin());
}
if (!client_->isEnableRequest())
break;
uint64_t pos = partSize_ * (part.partNumber - 1);
uint64_t start = part.offset;
uint64_t end = start + part.size - 1;
auto getObjectReq = GetObjectRequest(request_.Bucket(), request_.Key(), request_.ModifiedSinceConstraint(), request_.UnmodifiedSinceConstraint(),
request_.MatchingETagsConstraint(), request_.NonmatchingETagsConstraint(), request_.ResponseHeaderParameters());
getObjectReq.setResponseStreamFactory([=]() {
auto tmpFstream = GetFstreamByPath(request_.TempFilePath(), request_.TempFilePathW(),
std::ios_base::in | std::ios_base::out | std::ios_base::binary);
tmpFstream->seekp(pos, tmpFstream->beg);
return tmpFstream;
});
getObjectReq.setRange(start, end);
getObjectReq.setFlags(getObjectReq.Flags() | REQUEST_FLAG_CHECK_CRC64 | REQUEST_FLAG_SAVE_CLIENT_CRC64);
auto process = request_.TransferProgress();
if (process.Handler) {
TransferProgress uploadPartProcess = { DownloadPartProcessCallback, (void *)this };
getObjectReq.setTransferProgress(uploadPartProcess);
}
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());
}
auto outcome = GetObjectWrap(getObjectReq);
#ifdef ENABLE_OSS_TEST
if (!!(request_.Flags() & 0x40000000) && part.partNumber == 2) {
const char* TAG = "ResumableDownloadObjectClient";
OSS_LOG(LogLevel::LogDebug, TAG, "NO.2 part data download failed.");
outcome = GetObjectOutcome();
}
#endif // ENABLE_OSS_TEST
// lock
{
std::lock_guard<std::mutex> lck(lock_);
if (outcome.isSuccess()) {
part.crc64 = std::strtoull(outcome.result().Metadata().HttpMetaData().at("x-oss-hash-crc64ecma-by-client").c_str(), nullptr, 10);
downloadedParts.push_back(part);
}
outcomes.push_back(outcome);
//update record
if (hasRecordPath() && outcome.isSuccess()) {
auto &record = record_;
record.parts = downloadedParts;
Json::Value root;
root["opType"] = record.opType;
root["bucket"] = record.bucket;
root["key"] = record.key;
root["filePath"] = record.filePath;
root["mtime"] = record.mtime;
root["size"] = record.size;
root["partSize"] = record.partSize;
int index = 0;
for (PartRecord& partR : record.parts) {
root["parts"][index]["partNumber"] = partR.partNumber;
root["parts"][index]["size"] = partR.size;
root["parts"][index]["crc64"] = partR.crc64;
index++;
}
std::stringstream ss;
ss << root;
std::string md5Sum = ComputeContentETag(ss);
root["md5Sum"] = md5Sum;
if (request_.RangeIsSet()) {
root["rangeStart"] = record.rangeStart;
root["rangeEnd"] = record.rangeEnd;
}
auto recordStream = GetFstreamByPath(recordPath_, recordPathW_, std::ios::out);
if (recordStream->is_open()) {
*recordStream << root;
recordStream->close();
}
}
}
}
}));
}
for (auto& worker : threadPool) {
if (worker.joinable()) {
worker.join();
}
}
std::shared_ptr<std::iostream> content = nullptr;
for (auto& outcome : outcomes) {
if (!outcome.isSuccess()) {
return GetObjectOutcome(outcome.error());
}
outcome.result().setContent(content);
}
if (!client_->isEnableRequest()) {
return GetObjectOutcome(OssError("ClientError:100002", "Disable all requests by upper."));
}
// sort
std::sort(downloadedParts.begin(), downloadedParts.end(), [&](const PartRecord& a, const PartRecord& b)
{
return a.partNumber < b.partNumber;
});
ObjectMetaData meta;
if (outcomes.empty()) {
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());
}
meta = hOutcome.result();
}
else {
meta = outcomes[0].result().Metadata();
}
meta.setContentLength(contentLength_);
//check crc and update metadata
if (!request_.RangeIsSet()) {
if (client_->configuration().enableCrc64) {
uint64_t localCRC64 = downloadedParts[0].crc64;
for (size_t i = 1; i < downloadedParts.size(); i++) {
localCRC64 = CRC64::CombineCRC(localCRC64, downloadedParts[i].crc64, downloadedParts[i].size);
}
if (localCRC64 != outcomes[0].result().Metadata().CRC64()) {
return GetObjectOutcome(OssError("CrcCheckError", "ResumableDownload object CRC checksum fail."));
}
}
meta.HttpMetaData().erase(Http::CONTENT_RANGE);
}
else {
std::stringstream ss;
ss << "bytes " << request_.RangeStart() << "-";
if (request_.RangeEnd() != -1) {
ss << request_.RangeEnd() << "/" << objectSize_;
}
else {
ss << (objectSize_ - 1) << "/" << objectSize_;
}
meta.HttpMetaData()["Content-Range"] = ss.str();
}
if (meta.HttpMetaData().find("x-oss-hash-crc64ecma-by-client") != meta.HttpMetaData().end()) {
meta.HttpMetaData().erase("x-oss-hash-crc64ecma-by-client");
}
if (!renameTempFile()) {
std::stringstream ss;
ss << "rename temp file failed";
return GetObjectOutcome(OssError("RenameError", ss.str()));
}
removeRecordFile();
GetObjectResult result(request_.Bucket(), request_.Key(), meta);
return GetObjectOutcome(result);
}
int ResumableDownloader::prepare(OssError& err)
{
UNUSED_PARAM(err);
determinePartSize();
if (hasRecordPath()) {
initRecord();
Json::Value root;
root["opType"] = record_.opType;
root["bucket"] = record_.bucket;
root["key"] = record_.key;
root["filePath"] = record_.filePath;
root["mtime"] = record_.mtime;
root["size"] = record_.size;
root["partSize"] = record_.partSize;
root["parts"].resize(0);
std::stringstream ss;
ss << root;
std::string md5Sum = ComputeContentETag(ss);
root["md5Sum"] = md5Sum;
if (request_.RangeIsSet()) {
root["rangeStart"] = record_.rangeStart;
root["rangeEnd"] = record_.rangeEnd;
}
auto recordStream = GetFstreamByPath(recordPath_, recordPathW_, std::ios::out);
if (recordStream->is_open()) {
*recordStream << root;
recordStream->close();
}
}
return 0;
}
int ResumableDownloader::validateRecord()
{
auto record = record_;
if (record.size != objectSize_ || record.mtime != request_.ObjectMtime()) {
return ARG_ERROR_DOWNLOAD_OBJECT_MODIFIED;
}
if (request_.RangeIsSet()) {
if (record.rangeStart != request_.RangeStart() || record.rangeEnd != request_.RangeEnd()) {
return ARG_ERROR_RANGE_HAS_BEEN_RESET;
}
}
Json::Value root;
root["opType"] = record.opType;
root["bucket"] = record.bucket;
root["key"] = record.key;
root["filePath"] = record.filePath;
root["mtime"] = record.mtime;
root["size"] = record.size;
root["partSize"] = record.partSize;
root["parts"].resize(0);
int index = 0;
for (PartRecord& part : record.parts) {
root["parts"][index]["partNumber"] = part.partNumber;
root["parts"][index]["size"] = part.size;
root["parts"][index]["crc64"] = part.crc64;
index++;
}
if (!(record.rangeStart == 0 && record.rangeEnd == -1)) {
root["rangeStart"] = record.rangeStart;
root["rangeEnd"] = record.rangeEnd;
}
std::stringstream recordStream;
recordStream << root;
std::string md5Sum = ComputeContentETag(recordStream);
if (md5Sum != record.md5Sum) {
return -1;
}
return 0;
}
int ResumableDownloader::loadRecord()
{
auto recordStream = GetFstreamByPath(recordPath_, recordPathW_, std::ios::in);
if (recordStream->is_open()) {
Json::Value root;
Json::CharReaderBuilder rbuilder;
std::string errMsg;
if (!Json::parseFromStream(rbuilder, *recordStream, &root, &errMsg))
{
return ARG_ERROR_PARSE_DOWNLOAD_RECORD_FILE;
}
record_.opType = root["opType"].asString();
record_.bucket = root["bucket"].asString();
record_.key = root["key"].asString();
record_.filePath = root["filePath"].asString();
record_.mtime = root["mtime"].asString();
record_.size = root["size"].asUInt64();
record_.partSize = root["partSize"].asUInt64();
PartRecord part;
for (uint32_t i = 0; i < root["parts"].size(); i++) {
Json::Value partValue = root["parts"][i];
part.partNumber = partValue["partNumber"].asInt();
part.size = partValue["size"].asInt64();
part.crc64 = partValue["crc64"].asUInt64();
record_.parts.push_back(part);
}
record_.md5Sum = root["md5Sum"].asString();
if (root["rangeStart"] != Json::nullValue && root["rangeEnd"] != Json::nullValue) {
record_.rangeStart = root["rangeStart"].asInt64();
record_.rangeEnd = root["rangeEnd"].asInt64();
}
else if(root["rangeStart"] == Json::nullValue && root["rangeEnd"] == Json::nullValue){
record_.rangeStart = 0;
record_.rangeEnd = -1;
}else {
return ARG_ERROR_INVALID_RANGE_IN_DWONLOAD_RECORD;
}
partSize_ = record_.partSize;
hasRecord_ = true;
recordStream->close();
}
return 0;
}
void ResumableDownloader::genRecordPath()
{
recordPath_ = "";
recordPathW_ = L"";
if (!request_.hasCheckpointDir())
return;
std::stringstream ss;
ss << "oss://" << request_.Bucket() << "/" << request_.Key();
if (!request_.VersionId().empty()) {
ss << "?versionId=" << request_.VersionId();
}
auto srcPath = ss.str();
auto destPath = !request_.FilePathW().empty() ? toString(request_.FilePathW()) : request_.FilePath();
auto safeFileName = ComputeContentETag(srcPath) + "--" + ComputeContentETag(destPath);
if (!request_.CheckpointDirW().empty()) {
recordPathW_ = request_.CheckpointDirW() + WPATH_DELIMITER + toWString(safeFileName);;
}
else {
recordPath_ = request_.CheckpointDir() + PATH_DELIMITER + safeFileName;
}
}
int ResumableDownloader::getPartsToDownload(OssError &err, PartRecordList &partsToDownload)
{
UNUSED_PARAM(err);
std::set<uint64_t> partNumbersDownloaded;
if (hasRecord_) {
for (PartRecord &part : record_.parts) {
partNumbersDownloaded.insert(part.partNumber);
consumedSize_ += part.size;
}
}
int64_t start = 0;
int64_t end = objectSize_ - 1;
if (request_.RangeIsSet()) {
start = request_.RangeStart();
end = request_.RangeEnd();
if (end == -1) {
end = objectSize_ - 1;
}
contentLength_ = end - start + 1;
}
int32_t index = 1;
for (int64_t offset = start; offset < end + 1; offset += partSize_, index++) {
PartRecord part;
part.partNumber = index;
part.offset = offset;
if (offset + (int64_t)partSize_ > end) {
part.size = end - offset + 1;
}
else {
part.size = partSize_;
}
auto iterNum = partNumbersDownloaded.find(part.partNumber);
if (iterNum == partNumbersDownloaded.end()) {
partsToDownload.push_back(part);
}
}
return 0;
}
void ResumableDownloader::initRecord()
{
auto filePath = request_.FilePath();
if (!request_.FilePathW().empty()) {
filePath = toString(request_.FilePathW());
}
record_.opType = "ResumableDownload";
record_.bucket = request_.Bucket();
record_.key = request_.Key();
record_.filePath = filePath;
record_.mtime = request_.ObjectMtime();
record_.size = objectSize_;
record_.partSize = partSize_;
//in this place we shuold consider the condition that range is not set
if (request_.RangeIsSet()) {
record_.rangeStart = request_.RangeStart();
record_.rangeEnd = request_.RangeEnd();
}
else {
record_.rangeStart = 0;
record_.rangeEnd = -1;
}
}
void ResumableDownloader::DownloadPartProcessCallback(size_t increment, int64_t transfered, int64_t total, void *userData)
{
UNUSED_PARAM(transfered);
UNUSED_PARAM(total);
auto downloader = (ResumableDownloader*)userData;
std::lock_guard<std::mutex> lck(downloader->lock_);
downloader->consumedSize_ += increment;
auto process = downloader->request_.TransferProgress();
if (process.Handler) {
process.Handler(increment, downloader->consumedSize_, downloader->contentLength_, process.UserData);
}
}
bool ResumableDownloader::renameTempFile()
{
#ifdef _WIN32
if (!request_.TempFilePathW().empty()) {
return RenameFile(request_.TempFilePathW(), request_.FilePathW());
}
else
#endif
{
return RenameFile(request_.TempFilePath(), request_.FilePath());
}
}
GetObjectOutcome ResumableDownloader::GetObjectWrap(const GetObjectRequest &request) const
{
return client_->GetObject(request);
}
| YifuLiu/AliOS-Things | components/oss/src/resumable/ResumableDownloader.cc | C++ | apache-2.0 | 17,623 |
#pragma once
/*
* 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 "ResumableBaseWorker.h"
namespace AlibabaCloud
{
namespace OSS
{
struct PartRecord {
int32_t partNumber;
int64_t offset;
int64_t size;
uint64_t crc64;
};
typedef std::vector<PartRecord> PartRecordList;
struct DownloadRecord {
std::string opType;
std::string bucket;
std::string key;
std::string filePath;
std::string mtime;
uint64_t size;
uint64_t partSize;
PartRecordList parts;
std::string md5Sum;
int64_t rangeStart;
int64_t rangeEnd;
//crc64
};
class ResumableDownloader : public ResumableBaseWorker
{
public:
ResumableDownloader(const DownloadObjectRequest& request, const OssClientImpl *client, uint64_t objectSize)
: ResumableBaseWorker(objectSize, request.PartSize()), request_(request),client_(client), contentLength_(objectSize)
{}
GetObjectOutcome Download();
protected:
void genRecordPath();
int loadRecord();
int validateRecord();
int prepare(OssError& err);
void initRecord();
int getPartsToDownload(OssError &err, PartRecordList &partsToDownload);
bool renameTempFile();
static void DownloadPartProcessCallback(size_t increment, int64_t transfered, int64_t total, void *userData);
virtual GetObjectOutcome GetObjectWrap(const GetObjectRequest &request) const;
const DownloadObjectRequest request_;
DownloadRecord record_;
const OssClientImpl *client_;
uint64_t contentLength_;
};
}
}
| YifuLiu/AliOS-Things | components/oss/src/resumable/ResumableDownloader.h | C++ | apache-2.0 | 2,274 |
/*
* 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/UploadObjectRequest.h>
#include <alibabacloud/oss/model/InitiateMultipartUploadRequest.h>
#include <alibabacloud/oss/model/CompleteMultipartUploadRequest.h>
#include <alibabacloud/oss/OssFwd.h>
#include <alibabacloud/oss/Const.h>
#include <sstream>
#include <fstream>
#include <algorithm>
#include <iostream>
#include <set>
#include "../external/json/json.h"
#include "../utils/FileSystemUtils.h"
#include "utils/Utils.h"
#include "../utils/LogUtils.h"
#include "utils/Crc64.h"
#include "../OssClientImpl.h"
#include "../model/ModelError.h"
#include "ResumableUploader.h"
using namespace AlibabaCloud::OSS;
ResumableUploader::ResumableUploader(const UploadObjectRequest& request, const OssClientImpl *client) :
ResumableBaseWorker(request.ObjectSize(), request.PartSize()),
request_(request),
client_(client)
{
if (!request.FilePath().empty()) {
time_t lastMtime;
std::streamsize fileSize;
if (GetPathInfo(request.FilePath(), lastMtime, fileSize)) {
objectSize_ = static_cast<uint64_t>(fileSize);
}
}
#ifdef _WIN32
else if (!request.FilePathW().empty()) {
time_t lastMtime;
std::streamsize fileSize;
if (GetPathInfo(request.FilePathW(), lastMtime, fileSize)) {
objectSize_ = static_cast<uint64_t>(fileSize);
}
}
#endif
}
PutObjectOutcome ResumableUploader::Upload()
{
OssError err;
if (0 != validate(err)) {
return PutObjectOutcome(err);
}
PartList partsToUpload;
PartList uploadedParts;
if (getPartsToUpload(err, uploadedParts, partsToUpload) != 0){
return PutObjectOutcome(err);
}
std::vector<PutObjectOutcome> outcomes;
std::vector<std::thread> threadPool;
for (uint32_t i = 0; i < request_.ThreadNum(); i++) {
threadPool.emplace_back(std::thread([&]() {
Part part;
while (true) {
{
std::lock_guard<std::mutex> lck(lock_);
if (partsToUpload.empty())
break;
part = partsToUpload.front();
partsToUpload.erase(partsToUpload.begin());
}
if (!client_->isEnableRequest())
break;
uint64_t offset = partSize_ * (part.PartNumber() - 1);
uint64_t length = part.Size();
auto content = GetFstreamByPath(request_.FilePath(), request_.FilePathW(),
std::ios::in | std::ios::binary);
content->seekg(offset, content->beg);
UploadPartRequest uploadPartRequest(request_.Bucket(), request_.Key(), part.PartNumber(), uploadID_, content);
uploadPartRequest.setContentLength(length);
auto process = request_.TransferProgress();
if (process.Handler) {
TransferProgress uploadPartProcess = { UploadPartProcessCallback, (void *)this };
uploadPartRequest.setTransferProgress(uploadPartProcess);
}
if (request_.RequestPayer() == RequestPayer::Requester) {
uploadPartRequest.setRequestPayer(request_.RequestPayer());
}
if (request_.TrafficLimit() != 0) {
uploadPartRequest.setTrafficLimit(request_.TrafficLimit());
}
auto outcome = UploadPartWrap(uploadPartRequest);
#ifdef ENABLE_OSS_TEST
if (!!(request_.Flags() & 0x40000000) && part.PartNumber() == 2) {
const char* TAG = "ResumableUploadObjectClient";
OSS_LOG(LogLevel::LogDebug, TAG, "NO.2 part data upload failed.");
outcome = PutObjectOutcome();
}
#endif // ENABLE_OSS_TEST
if (outcome.isSuccess()) {
part.eTag_ = outcome.result().ETag();
part.cRC64_ = outcome.result().CRC64();
}
//lock
{
std::lock_guard<std::mutex> lck(lock_);
uploadedParts.push_back(part);
outcomes.push_back(outcome);
}
}
}));
}
for (auto& worker:threadPool) {
if(worker.joinable()){
worker.join();
}
}
if (!client_->isEnableRequest()) {
return PutObjectOutcome(OssError("ClientError:100002", "Disable all requests by upper."));
}
for (const auto& outcome : outcomes) {
if (!outcome.isSuccess()) {
return PutObjectOutcome(outcome.error());
}
}
// sort uploadedParts
std::sort(uploadedParts.begin(), uploadedParts.end(), [&](const Part& a, const Part& b)
{
return a.PartNumber() < b.PartNumber();
});
CompleteMultipartUploadRequest completeMultipartUploadReq(request_.Bucket(), request_.Key(), uploadedParts, uploadID_);
if (request_.MetaData().hasHeader("x-oss-object-acl")) {
completeMultipartUploadReq.MetaData().HttpMetaData()["x-oss-object-acl"] =
request_.MetaData().HttpMetaData().at("x-oss-object-acl");
}
if (!request_.EncodingType().empty()) {
completeMultipartUploadReq.setEncodingType(request_.EncodingType());
}
if (request_.MetaData().hasHeader("x-oss-callback")) {
completeMultipartUploadReq.MetaData().HttpMetaData()["x-oss-callback"] =
request_.MetaData().HttpMetaData().at("x-oss-callback");
if (request_.MetaData().hasHeader("x-oss-callback-var")) {
completeMultipartUploadReq.MetaData().HttpMetaData()["x-oss-callback-var"] =
request_.MetaData().HttpMetaData().at("x-oss-callback-var");
}
if (request_.MetaData().hasHeader("x-oss-pub-key-url")) {
completeMultipartUploadReq.MetaData().HttpMetaData()["x-oss-pub-key-url"] =
request_.MetaData().HttpMetaData().at("x-oss-pub-key-url");
}
}
if (request_.RequestPayer() == RequestPayer::Requester) {
completeMultipartUploadReq.setRequestPayer(request_.RequestPayer());
}
auto outcome = CompleteMultipartUploadWrap(completeMultipartUploadReq);
if (!outcome.isSuccess()) {
return PutObjectOutcome(outcome.error());
}
// crc
uint64_t localCRC64 = uploadedParts[0].CRC64();
for (size_t i = 1; i < uploadedParts.size(); i++) {
localCRC64 = CRC64::CombineCRC(localCRC64, uploadedParts[i].CRC64(), uploadedParts[i].Size());
}
uint64_t ossCRC64 = outcome.result().CRC64();
if (ossCRC64 != 0 && localCRC64 != ossCRC64) {
return PutObjectOutcome(OssError("CrcCheckError", "ResumableUpload Object CRC Checksum fail."));
}
removeRecordFile();
HeaderCollection headers;
headers[Http::ETAG] = outcome.result().ETag();
headers["x-oss-hash-crc64ecma"] = std::to_string(outcome.result().CRC64());
headers["x-oss-request-id"] = outcome.result().RequestId();
if (!outcome.result().VersionId().empty()) {
headers["x-oss-version-id"] = outcome.result().VersionId();
}
return PutObjectOutcome(PutObjectResult(headers, outcome.result().Content()));
}
int ResumableUploader::prepare(OssError& err)
{
determinePartSize();
auto initMultipartUploadReq = InitiateMultipartUploadRequest(request_.Bucket(), request_.Key(), request_.MetaData());
if (!request_.EncodingType().empty()) {
initMultipartUploadReq.setEncodingType(request_.EncodingType());
}
if (request_.RequestPayer() == RequestPayer::Requester) {
initMultipartUploadReq.setRequestPayer(request_.RequestPayer());
}
auto outcome = InitiateMultipartUploadWrap(initMultipartUploadReq);
if(!outcome.isSuccess()){
err = outcome.error();
return -1;
}
//init record_
uploadID_ = outcome.result().UploadId();
if (hasRecordPath()) {
Json::Value root;
initRecordInfo();
dumpRecordInfo(root);
std::stringstream ss;
ss << root;
std::string md5Sum = ComputeContentETag(ss);
root["md5Sum"] = md5Sum;
auto recordStream = GetFstreamByPath(recordPath_, recordPathW_, std::ios::out);
if (recordStream->is_open()) {
*recordStream << root;
recordStream->close();
}
}
return 0;
}
int ResumableUploader::validateRecord()
{
if (record_.size != objectSize_ || record_.mtime != request_.ObjectMtime()){
return ARG_ERROR_UPLOAD_FILE_MODIFIED;
}
Json::Value root;
dumpRecordInfo(root);
std::stringstream recordStream;
recordStream << root;
std::string md5Sum = ComputeContentETag(recordStream);
if (md5Sum != record_.md5Sum){
return ARG_ERROR_UPLOAD_RECORD_INVALID;
}
return 0;
}
int ResumableUploader::loadRecord()
{
auto recordStream = GetFstreamByPath(recordPath_, recordPathW_, std::ios::in);
if (recordStream->is_open()){
Json::Value root;
Json::CharReaderBuilder rbuilder;
std::string errMsg;
if (!Json::parseFromStream(rbuilder, *recordStream, &root, &errMsg))
{
return ARG_ERROR_PARSE_UPLOAD_RECORD_FILE;
}
buildRecordInfo(root);
partSize_ = record_.partSize;
uploadID_ = record_.uploadID;
hasRecord_ = true;
recordStream->close();
}
return 0;
}
void ResumableUploader::genRecordPath()
{
recordPath_ = "";
recordPathW_ = L"";
if (!request_.hasCheckpointDir())
return;
auto srcPath = !request_.FilePathW().empty()? toString(request_.FilePathW()): request_.FilePath();
std::stringstream ss;
ss << "oss://" << request_.Bucket() << "/" << request_.Key();
auto destPath = ss.str();
auto safeFileName = ComputeContentETag(srcPath) + "--" + ComputeContentETag(destPath);
if (!request_.CheckpointDirW().empty()) {
recordPathW_ = request_.CheckpointDirW() + WPATH_DELIMITER + toWString(safeFileName);;
}
else {
recordPath_ = request_.CheckpointDir() + PATH_DELIMITER + safeFileName;
}
}
int ResumableUploader::getPartsToUpload(OssError &err, PartList &partsUploaded, PartList &partsToUpload)
{
std::set<uint64_t> partNumbersUploaded;
if(hasRecord_){
uint32_t marker = 0;
auto listPartsRequest = ListPartsRequest(request_.Bucket(), request_.Key(), uploadID_);
if (!request_.EncodingType().empty()) {
listPartsRequest.setEncodingType(request_.EncodingType());
}
if (request_.RequestPayer() == RequestPayer::Requester) {
listPartsRequest.setRequestPayer(request_.RequestPayer());
}
while(true){
listPartsRequest.setPartNumberMarker(marker);
auto outcome = ListPartsWrap(listPartsRequest);
if(!outcome.isSuccess()){
err = outcome.error();
return -1;
}
auto parts = outcome.result().PartList();
for(auto iter = parts.begin(); iter != parts.end(); iter++){
partNumbersUploaded.insert(iter->PartNumber());
partsUploaded.emplace_back(*iter);
consumedSize_ += iter->Size();
}
if(outcome.result().IsTruncated()){
marker = outcome.result().NextPartNumberMarker();
}else{
break;
}
}
}
int32_t partCount = (int32_t)((objectSize_ - 1)/ partSize_ + 1);
for(int32_t i = 0; i < partCount; i++){
Part part;
part.partNumber_ = i+1;
if (i == partCount -1 ){
part.size_ = objectSize_ - partSize_ * (partCount - 1);
}else{
part.size_ = partSize_;
}
auto iterNum = partNumbersUploaded.find(part.PartNumber());
if (iterNum == partNumbersUploaded.end()){
partsToUpload.push_back(part);
}
}
return 0;
}
void ResumableUploader::initRecordInfo()
{
record_.opType = "ResumableUpload";
record_.uploadID = uploadID_;
record_.filePath = request_.FilePath();
record_.bucket = request_.Bucket();
record_.key = request_.Key();
record_.mtime = request_.ObjectMtime();
record_.size = objectSize_;
record_.partSize = partSize_;
}
void ResumableUploader::buildRecordInfo(const AlibabaCloud::OSS::Json::Value& root)
{
record_.opType = root["opType"].asString();
record_.uploadID = root["uploadID"].asString();
record_.filePath = root["filePath"].asString();
record_.bucket = root["bucket"].asString();
record_.key = root["key"].asString();
record_.size = root["size"].asUInt64();
record_.mtime = root["mtime"].asString();
record_.partSize = root["partSize"].asUInt64();
record_.md5Sum = root["md5Sum"].asString();
}
void ResumableUploader::dumpRecordInfo(AlibabaCloud::OSS::Json::Value& root)
{
root["opType"] = record_.opType;
root["uploadID"] = record_.uploadID;
root["filePath"] = record_.filePath;
root["bucket"] = record_.bucket;
root["key"] = record_.key;
root["mtime"] = record_.mtime;
root["size"] = record_.size;
root["partSize"] = record_.partSize;
}
void ResumableUploader::UploadPartProcessCallback(size_t increment, int64_t transfered, int64_t total, void *userData)
{
UNUSED_PARAM(transfered);
UNUSED_PARAM(total);
auto uploader = (ResumableUploader*)userData;
std::lock_guard<std::mutex> lck(uploader->lock_);
uploader->consumedSize_ += increment;
auto process = uploader->request_.TransferProgress();
if (process.Handler) {
process.Handler(increment, uploader->consumedSize_, uploader->objectSize_, process.UserData);
}
}
InitiateMultipartUploadOutcome ResumableUploader::InitiateMultipartUploadWrap(const InitiateMultipartUploadRequest &request) const
{
return client_->InitiateMultipartUpload(request);
}
PutObjectOutcome ResumableUploader::UploadPartWrap(const UploadPartRequest &request) const
{
return client_->UploadPart(request);
}
ListPartsOutcome ResumableUploader::ListPartsWrap(const ListPartsRequest &request) const
{
return client_->ListParts(request);
}
CompleteMultipartUploadOutcome ResumableUploader::CompleteMultipartUploadWrap(const CompleteMultipartUploadRequest &request) const
{
return client_->CompleteMultipartUpload(request);
}
| YifuLiu/AliOS-Things | components/oss/src/resumable/ResumableUploader.cc | C++ | apache-2.0 | 15,480 |
/*
* 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 "ResumableBaseWorker.h"
#include "../external/json/json.h"
namespace AlibabaCloud
{
namespace OSS
{
struct UploadRecord{
std::string opType;
std::string uploadID;
std::string filePath;
std::string bucket;
std::string key;
std::string mtime;
uint64_t size;
uint64_t partSize;
std::string md5Sum;
};
class ResumableUploader : public ResumableBaseWorker
{
public:
ResumableUploader(const UploadObjectRequest& request, const OssClientImpl *client);
PutObjectOutcome Upload();
protected:
virtual InitiateMultipartUploadOutcome InitiateMultipartUploadWrap(const InitiateMultipartUploadRequest &request) const;
virtual PutObjectOutcome UploadPartWrap(const UploadPartRequest &request) const;
virtual ListPartsOutcome ListPartsWrap(const ListPartsRequest &request) const;
virtual CompleteMultipartUploadOutcome CompleteMultipartUploadWrap(const CompleteMultipartUploadRequest &request) const;
virtual void initRecordInfo();
virtual void buildRecordInfo(const AlibabaCloud::OSS::Json::Value& value);
virtual void dumpRecordInfo(AlibabaCloud::OSS::Json::Value& value);
virtual int validateRecord();
private:
int getPartsToUpload(OssError &err, PartList &partsUploaded, PartList &partsToUpload);
virtual void genRecordPath();
virtual int loadRecord();
virtual int prepare(OssError& err);
const UploadObjectRequest& request_;
UploadRecord record_;
const OssClientImpl *client_;
std::string uploadID_;
static void UploadPartProcessCallback(size_t increment, int64_t transfered, int64_t total, void *userData);
};
}
}
| YifuLiu/AliOS-Things | components/oss/src/resumable/ResumableUploader.h | C++ | apache-2.0 | 2,419 |
/*
* 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/UploadObjectRequest.h>
#include <alibabacloud/oss/http/HttpType.h>
#include <alibabacloud/oss/Const.h>
#include <fstream>
#include "utils/Utils.h"
#include "../utils/FileSystemUtils.h"
#include "../model/ModelError.h"
using namespace AlibabaCloud::OSS;
UploadObjectRequest::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):
OssResumableBaseRequest(bucket, key, checkpointDir, partSize, threadNum),
filePath_(filePath)
{
time_t lastMtime;
std::streamsize fileSize;
isFileExist_ = true;
if (!GetPathInfo(filePath_, lastMtime, fileSize)) {
//if fail, ignore the lastmodified time.
lastMtime = 0;
fileSize = 0;
isFileExist_ = false;
}
mtime_ = ToGmtTime(lastMtime);
objectSize_ = static_cast<uint64_t>(fileSize);
}
UploadObjectRequest::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(bucket, key, filePath, checkpointDir, partSize, threadNum)
{
metaData_ = meta;
}
UploadObjectRequest::UploadObjectRequest(const std::string &bucket, const std::string &key,
const std::string &filePath, const std::string &checkpointDir, const ObjectMetaData& meta):
UploadObjectRequest(bucket, key, filePath, checkpointDir, DefaultPartSize, DefaultResumableThreadNum, meta)
{}
UploadObjectRequest::UploadObjectRequest(const std::string &bucket, const std::string &key,
const std::string &filePath, const std::string &checkpointDir) :
UploadObjectRequest(bucket, key, filePath, checkpointDir, DefaultPartSize, DefaultResumableThreadNum)
{}
UploadObjectRequest::UploadObjectRequest(const std::string &bucket, const std::string &key,
const std::string &filePath):
UploadObjectRequest(bucket, key, filePath, "", DefaultPartSize, DefaultResumableThreadNum)
{}
//wstring
UploadObjectRequest::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) :
OssResumableBaseRequest(bucket, key, checkpointDir, partSize, threadNum),
filePathW_(filePath)
{
#ifdef _WIN32
time_t lastMtime;
std::streamsize fileSize;
isFileExist_ = true;
if (!GetPathInfo(filePathW_, lastMtime, fileSize)) {
//if fail, ignore the lastmodified time.
lastMtime = 0;
fileSize = 0;
isFileExist_ = false;
}
mtime_ = ToGmtTime(lastMtime);
objectSize_ = static_cast<uint64_t>(fileSize);
#else
objectSize_ = 0;
time_t lastMtime = 0;
mtime_ = ToGmtTime(lastMtime);
isFileExist_ = false;
#endif
}
UploadObjectRequest::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(bucket, key, filePath, checkpointDir, partSize, threadNum)
{
metaData_ = meta;
}
UploadObjectRequest::UploadObjectRequest(const std::string &bucket, const std::string &key,
const std::wstring &filePath, const std::wstring &checkpointDir, const ObjectMetaData& meta) :
UploadObjectRequest(bucket, key, filePath, checkpointDir, DefaultPartSize, DefaultResumableThreadNum, meta)
{}
UploadObjectRequest::UploadObjectRequest(const std::string &bucket, const std::string &key,
const std::wstring &filePath, const std::wstring &checkpointDir) :
UploadObjectRequest(bucket, key, filePath, checkpointDir, DefaultPartSize, DefaultResumableThreadNum)
{}
UploadObjectRequest::UploadObjectRequest(const std::string &bucket, const std::string &key,
const std::wstring &filePath) :
UploadObjectRequest(bucket, key, filePath, L"", DefaultPartSize, DefaultResumableThreadNum)
{}
void UploadObjectRequest::setAcl(CannedAccessControlList& acl)
{
metaData_.addHeader("x-oss-object-acl", ToAclName(acl));
}
void UploadObjectRequest::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);
}
}
void UploadObjectRequest::setTagging(const std::string& value)
{
metaData_.addHeader("x-oss-tagging", value);
}
int UploadObjectRequest::validate() const
{
auto ret = OssResumableBaseRequest::validate();
if (ret != 0) {
return ret;
}
#if !defined(_WIN32)
if (!filePathW_.empty()) {
return ARG_ERROR_PATH_NOT_SUPPORT_WSTRING_TYPE;
}
#endif
//path and checkpoint must be same type.
if ((!filePath_.empty() && !checkpointDirW_.empty()) ||
(!filePathW_.empty() && !checkpointDir_.empty())) {
return ARG_ERROR_PATH_NOT_SAME_TYPE;
}
if (!isFileExist_) {
return ARG_ERROR_OPEN_UPLOAD_FILE;
}
return 0;
}
| YifuLiu/AliOS-Things | components/oss/src/resumable/UploadObjectRequest.cc | C++ | apache-2.0 | 6,120 |
/* Crc64.cc -- compute CRC-64
* Copyright (C) 2013 Mark Adler
* Version 1.4 16 Dec 2013 Mark Adler
*/
/*
This software is provided 'as-is', without any express or implied
warranty. In no event will the author be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
Mark Adler
madler@alumni.caltech.edu
*/
/* Compute CRC-64 in the manner of xz, using the ECMA-182 polynomial,
bit-reversed, with one's complement pre and post processing. Provide a
means to combine separately computed CRC-64's. */
/* Version history:
1.0 13 Dec 2013 First version
1.1 13 Dec 2013 Fix comments in test code
1.2 14 Dec 2013 Determine endianess at run time
1.3 15 Dec 2013 Add eight-byte processing for big endian as well
Make use of the pthread library optional
1.4 16 Dec 2013 Make once variable volatile for limited thread protection
*/
#include "Crc32.h"
namespace AlibabaCloud
{
namespace OSS
{
/*CRC32*/
static const uint32_t crc32Table[256] = {
0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,
0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,
0xE7B82D07,0x90BF1D91,0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,
0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,
0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,0x3B6E20C8,0x4C69105E,0xD56041E4,
0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,
0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,0x26D930AC,
0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,
0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,
0xB6662D3D,0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,
0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,
0x086D3D2D,0x91646C97,0xE6635C01,0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,
0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA,
0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,0x4DB26158,0x3AB551CE,
0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A,
0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,
0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,
0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,
0xB7BD5C3B,0xC0BA6CAD,0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,
0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,
0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,0xF00F9344,0x8708A3D2,0x1E01F268,
0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,
0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,0xD6D6A3E8,
0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,
0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,
0x4669BE79,0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,
0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,
0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,
0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,
0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,0x86D3D2D4,0xF1D4E242,
0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,
0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,
0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,
0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,
0x47B2CF7F,0x30B5FFE9,0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,
0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,
0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D
};
uint32_t CRC32::CalcCRC(uint32_t crc, const void *buf, size_t bufLen)
{
uint32_t crc32;
unsigned char *byteBuf;
size_t i;
/** accumulate crc32 for buffer **/
crc32 = crc ^ 0xFFFFFFFF;
byteBuf = (unsigned char*)buf;
for (i = 0; i < bufLen; i++) {
crc32 = (crc32 >> 8) ^ crc32Table[(crc32 ^ byteBuf[i]) & 0xFF];
}
return crc32 ^ 0xFFFFFFFF;
}
}
}
| YifuLiu/AliOS-Things | components/oss/src/utils/Crc32.cc | C++ | apache-2.0 | 5,080 |
/*
* 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 <stdint.h>
#include <cstddef>
namespace AlibabaCloud
{
namespace OSS
{
class CRC32
{
public:
static uint32_t CalcCRC(uint32_t crc, const void *buf, size_t bufLen);
};
}
}
| YifuLiu/AliOS-Things | components/oss/src/utils/Crc32.h | C++ | apache-2.0 | 843 |
/* Crc64.cc -- compute CRC-64
* Copyright (C) 2013 Mark Adler
* Version 1.4 16 Dec 2013 Mark Adler
*/
/*
This software is provided 'as-is', without any express or implied
warranty. In no event will the author be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
Mark Adler
madler@alumni.caltech.edu
*/
/* Compute CRC-64 in the manner of xz, using the ECMA-182 polynomial,
bit-reversed, with one's complement pre and post processing. Provide a
means to combine separately computed CRC-64's. */
/* Version history:
1.0 13 Dec 2013 First version
1.1 13 Dec 2013 Fix comments in test code
1.2 14 Dec 2013 Determine endianess at run time
1.3 15 Dec 2013 Add eight-byte processing for big endian as well
Make use of the pthread library optional
1.4 16 Dec 2013 Make once variable volatile for limited thread protection
*/
#include "Crc64.h"
namespace AlibabaCloud
{
namespace OSS
{
/* 64-bit CRC polynomial with these coefficients, but reversed:
64, 62, 57, 55, 54, 53, 52, 47, 46, 45, 40, 39, 38, 37, 35, 33, 32,
31, 29, 27, 24, 23, 22, 21, 19, 17, 13, 12, 10, 9, 7, 4, 1, 0 */
#define POLY UINT64_C(0xc96c5795d7870f42)
/* Tables for CRC calculation -- filled in by initialization functions that are
called once. These could be replaced by constant tables generated in the
same way. There are two tables, one for each endianess. Since these are
static, i.e. local, one should be compiled out of existence if the compiler
can evaluate the endianess check in crc64() at compile time. */
static uint64_t crc64_table[8][256];
/* Fill in the CRC-64 constants table. */
static void crc64_init(uint64_t table[][256])
{
unsigned n, k;
uint64_t crc;
/* generate CRC-64's for all single byte sequences */
for (n = 0; n < 256; n++) {
crc = n;
for (k = 0; k < 8; k++)
crc = crc & 1 ? POLY ^ (crc >> 1) : crc >> 1;
table[0][n] = crc;
}
/* generate CRC-64's for those followed by 1 to 7 zeros */
for (n = 0; n < 256; n++) {
crc = table[0][n];
for (k = 1; k < 8; k++) {
crc = table[0][crc & 0xff] ^ (crc >> 8);
table[k][n] = crc;
}
}
}
/* This function is called once to initialize the CRC-64 table for use on a
little-endian architecture. */
static void crc64_little_init(void)
{
crc64_init(crc64_table);
}
/* Reverse the bytes in a 64-bit word. */
static uint64_t rev8(uint64_t a)
{
uint64_t m;
m = UINT64_C(0xff00ff00ff00ff);
a = ((a >> 8) & m) | (a & m) << 8;
m = UINT64_C(0xffff0000ffff);
a = ((a >> 16) & m) | (a & m) << 16;
return a >> 32 | a << 32;
}
/* This function is called once to initialize the CRC-64 table for use on a
big-endian architecture. */
static void crc64_big_init(void)
{
unsigned k, n;
crc64_init(crc64_table);
for (k = 0; k < 8; k++)
for (n = 0; n < 256; n++)
crc64_table[k][n] = rev8(crc64_table[k][n]);
}
/* Calculate a CRC-64 eight bytes at a time on a little-endian architecture. */
static uint64_t crc64_little(uint64_t crc, void *buf, size_t len)
{
unsigned char *next = (unsigned char *)buf;
crc = ~crc;
while (len && ((uintptr_t)next & 7) != 0) {
crc = crc64_table[0][(crc ^ *next++) & 0xff] ^ (crc >> 8);
len--;
}
while (len >= 8) {
crc ^= *(uint64_t *)next;
crc = crc64_table[7][crc & 0xff] ^
crc64_table[6][(crc >> 8) & 0xff] ^
crc64_table[5][(crc >> 16) & 0xff] ^
crc64_table[4][(crc >> 24) & 0xff] ^
crc64_table[3][(crc >> 32) & 0xff] ^
crc64_table[2][(crc >> 40) & 0xff] ^
crc64_table[1][(crc >> 48) & 0xff] ^
crc64_table[0][crc >> 56];
next += 8;
len -= 8;
}
while (len) {
crc = crc64_table[0][(crc ^ *next++) & 0xff] ^ (crc >> 8);
len--;
}
return ~crc;
}
/* Calculate a CRC-64 eight bytes at a time on a big-endian architecture. */
static uint64_t crc64_big(uint64_t crc, void *buf, size_t len)
{
unsigned char *next = (unsigned char *)buf;
crc = ~rev8(crc);
while (len && ((uintptr_t)next & 7) != 0) {
crc = crc64_table[0][(crc >> 56) ^ *next++] ^ (crc << 8);
len--;
}
while (len >= 8) {
crc ^= *(uint64_t *)next;
crc = crc64_table[0][crc & 0xff] ^
crc64_table[1][(crc >> 8) & 0xff] ^
crc64_table[2][(crc >> 16) & 0xff] ^
crc64_table[3][(crc >> 24) & 0xff] ^
crc64_table[4][(crc >> 32) & 0xff] ^
crc64_table[5][(crc >> 40) & 0xff] ^
crc64_table[6][(crc >> 48) & 0xff] ^
crc64_table[7][crc >> 56];
next += 8;
len -= 8;
}
while (len) {
crc = crc64_table[0][(crc >> 56) ^ *next++] ^ (crc << 8);
len--;
}
return ~rev8(crc);
}
/* Return the CRC-64 of buf[0..len-1] with initial crc, processing eight bytes
at a time. This selects one of two routines depending on the endianess of
the architecture. A good optimizing compiler will determine the endianess
at compile time if it can, and get rid of the unused code and table. If the
endianess can be changed at run time, then this code will handle that as
well, initializing and using two tables, if called upon to do so. */
#define GF2_DIM 64 /* dimension of GF(2) vectors (length of CRC) */
static uint64_t gf2_matrix_times(uint64_t *mat, uint64_t vec)
{
uint64_t sum;
sum = 0;
while (vec) {
if (vec & 1)
sum ^= *mat;
vec >>= 1;
mat++;
}
return sum;
}
static void gf2_matrix_square(uint64_t *square, uint64_t *mat)
{
unsigned n;
for (n = 0; n < GF2_DIM; n++)
square[n] = gf2_matrix_times(mat, mat[n]);
}
/* Return the CRC-64 of two sequential blocks, where crc1 is the CRC-64 of the
first block, crc2 is the CRC-64 of the second block, and len2 is the length
of the second block. */
static uint64_t crc64_combine(uint64_t crc1, uint64_t crc2, uintmax_t len2)
{
unsigned n;
uint64_t row;
uint64_t even[GF2_DIM]; /* even-power-of-two zeros operator */
uint64_t odd[GF2_DIM]; /* odd-power-of-two zeros operator */
/* degenerate case */
if (len2 == 0)
return crc1;
/* put operator for one zero bit in odd */
odd[0] = POLY; /* CRC-64 polynomial */
row = 1;
for (n = 1; n < GF2_DIM; n++) {
odd[n] = row;
row <<= 1;
}
/* put operator for two zero bits in even */
gf2_matrix_square(even, odd);
/* put operator for four zero bits in odd */
gf2_matrix_square(odd, even);
/* apply len2 zeros to crc1 (first square will put the operator for one
zero byte, eight zero bits, in even) */
do {
/* apply zeros operator for this bit of len2 */
gf2_matrix_square(even, odd);
if (len2 & 1)
crc1 = gf2_matrix_times(even, crc1);
len2 >>= 1;
/* if no more bits set, then done */
if (len2 == 0)
break;
/* another iteration of the loop with odd and even swapped */
gf2_matrix_square(odd, even);
if (len2 & 1)
crc1 = gf2_matrix_times(odd, crc1);
len2 >>= 1;
/* if no more bits set, then done */
} while (len2 != 0);
/* return combined crc */
crc1 ^= crc2;
return crc1;
}
class CRC64_GUARD
{
public:
CRC64_GUARD()
{
uint64_t n = 1;
if (*(char *)&n) {
crc64_little_init();
}
else {
crc64_big_init();
}
}
~CRC64_GUARD() = default;
};
static CRC64_GUARD crc64Guard;
uint64_t CRC64::CalcCRC(uint64_t crc, void *buf, size_t len)
{
uint64_t n = 1;
return *(char *)&n ? crc64_little(crc, buf, len) : crc64_big(crc, buf, len);
}
uint64_t CRC64::CalcCRC(uint64_t crc, void *buf, size_t len, bool little)
{
return little ? crc64_little(crc, buf, len) : crc64_big(crc, buf, len);
}
uint64_t CRC64::CombineCRC(uint64_t crc1, uint64_t crc2, uintmax_t len2)
{
return crc64_combine(crc1, crc2, len2);
}
}
}
| YifuLiu/AliOS-Things | components/oss/src/utils/Crc64.cc | C++ | apache-2.0 | 8,888 |
/*
* 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 <stdint.h>
#include <cstddef>
namespace AlibabaCloud
{
namespace OSS
{
class CRC64
{
public:
static uint64_t CalcCRC(uint64_t crc, void *buf, size_t len);
static uint64_t CombineCRC(uint64_t crc1, uint64_t crc2, uintmax_t len2);
static uint64_t CalcCRC(uint64_t crc, void *buf, size_t len, bool little);
};
}
}
| YifuLiu/AliOS-Things | components/oss/src/utils/Crc64.h | C++ | apache-2.0 | 999 |
/*
* 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/utils/Executor.h>
using namespace AlibabaCloud::OSS;
Executor::Executor()
{
}
Executor::~Executor()
{
}
| YifuLiu/AliOS-Things | components/oss/src/utils/Executor.cc | C++ | apache-2.0 | 772 |
/*
* 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 <string>
#include <map>
#include <ctime>
#include <fstream>
#include <memory>
#include <alibabacloud/oss/Types.h>
#include "FileSystemUtils.h"
#include <alibabacloud/oss/Const.h>
#ifdef _WIN32
#include <direct.h>
#include <io.h>
#include <sys/stat.h>
#define oss_access(a) ::_access((a), 0)
#define oss_mkdir(a) ::_mkdir(a)
#define oss_rmdir(a) ::_rmdir(a)
#define oss_stat ::_stat64
#define oss_waccess(a) ::_waccess((a), 0)
#define oss_wmkdir(a) ::_wmkdir(a)
#define oss_wrmdir(a) ::_wrmdir(a)
#define oss_wstat ::_wstat64
#define oss_wremove ::_wremove
#define oss_wrename ::_wrename
#else
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#define oss_access(a) ::access(a, 0)
#define oss_mkdir(a) ::mkdir((a), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH)
#define oss_rmdir(a) ::rmdir(a)
#define oss_stat stat
#endif
using namespace AlibabaCloud::OSS;
bool AlibabaCloud::OSS::CreateDirectory(const std::string &folder)
{
std::string folder_builder;
std::string sub;
sub.reserve(folder.size());
for (auto it = folder.begin(); it != folder.end(); ++it) {
const char c = *it;
sub.push_back(c);
if (c == PATH_DELIMITER || it == folder.end() - 1) {
folder_builder.append(sub);
if (oss_access(folder_builder.c_str()) != 0) {
if (oss_mkdir(folder_builder.c_str()) != 0) {
return false;
}
}
sub.clear();
}
}
return true;
}
bool AlibabaCloud::OSS::IsDirectoryExist(std::string folder) {
if (folder[folder.length() - 1] != PATH_DELIMITER && folder[folder.length() - 1] != '/') {
folder += PATH_DELIMITER;
}
return !oss_access(folder.c_str());
}
bool AlibabaCloud::OSS::RemoveDirectory(const std::string &folder)
{
return !oss_rmdir(folder.c_str());
}
bool AlibabaCloud::OSS::RemoveFile(const std::string &filepath)
{
int ret = ::remove(filepath.c_str());
return !ret;
}
bool AlibabaCloud::OSS::RenameFile(const std::string &from, const std::string &to)
{
return !::rename(from.c_str(), to.c_str());
}
bool AlibabaCloud::OSS::GetPathLastModifyTime(const std::string& path, time_t& t)
{
std::streamsize size;
return GetPathInfo(path, t, size);
}
bool AlibabaCloud::OSS::GetPathInfo(const std::string& path, time_t& t, std::streamsize& size)
{
struct oss_stat buf;
auto filename = path.c_str();
#if defined(_WIN32) && _MSC_VER < 1900
std::string tmp;
if (!path.empty() && (path.rbegin()[0] == PATH_DELIMITER)) {
tmp = path.substr(0, path.size() - 1);
filename = tmp.c_str();
}
#endif
if (oss_stat(filename, &buf) != 0)
return false;
t = buf.st_mtime;
size = static_cast<std::streamsize>(buf.st_size);
return true;
}
bool AlibabaCloud::OSS::IsFileExist(const std::string& file)
{
std::streamsize size;
time_t t;
return GetPathInfo(file, t, size);
}
//wchar path
#ifdef _WIN32
bool AlibabaCloud::OSS::CreateDirectory(const std::wstring &folder)
{
std::wstring folder_builder;
std::wstring sub;
sub.reserve(folder.size());
for (auto it = folder.begin(); it != folder.end(); ++it) {
auto c = *it;
sub.push_back(c);
if (c == WPATH_DELIMITER || it == folder.end() - 1) {
folder_builder.append(sub);
if (oss_waccess(folder_builder.c_str()) != 0) {
if (oss_wmkdir(folder_builder.c_str()) != 0) {
return false;
}
}
sub.clear();
}
}
return true;
}
bool AlibabaCloud::OSS::IsDirectoryExist(std::wstring folder) {
if (folder[folder.length() - 1] != WPATH_DELIMITER && folder[folder.length() - 1] != '/') {
folder += WPATH_DELIMITER;
}
return !oss_waccess(folder.c_str());
}
bool AlibabaCloud::OSS::RemoveDirectory(const std::wstring& folder)
{
return !oss_wrmdir(folder.c_str());
}
bool AlibabaCloud::OSS::RemoveFile(const std::wstring& filepath)
{
int ret = oss_wremove(filepath.c_str());
return !ret;
}
bool AlibabaCloud::OSS::RenameFile(const std::wstring& from, const std::wstring& to)
{
return !oss_wrename(from.c_str(), to.c_str());
}
bool AlibabaCloud::OSS::GetPathLastModifyTime(const std::wstring& path, time_t& t)
{
std::streamsize size;
return GetPathInfo(path, t, size);
}
bool AlibabaCloud::OSS::GetPathInfo(const std::wstring& path, time_t& t, std::streamsize& size)
{
struct oss_stat buf;
auto filename = path.c_str();
#if defined(_WIN32) && _MSC_VER < 1900
std::wstring tmp;
if (!path.empty() && (path.rbegin()[0] == WPATH_DELIMITER)) {
tmp = path.substr(0, path.size() - 1);
filename = tmp.c_str();
}
#endif
if (oss_wstat(filename, &buf) != 0)
return false;
t = buf.st_mtime;
size = static_cast<std::streamsize>(buf.st_size);
return true;
}
bool AlibabaCloud::OSS::IsFileExist(const std::wstring& file)
{
std::streamsize size;
time_t t;
return GetPathInfo(file, t, size);
}
#endif
std::shared_ptr<std::fstream> AlibabaCloud::OSS::GetFstreamByPath(
const std::string& path, const std::wstring& pathw,
std::ios_base::openmode mode)
{
#ifdef _WIN32
if (!pathw.empty()) {
return std::make_shared<std::fstream>(pathw, mode);
}
#else
((void)(pathw));
#endif
return std::make_shared<std::fstream>(path, mode);
}
| YifuLiu/AliOS-Things | components/oss/src/utils/FileSystemUtils.cc | C++ | apache-2.0 | 6,312 |
/*
* 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 <string>
#include <fstream>
#include <memory>
#include <alibabacloud/oss/Types.h>
namespace AlibabaCloud
{
namespace OSS
{
bool CreateDirectory(const std::string &folder);
bool RemoveDirectory(const std::string &folder);
bool RemoveFile(const std::string &filepath);
bool RenameFile(const std::string &from, const std::string &to);
bool GetPathLastModifyTime(const std::string &path, time_t &t);
bool IsDirectoryExist(std::string folder);
bool GetPathInfo(const std::string &path, time_t &t, std::streamsize& size);
bool IsFileExist(const std::string& file);
//wchar path
#ifdef _WIN32
bool CreateDirectory(const std::wstring& folder);
bool RemoveDirectory(const std::wstring& folder);
bool RemoveFile(const std::wstring& filepath);
bool RenameFile(const std::wstring& from, const std::wstring& to);
bool GetPathLastModifyTime(const std::wstring& path, time_t& t);
bool IsDirectoryExist(std::wstring folder);
bool GetPathInfo(const std::wstring &path, time_t &t, std::streamsize& size);
bool IsFileExist(const std::wstring& file);
#endif
std::shared_ptr<std::fstream> GetFstreamByPath(
const std::string& path,
const std::wstring& pathw,
std::ios_base::openmode mode);
}
}
| YifuLiu/AliOS-Things | components/oss/src/utils/FileSystemUtils.h | C++ | apache-2.0 | 1,911 |
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "Utils.h"
#include "LogUtils.h"
#include <iostream>
#include <memory>
#include <cstdarg>
#include <sstream>
#include <chrono>
#include <iomanip>
#include <ctime>
#include <thread>
#include <cstdarg>
using namespace AlibabaCloud::OSS;
static LogLevel gOssLogLevel = LogLevel::LogAll;
static LogCallback gLogCallback = nullptr;
const static char *EnvLogLevels[] =
{
"off", "fatal", "error", "warn",
"info", "debug", "trace", "all"
};
static std::string LogPrefix(LogLevel logLevel, const char* tag)
{
static const char *LogStr[] = {"[OFF]", "[FATAL]", "[ERROR]", "[WARN]", "[INFO]" , "[DEBUG]", "[TRACE]", "[ALL]"};
int index = logLevel - LogLevel::LogOff;
std::stringstream ss;
auto tp = std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now());
auto ms = tp.time_since_epoch().count() % 1000;
auto t = std::chrono::system_clock::to_time_t(tp);
struct tm tm;
#ifdef WIN32
::localtime_s(&tm, &t);
#else
::localtime_r(&t, &tm);
#endif
#if defined(__GNUG__) && __GNUC__ < 5
char tmbuff[64];
strftime(tmbuff, 64, "%Y-%m-%d %H:%M:%S.", &tm);
ss << "[" << tmbuff << std::setw(3) << std::setfill('0') << ms << "]";
#else
ss << "[" << std::put_time(&tm, "%Y-%m-%d %H:%M:%S.") << std::setw(3) << std::setfill('0') << ms << "]";
#endif
ss << LogStr[index];
ss << "[" << tag << "]";
ss << "[" << std::this_thread::get_id() << "]";
return ss.str();
}
void AlibabaCloud::OSS::FormattedLog(LogLevel logLevel, const char* tag, const char* fmt, ...)
{
std::stringstream ss;
ss << LogPrefix(logLevel, tag);
char buffer[2050];
int i = 0;
va_list args;
va_start(args, fmt);
#ifdef WIN32
i = vsnprintf_s(buffer, sizeof(buffer) - 1, _TRUNCATE, fmt, args);
#else
i = vsnprintf(buffer, sizeof(buffer) - 1, fmt, args);
#endif
va_end(args);
while (i > 0 && buffer[i - 1] == '\n') {
i--;
buffer[i] = '\0';
}
std::cout << buffer << std::endl;
if (gLogCallback) {
gLogCallback(logLevel, ss.str());
}
}
static void DefaultLogCallbackFunc(LogLevel level, const std::string &stream)
{
UNUSED_PARAM(level);
std::cerr << stream;
}
LogLevel AlibabaCloud::OSS::GetLogLevelInner()
{
return gOssLogLevel;
}
LogCallback AlibabaCloud::OSS::GetLogCallbackInner()
{
return gLogCallback;
}
void AlibabaCloud::OSS::SetLogLevelInner(LogLevel level)
{
gOssLogLevel = level;
}
void AlibabaCloud::OSS::SetLogCallbackInner(LogCallback callback)
{
gLogCallback = callback;
}
void AlibabaCloud::OSS::InitLogInner()
{
gOssLogLevel = LogLevel::LogOff;
gLogCallback = nullptr;
auto value = std::getenv("OSS_SDK_LOG_LEVEL");
if (value) {
auto level = ToLower(Trim(value).c_str());
const auto size = sizeof(EnvLogLevels)/sizeof(EnvLogLevels[0]);
for (auto i = 0U; i < size; i++) {
if (level.compare(EnvLogLevels[i]) == 0) {
gOssLogLevel = static_cast<decltype(LogLevel::LogOff)>(static_cast<decltype(i)>(LogLevel::LogOff) + i);
gLogCallback = DefaultLogCallbackFunc;
break;
}
}
}
}
void AlibabaCloud::OSS::DeinitLogInner()
{
gOssLogLevel = LogLevel::LogOff;
gLogCallback = nullptr;
}
| YifuLiu/AliOS-Things | components/oss/src/utils/LogUtils.cc | C++ | apache-2.0 | 3,908 |
/*
* 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/Types.h>
namespace AlibabaCloud
{
namespace OSS
{
void InitLogInner();
void DeinitLogInner();
LogLevel GetLogLevelInner();
LogCallback GetLogCallbackInner();
void SetLogLevelInner(LogLevel level);
void SetLogCallbackInner(LogCallback callback);
void FormattedLog(LogLevel logLevel, const char* tag, const char* formatStr, ...);
//#define OSS_LOG(level, tag, ...) FormattedLog(level, tag, __VA_ARGS__)
#ifdef DISABLE_OSS_LOGGING
#define OSS_LOG(level, tag, ...)
#else
#define OSS_LOG(level, tag, ...) \
{ \
if ( AlibabaCloud::OSS::GetLogCallbackInner() && AlibabaCloud::OSS::GetLogLevelInner() >= level ) \
{ \
FormattedLog(level, tag, __VA_ARGS__); \
} \
}
#endif // DISABLE_OSS_LOGGING
}
}
| YifuLiu/AliOS-Things | components/oss/src/utils/LogUtils.h | C++ | apache-2.0 | 1,442 |
/*
* 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/utils/Runnable.h>
using namespace AlibabaCloud::OSS;
Runnable::Runnable(const std::function<void()> f) :
f_(f)
{
}
void Runnable::run() const
{
f_();
} | YifuLiu/AliOS-Things | components/oss/src/utils/Runnable.cc | C++ | apache-2.0 | 801 |
/*
* 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 "SignUtils.h"
#include "Utils.h"
#include <sstream>
#include <map>
#include <set>
#include <alibabacloud/oss/Const.h>
#include <alibabacloud/oss/Types.h>
#include <alibabacloud/oss/http/HttpType.h>
using namespace AlibabaCloud::OSS;
const static std::set<std::string> ParamtersToSign =
{
"acl", "location", "bucketInfo", "stat", "referer", "cors", "website", "restore",
"logging", "symlink", "qos", "uploadId", "uploads", "partNumber",
"response-content-type", "response-content-language", "response-expires",
"response-cache-control", "response-content-disposition", "response-content-encoding",
"append", "position", "lifecycle", "delete", "live", "status", "comp", "vod",
"startTime", "endTime", "x-oss-process", "security-token", "objectMeta",
"callback", "callback-var", "tagging", "policy", "requestPayment", "x-oss-traffic-limit",
"encryption", "qosInfo", "versioning", "versionId", "versions",
"x-oss-request-payer", "sequential", "inventory", "inventoryId", "continuation-token"
};
SignUtils::SignUtils(const std::string &version):
signVersion_(version),
canonicalString_()
{
}
SignUtils::~SignUtils()
{
}
const std::string &SignUtils::CanonicalString() const
{
return canonicalString_;
}
void SignUtils::build(const std::string &method,
const std::string &resource,
const std::string &date,
const HeaderCollection &headers,
const ParameterCollection ¶meters)
{
std::stringstream ss;
/*Version 1*/
// VERB + "\n" +
// Content-MD5 + "\n" +
// Content-Type + "\n"
// Date + "\n" +
// CanonicalizedOSSHeaders +
// CanonicalizedResource) +
//common headers
ss << method << "\n";
if (headers.find(Http::CONTENT_MD5) != headers.end()) {
ss << headers.at(Http::CONTENT_MD5);
}
ss << "\n";
if (headers.find(Http::CONTENT_TYPE) != headers.end()) {
ss << headers.at(Http::CONTENT_TYPE);
}
ss << "\n";
//Date or EXPIRES
ss << date << "\n";
//CanonicalizedOSSHeaders, start with x-oss-
for (const auto &header : headers) {
std::string lower = Trim(ToLower(header.first.c_str()).c_str());
if (lower.compare(0, 6, "x-oss-", 6) == 0) {
std::string value = Trim(header.second.c_str());
ss << lower << ":" << value << "\n";
}
}
//CanonicalizedResource, the sub resouce in
ss << resource;
char separator = '?';
for (auto const& param : parameters) {
if (ParamtersToSign.find(param.first) == ParamtersToSign.end()) {
continue;
}
ss << separator;
ss << param.first;
if (!param.second.empty()) {
ss << "=" << param.second;
}
separator = '&';
}
canonicalString_ = ss.str();
}
void SignUtils::build(const std::string &expires,
const std::string &resource,
const ParameterCollection ¶meters)
{
std::stringstream ss;
ss << expires << '\n';
for(auto const& param : parameters)
{
ss << param.first << ":" << param.second << '\n';
}
ss << resource;
canonicalString_ = ss.str();
}
| YifuLiu/AliOS-Things | components/oss/src/utils/SignUtils.cc | C++ | apache-2.0 | 3,981 |
/*
* 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 <map>
#include <ctime>
#include <iostream>
#include <alibabacloud/oss/Types.h>
namespace AlibabaCloud
{
namespace OSS
{
class SignUtils
{
public:
SignUtils(const std::string &version);
~SignUtils();
void build(const std::string &method,
const std::string &resource,
const std::string &date,
const HeaderCollection &headers,
const ParameterCollection ¶meters);
void build(const std::string &expires,
const std::string &resource,
const ParameterCollection ¶meters);
const std::string &CanonicalString() const;
private:
std::string signVersion_;
std::string canonicalString_;
};
}
}
| YifuLiu/AliOS-Things | components/oss/src/utils/SignUtils.h | C++ | apache-2.0 | 1,453 |
/*
* 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 <iostream>
namespace AlibabaCloud
{
namespace OSS
{
template<class _Elem, class _Traits>
class basic_streambuf_proxy : public std::basic_streambuf <_Elem, _Traits>
{
public:
virtual ~basic_streambuf_proxy() {
std::ios_base::iostate state = _Stream->rdstate();
_Stream->rdbuf(_Sbuf);
_Stream->setstate(state);
}
using int_type = typename _Traits::int_type;
using pos_type = typename _Traits::pos_type;
using off_type = typename _Traits::off_type;
protected:
basic_streambuf_proxy(std::basic_iostream<_Elem, _Traits>& stream)
: _Stream(&stream)
, _Sbuf(_Stream->rdbuf(this)) {
}
int_type overflow(int_type _Meta = _Traits::eof())
{ // put a character to stream
return _Sbuf->sputc(_Meta);
}
int_type pbackfail(int_type _Meta = _Traits::eof())
{ // put a character back to stream
return _Sbuf->sputbackc(_Meta);
}
std::streamsize showmanyc()
{ // return count of input characters
return _Sbuf->in_avail();;
}
int_type underflow()
{ // get a character from stream, but don't point past it
return _Sbuf->sgetc();
}
int_type uflow()
{ // get a character from stream, point past it
return _Sbuf->sbumpc();
}
std::streamsize xsgetn(_Elem * _Ptr, std::streamsize _Count)
{ // get _Count characters from stream
return _Sbuf->sgetn(_Ptr, _Count);
}
std::streamsize xsputn(const _Elem *_Ptr, std::streamsize _Count)
{ // put _Count characters to stream
return _Sbuf->sputn(_Ptr, _Count);
}
pos_type seekoff(off_type _Off, std::ios_base::seekdir _Way, std::ios_base::openmode _Mode = std::ios_base::in | std::ios_base::out)
{ // change position by offset, according to way and mode
return _Sbuf->pubseekoff(_Off, _Way, _Mode);
}
pos_type seekpos(pos_type _Pos, std::ios_base::openmode _Mode = std::ios_base::in | std::ios_base::out)
{ // change to specified position, according to mode
return _Sbuf->pubseekpos(_Pos, _Mode);
}
std::basic_streambuf<_Elem, _Traits>* setbuf(_Elem *_Buffer, std::streamsize _Count)
{ // offer buffer to external agent
return _Sbuf->pubsetbuf(_Buffer, _Count);
}
int sync()
{ // synchronize with external agent
return _Sbuf->pubsync();
}
void imbue(const std::locale& _Newlocale)
{ // set locale to argument
_Sbuf->pubimbue(_Newlocale);
}
private:
std::basic_iostream<_Elem, _Traits>* _Stream;
std::basic_streambuf<_Elem, _Traits>* _Sbuf;
};
using StreamBufProxy = basic_streambuf_proxy<char, std::char_traits<char>>;
}
}
| YifuLiu/AliOS-Things | components/oss/src/utils/StreamBuf.h | C++ | apache-2.0 | 3,458 |
/*
* 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 "ThreadExecutor.h"
#include <assert.h>
#include "../utils/LogUtils.h"
using namespace AlibabaCloud::OSS;
static const char *TAG = "ThreadExecutor";
ThreadExecutor::ThreadExecutor():
state_(State::Free)
{
}
ThreadExecutor::~ThreadExecutor()
{
auto expected = State::Free;
while (!state_.compare_exchange_strong(expected, State::Shutdown))
{
assert(expected == State::Locked);
expected = State::Free;
}
auto it = threads_.begin();
while (!threads_.empty())
{
it->second.join();
it = threads_.erase(it);
}
}
void ThreadExecutor::execute(Runnable* task)
{
auto main = [task, this] {
OSS_LOG(LogLevel::LogDebug, TAG, "task(%p) enter execute main thread", task);
task->run();
delete task;
detach(std::this_thread::get_id());
OSS_LOG(LogLevel::LogDebug, TAG, "task(%p) leave execute main thread", task);
};
State expected;
do
{
expected = State::Free;
if (state_.compare_exchange_strong(expected, State::Locked))
{
std::thread t(main);
const auto id = t.get_id();
threads_.emplace(id, std::move(t));
state_ = State::Free;
return;
}
} while (expected != State::Shutdown);
return;
}
void ThreadExecutor::detach(std::thread::id id)
{
State expected;
do
{
expected = State::Free;
if (state_.compare_exchange_strong(expected, State::Locked))
{
auto it = threads_.find(id);
assert(it != threads_.end());
it->second.detach();
threads_.erase(it);
state_ = State::Free;
return;
}
} while (expected != State::Shutdown);
} | YifuLiu/AliOS-Things | components/oss/src/utils/ThreadExecutor.cc | C++ | apache-2.0 | 2,381 |
/*
* 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/utils/Executor.h>
namespace AlibabaCloud
{
namespace OSS
{
class ThreadExecutor: public Executor
{
public:
ThreadExecutor();
virtual ~ThreadExecutor();
void execute(Runnable* task);
private:
enum class State
{
Free, Locked, Shutdown
};
void detach(std::thread::id id);
std::atomic<State> state_;
std::unordered_map<std::thread::id, std::thread> threads_;
};
}
}
| YifuLiu/AliOS-Things | components/oss/src/utils/ThreadExecutor.h | C++ | apache-2.0 | 1,119 |
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "Utils.h"
#ifdef USE_CRYPTO_MBEDTLS
#include "mbedtls/md.h"
#include "mbedtls/compat-1.3.h"
#include "mbedtls/sha1.h"
#include "mbedtls/base64.h"
#include "mbedtls/md5.h"
#else
#include <openssl/evp.h>
#include <openssl/hmac.h>
#include <openssl/md5.h>
#ifdef OPENSSL_IS_BORINGSSL
#include <openssl/base64.h>
#endif
#endif
#include <algorithm>
#include <cstring>
#include <iostream>
#include <sstream>
#include <map>
#include <regex>
#include <iomanip>
#include <alibabacloud/oss/Const.h>
#include <alibabacloud/oss/http/HttpType.h>
#include <alibabacloud/oss/http/Url.h>
#include "../external/json/json.h"
using namespace AlibabaCloud::OSS;
#if defined(__GNUG__) && __GNUC__ < 5
#else
static const std::regex ipPattern("((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])");
static const std::regex bucketNamePattern("^[a-z0-9][a-z0-9\\-]{1,61}[a-z0-9]$");
static const std::regex loggingPrefixPattern("^[a-zA-Z][a-zA-Z0-9\\-]{0,31}$");
#endif
std::string AlibabaCloud::OSS::GenerateUuid()
{
return "";
}
std::string AlibabaCloud::OSS::UrlEncode(const std::string & src)
{
std::stringstream dest;
static const char *hex = "0123456789ABCDEF";
unsigned char c;
for (size_t i = 0; i < src.size(); i++) {
c = src[i];
if (isalnum(c) || (c == '-') || (c == '_') || (c == '.') || (c == '~')) {
dest << c;
} else if (c == ' ') {
dest << "%20";
} else {
dest << '%' << hex[c >> 4] << hex[c & 15];
}
}
return dest.str();
}
std::string AlibabaCloud::OSS::UrlDecode(const std::string & src)
{
std::stringstream unescaped;
unescaped.fill('0');
unescaped << std::hex;
size_t safeLength = src.size();
const char *safe = src.c_str();
for (auto i = safe, n = safe + safeLength; i != n; ++i)
{
char c = *i;
if(c == '%')
{
char hex[3];
hex[0] = *(i + 1);
hex[1] = *(i + 2);
hex[2] = 0;
i += 2;
auto hexAsInteger = strtol(hex, nullptr, 16);
unescaped << (char)hexAsInteger;
}
else
{
unescaped << *i;
}
}
return unescaped.str();
}
std::string AlibabaCloud::OSS::Base64Encode(const std::string &src)
{
return AlibabaCloud::OSS::Base64Encode(src.c_str(), static_cast<int>(src.size()));
}
std::string AlibabaCloud::OSS::Base64Encode(const ByteBuffer& buffer)
{
return AlibabaCloud::OSS::Base64Encode(reinterpret_cast<const char*>(buffer.data()), static_cast<int>(buffer.size()));
}
std::string AlibabaCloud::OSS::Base64Encode(const char *src, int len)
{
if (!src || len == 0) {
return "";
}
static const char *ENC = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
auto in = reinterpret_cast<const unsigned char *>(src);
auto inLen = len;
std::stringstream ss;
while (inLen) {
// first 6 bits of char 1
ss << ENC[*in >> 2];
if (!--inLen) {
// last 2 bits of char 1, 4 bits of 0
ss << ENC[(*in & 0x3) << 4];
ss << '=';
ss << '=';
break;
}
// last 2 bits of char 1, first 4 bits of char 2
ss << ENC[((*in & 0x3) << 4) | (*(in + 1) >> 4)];
in++;
if (!--inLen) {
// last 4 bits of char 2, 2 bits of 0
ss << ENC[(*in & 0xF) << 2];
ss << '=';
break;
}
// last 4 bits of char 2, first 2 bits of char 3
ss << ENC[((*in & 0xF) << 2) | (*(in + 1) >> 6)];
in++;
// last 6 bits of char 3
ss << ENC[*in & 0x3F];
in++, inLen--;
}
return ss.str();
}
std::string AlibabaCloud::OSS::Base64EncodeUrlSafe(const std::string &src)
{
return AlibabaCloud::OSS::Base64EncodeUrlSafe(src.c_str(), static_cast<int>(src.size()));
}
std::string AlibabaCloud::OSS::Base64EncodeUrlSafe(const char *src, int len)
{
std::string out = AlibabaCloud::OSS::Base64Encode(src, len);
while (out.size() > 0 && *out.rbegin() == '=')
out.pop_back();
std::transform(out.begin(), out.end(), out.begin(), [](unsigned char c) {
if (c == '+') return '-';
if (c == '/') return '_';
return (char)c;
});
return out;
}
std::string AlibabaCloud::OSS::XmlEscape(const std::string& value)
{
struct Entity {
const char* pattern;
char value;
};
static const Entity entities[] = {
{ """, '\"' },
{ "&", '&' },
{ "'", '\'' },
{ "<", '<' },
{ ">", '>' },
{ " ", '\r' }
};
if (value.empty()) {
return value;
}
std::stringstream ss;
for (size_t i = 0; i < value.size(); i++) {
bool flag = false;
for (size_t j = 0; j < (sizeof(entities)/sizeof(entities[0])); j++) {
if (value[i] == entities[j].value) {
flag = true;
ss << entities[j].pattern;
break;
}
}
if (!flag) {
ss << value[i];
}
}
return ss.str();
}
ByteBuffer AlibabaCloud::OSS::Base64Decode(const char *data, int len)
{
int in_len = len;
int i = 0;
int in_ = 0;
unsigned char part4[4];
const int max_len = (len * 3 / 4);
ByteBuffer ret(max_len);
int idx = 0;
while (in_len-- && (data[in_] != '=')) {
unsigned char ch = data[in_++];
if ('A' <= ch && ch <= 'Z') ch = ch - 'A'; // A - Z
else if ('a' <= ch && ch <= 'z') ch = ch - 'a' + 26; // a - z
else if ('0' <= ch && ch <= '9') ch = ch - '0' + 52; // 0 - 9
else if ('+' == ch) ch = 62; // +
else if ('/' == ch) ch = 63; // /
else if ('=' == ch) ch = 64; // =
else ch = 0xff; // something wrong
part4[i++] = ch;
if (i == 4) {
ret[idx++] = (part4[0] << 2) + ((part4[1] & 0x30) >> 4);
ret[idx++] = ((part4[1] & 0xf) << 4) + ((part4[2] & 0x3c) >> 2);
ret[idx++] = ((part4[2] & 0x3) << 6) + part4[3];
i = 0;
}
}
if (i) {
for (int j = i; j < 4; j++)
part4[j] = 0xFF;
ret[idx++] = (part4[0] << 2) + ((part4[1] & 0x30) >> 4);
if (part4[2] != 0xFF) {
ret[idx++] = ((part4[1] & 0xf) << 4) + ((part4[2] & 0x3c) >> 2);
if (part4[3] != 0xFF) {
ret[idx++] = ((part4[2] & 0x3) << 6) + part4[3];
}
}
}
ret.resize(idx);
return ret;
}
ByteBuffer AlibabaCloud::OSS::Base64Decode(const std::string &src)
{
return Base64Decode(src.c_str(), src.size());
}
std::string AlibabaCloud::OSS::ComputeContentMD5(const std::string& data)
{
return ComputeContentMD5(data.c_str(), data.size());
}
std::string AlibabaCloud::OSS::ComputeContentMD5(const char * data, size_t size)
{
#if defined(USE_CRYPTO_MBEDTLS)
unsigned char md_data[16];
unsigned int mdLen = 16;
mbedtls_md5_context ctx;
unsigned int olen = 0;
#if 0
mbedtls_md5_init(&ctx);
mbedtls_md5_starts(&ctx);
mbedtls_md5_update(&ctx, (const unsigned char *)data, size);
mbedtls_md5_finish(&ctx, md_data);
mbedtls_md5_free(&ctx);
#endif
mbedtls_md5_ret((const unsigned char*)data, size, md_data);
char encodedData[100];
mbedtls_base64_encode((unsigned char*)encodedData, sizeof(encodedData), &olen, md_data, mdLen);
return encodedData;
//TODO: ethan: not used for the moment
#elif 0//defined(USE_CRYPTO_MBEDTLS)
unsigned char md_data[16];
unsigned int mdLen = 16;
unsigned int olen = 0;
mbedtls_md(mbedtls_md_info_from_type(MBEDTLS_MD_MD5), data, size, md_data);
char encodedData[100];
mbedtls_base64_encode((unsigned char*)encodedData, sizeof(encodedData), &olen, md_data, mdLen);
return encodedData;
#else
unsigned char md[MD5_DIGEST_LENGTH];
MD5(reinterpret_cast<const unsigned char*>(data), size, (unsigned char*)&md);
char encodedData[100];
EVP_EncodeBlock(reinterpret_cast<unsigned char*>(encodedData), md, MD5_DIGEST_LENGTH);
return encodedData;
#endif
}
std::string AlibabaCloud::OSS::ComputeContentMD5(std::istream& stream)
{
#ifdef USE_CRYPTO_MBEDTLS
unsigned char md_value[16];
unsigned int md_len = 16;
unsigned int olen = 0;
mbedtls_md5_context ctx;
mbedtls_md5_init(&ctx);
mbedtls_md5_starts_ret(&ctx);
auto currentPos = stream.tellg();
if (currentPos == static_cast<std::streampos>(-1)) {
currentPos = 0;
stream.clear();
}
stream.seekg(0, stream.beg);
// TODO: ethan, need to shrink the buffer, or stack overflow may happen?
char streamBuffer[2048];
while (stream.good())
{
stream.read(streamBuffer, 2048);
auto bytesRead = stream.gcount();
if (bytesRead > 0)
{
mbedtls_md5_update_ret(&ctx, (const unsigned char *)streamBuffer, static_cast<size_t>(bytesRead));
}
}
mbedtls_md5_finish_ret(&ctx, md_value);
mbedtls_md5_free(&ctx);
stream.clear();
stream.seekg(currentPos, stream.beg);
//Based64
char encodedData[100];
mbedtls_base64_encode((unsigned char*)encodedData, sizeof(encodedData), &olen, md_value, md_len);
return encodedData;
#else
auto ctx = EVP_MD_CTX_create();
unsigned char md_value[EVP_MAX_MD_SIZE];
unsigned int md_len = 0;
EVP_MD_CTX_init(ctx);
#ifndef OPENSSL_IS_BORINGSSL
EVP_MD_CTX_set_flags(ctx, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
#endif
EVP_DigestInit_ex(ctx, EVP_md5(), nullptr);
auto currentPos = stream.tellg();
if (currentPos == static_cast<std::streampos>(-1)) {
currentPos = 0;
stream.clear();
}
stream.seekg(0, stream.beg);
char streamBuffer[2048];
while (stream.good())
{
stream.read(streamBuffer, 2048);
auto bytesRead = stream.gcount();
if (bytesRead > 0)
{
EVP_DigestUpdate(ctx, streamBuffer, static_cast<size_t>(bytesRead));
}
}
EVP_DigestFinal_ex(ctx, md_value, &md_len);
EVP_MD_CTX_destroy(ctx);
stream.clear();
stream.seekg(currentPos, stream.beg);
//Based64
char encodedData[100];
EVP_EncodeBlock(reinterpret_cast<unsigned char*>(encodedData), md_value, md_len);
return encodedData;
#endif
}
static std::string HexToString(const unsigned char *data, size_t size)
{
static char hex[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
std::stringstream ss;
for (size_t i = 0; i < size; i++)
ss << hex[(data[i] >> 4)] << hex[(data[i] & 0x0F)];
return ss.str();
}
std::string AlibabaCloud::OSS::ComputeContentETag(const std::string& data)
{
return ComputeContentETag(data.c_str(), data.size());
}
std::string AlibabaCloud::OSS::ComputeContentETag(const char * data, size_t size)
{
if (!data) {
return "";
}
#if defined(USE_CRYPTO_MBEDTLS)
unsigned char md_data[16];
#if 0
mbedtls_md5_context ctx;
mbedtls_md5_init(&ctx);
mbedtls_md5_starts_ret(&ctx);
mbedtls_md5_update_ret(&ctx, (const unsigned char*)data, size);
mbedtls_md5_finish_ret(&ctx, md_data);
mbedtls_md5_free(&ctx);
#endif
mbedtls_md5_ret((const unsigned char *)data, size, md_data);
return HexToString(md_data, 16);
#elif 0//defined(USE_CRYPTO_MBEDTLS)
unsigned char md_data[16];
mbedtls_md(mbedtls_md_info_from_type(MBEDTLS_MD_MD5), data, size, md_data);
return HexToString(md_data, 16);
#else
unsigned char md[MD5_DIGEST_LENGTH];
MD5(reinterpret_cast<const unsigned char*>(data), size, (unsigned char*)&md);
return HexToString(md, MD5_DIGEST_LENGTH);
#endif
}
std::string AlibabaCloud::OSS::ComputeContentETag(std::istream& stream)
{
#ifdef USE_CRYPTO_MBEDTLS
unsigned char md_value[16];
unsigned int md_len = 16;
mbedtls_md5_context ctx;
mbedtls_md5_init( &ctx);
mbedtls_md5_starts_ret(&ctx);
auto currentPos = stream.tellg();
if (currentPos == static_cast<std::streampos>(-1)) {
currentPos = 0;
stream.clear();
}
stream.seekg(0, stream.beg);
// TODO: ethan, need to shrink the buffer, or stack overflow may happen?
char streamBuffer[2048];
while (stream.good())
{
stream.read(streamBuffer, 2048);
auto bytesRead = stream.gcount();
if (bytesRead > 0)
{
mbedtls_md5_update_ret(&ctx, (const unsigned char *)streamBuffer, static_cast<size_t>(bytesRead));
}
}
mbedtls_md5_finish_ret(&ctx, md_value);
mbedtls_md5_free(&ctx);
stream.clear();
stream.seekg(currentPos, stream.beg);
return HexToString(md_value, md_len);
#else
auto ctx = EVP_MD_CTX_create();
unsigned char md_value[EVP_MAX_MD_SIZE];
unsigned int md_len = 0;
EVP_MD_CTX_init(ctx);
#ifndef OPENSSL_IS_BORINGSSL
EVP_MD_CTX_set_flags(ctx, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
#endif
EVP_DigestInit_ex(ctx, EVP_md5(), nullptr);
auto currentPos = stream.tellg();
if (currentPos == static_cast<std::streampos>(-1)) {
currentPos = 0;
stream.clear();
}
stream.seekg(0, stream.beg);
char streamBuffer[2048];
while (stream.good())
{
stream.read(streamBuffer, 2048);
auto bytesRead = stream.gcount();
if (bytesRead > 0)
{
EVP_DigestUpdate(ctx, streamBuffer, static_cast<size_t>(bytesRead));
}
}
EVP_DigestFinal_ex(ctx, md_value, &md_len);
EVP_MD_CTX_destroy(ctx);
stream.clear();
stream.seekg(currentPos, stream.beg);
return HexToString(md_value, md_len);
#endif
}
void AlibabaCloud::OSS::StringReplace(std::string & src, const std::string & s1, const std::string & s2)
{
std::string::size_type pos =0;
while ((pos = src.find(s1, pos)) != std::string::npos)
{
src.replace(pos, s1.length(), s2);
pos += s2.length();
}
}
std::string AlibabaCloud::OSS::LeftTrim(const char* source)
{
std::string copy(source);
copy.erase(copy.begin(), std::find_if(copy.begin(), copy.end(), [](unsigned char ch) { return !::isspace(ch); }));
return copy;
}
std::string AlibabaCloud::OSS::RightTrim(const char* source)
{
std::string copy(source);
copy.erase(std::find_if(copy.rbegin(), copy.rend(), [](unsigned char ch) { return !::isspace(ch); }).base(), copy.end());
return copy;
}
std::string AlibabaCloud::OSS::Trim(const char* source)
{
return LeftTrim(RightTrim(source).c_str());
}
std::string AlibabaCloud::OSS::LeftTrimQuotes(const char* source)
{
std::string copy(source);
copy.erase(copy.begin(), std::find_if(copy.begin(), copy.end(), [](int ch) { return !(ch == '"'); }));
return copy;
}
std::string AlibabaCloud::OSS::RightTrimQuotes(const char* source)
{
std::string copy(source);
copy.erase(std::find_if(copy.rbegin(), copy.rend(), [](int ch) { return !(ch == '"'); }).base(), copy.end());
return copy;
}
std::string AlibabaCloud::OSS::TrimQuotes(const char* source)
{
return LeftTrimQuotes(RightTrimQuotes(source).c_str());
}
std::string AlibabaCloud::OSS::ToLower(const char* source)
{
std::string copy;
if (source) {
size_t srcLength = strlen(source);
copy.resize(srcLength);
std::transform(source, source + srcLength, copy.begin(), [](unsigned char c) { return (char)::tolower(c); });
}
return copy;
}
std::string AlibabaCloud::OSS::ToUpper(const char* source)
{
std::string copy;
if (source) {
size_t srcLength = strlen(source);
copy.resize(srcLength);
std::transform(source, source + srcLength, copy.begin(), [](unsigned char c) { return (char)::toupper(c); });
}
return copy;
}
bool AlibabaCloud::OSS::IsIp(const std::string &host)
{
#if defined(__GNUG__) && __GNUC__ < 5
int n[4];
char c[4];
const char *p = host.c_str();
if (sscanf(p, "%d%c%d%c%d%c%d%c", &n[0], &c[0], &n[1], &c[1], &n[2], &c[2], &n[3], &c[3]) == 7)
{
int i;
for (i = 0; i < 3; ++i)
if (c[i] != '.')
return false;
for (i = 0; i < 4; ++i)
if (n[i] > 255 || n[i] < 0)
return false;
return true;
}
return false;
#else
return std::regex_match(host, ipPattern);
#endif
}
std::string AlibabaCloud::OSS::ToGmtTime(std::time_t &t)
{
std::stringstream date;
std::tm tm;
#ifdef _WIN32
::gmtime_s(&tm, &t);
#else
::gmtime_r(&t, &tm);
#endif
#if defined(__GNUG__) && __GNUC__ < 5
static const char wday_name[][4] = {
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
};
static const char mon_name[][4] = {
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};
char tmbuff[26];
snprintf(tmbuff, sizeof(tmbuff), "%.3s, %.2d %.3s %d %.2d:%.2d:%.2d",
wday_name[tm.tm_wday], tm.tm_mday, mon_name[tm.tm_mon],
1900 + tm.tm_year,
tm.tm_hour, tm.tm_min, tm.tm_sec);
date << tmbuff << " GMT";
#else
date.imbue(std::locale::classic());
date << std::put_time(&tm, "%a, %d %b %Y %H:%M:%S GMT");
#endif
return date.str();
}
std::string AlibabaCloud::OSS::ToUtcTime(std::time_t &t)
{
std::stringstream date;
std::tm tm;
#ifdef _WIN32
::gmtime_s(&tm, &t);
#else
::gmtime_r(&t, &tm);
#endif
#if defined(__GNUG__) && __GNUC__ < 5
char tmbuff[26];
strftime(tmbuff, 26, "%Y-%m-%dT%H:%M:%S.000Z", &tm);
date << tmbuff;
#else
date.imbue(std::locale::classic());
date << std::put_time(&tm, "%Y-%m-%dT%X.000Z");
#endif
return date.str();
}
std::time_t AlibabaCloud::OSS::UtcToUnixTime(const std::string &t)
{
const char* date = t.c_str();
std::tm tm;
std::time_t tt = -1;
int ms;
auto result = sscanf(date, "%4d-%2d-%2dT%2d:%2d:%2d.%dZ",
&tm.tm_year, &tm.tm_mon, &tm.tm_mday, &tm.tm_hour, &tm.tm_min, &tm.tm_sec, &ms);
if (result == 7) {
tm.tm_year = tm.tm_year - 1900;
tm.tm_mon = tm.tm_mon - 1;
#ifdef _WIN32
tt = _mkgmtime64(&tm);
#else
#if 0
tt = timegm(&tm);
#endif
#endif // _WIN32
}
return tt < 0 ? -1 : tt;
}
bool AlibabaCloud::OSS::IsValidBucketName(const std::string &bucketName)
{
#if defined(__GNUG__) && __GNUC__ < 5
if (bucketName.size() < 3 || bucketName.size() > 63)
return false;
for (auto it = bucketName.begin(); it != bucketName.end(); it++) {
if (!((*it >= 'a' && *it <= 'z') || (*it >= '0' && *it <= '9') || *it == '-'))
return false;
}
if (*bucketName.begin() == '-' || *bucketName.rbegin() == '-')
return false;
return true;
#else
if (bucketName.empty())
return false;
return std::regex_match(bucketName, bucketNamePattern);
#endif
}
bool AlibabaCloud::OSS::IsValidObjectKey(const std::string & key)
{
if (key.empty() || !key.compare(0, 1, "\\", 1))
return false;
return key.size() <= ObjectNameLengthLimit;
}
bool AlibabaCloud::OSS::IsValidLoggingPrefix(const std::string &prefix)
{
if (prefix.empty())
return true;
#if defined(__GNUG__) && __GNUC__ < 5
if (prefix.size() > 32)
return false;
auto ch = static_cast<int>(*prefix.begin());
if (isalpha(ch) == 0)
return false;
for (auto it = prefix.begin(); it != prefix.end(); it++) {
ch = static_cast<int>(*it);
if (!(::isalpha(ch) || ::isdigit(ch) || *it == '-'))
return false;
}
return true;
#else
return std::regex_match(prefix, loggingPrefixPattern);
#endif
}
bool AlibabaCloud::OSS::IsValidChannelName(const std::string &channelName)
{
if(channelName.empty() ||
std::string::npos != channelName.find('/') ||
channelName.size() > MaxLiveChannelNameLength)
return false;
return true;
}
bool AlibabaCloud::OSS::IsValidPlayListName(const std::string &playlistName)
{
if(playlistName.empty())
{
return false;
}else{
if(!IsValidObjectKey(playlistName))
{
return false;
}
if(playlistName.size() < MinLiveChannelPlayListLength ||
playlistName.size() > MaxLiveChannelPlayListLength)
{
return false;
}
std::size_t lastPos = playlistName.find_last_of('.');
std::size_t slashPos = playlistName.find('/');
if(lastPos == std::string::npos ||
slashPos != std::string::npos ||
0 == lastPos || '.' == playlistName[lastPos-1])
{
return false;
}else{
std::string suffix = playlistName.substr(lastPos);
if(suffix.size() < 5)
{
return false;
}
if(ToLower(suffix.c_str()) != ".m3u8")
{
return false;
}
return true;
}
}
}
bool AlibabaCloud::OSS::IsValidTagKey(const std::string &key)
{
if (key.empty() || key.size() > TagKeyLengthLimit)
return false;
return true;
}
bool AlibabaCloud::OSS::IsValidTagValue(const std::string &value)
{
return value.size() <= TagValueLengthLimit;
}
const std::string& AlibabaCloud::OSS::LookupMimeType(const std::string &name)
{
const static std::map<std::string, std::string> mimeType = {
{"html", "text/html"},
{"htm", "text/html"},
{"shtml", "text/html"},
{"css", "text/css"},
{"xml", "text/xml"},
{"gif", "image/gif"},
{"jpeg", "image/jpeg"},
{"jpg", "image/jpeg"},
{"js", "application/x-javascript"},
{"atom", "application/atom+xml"},
{"rss", "application/rss+xml"},
{"mml", "text/mathml"},
{"txt", "text/plain"},
{"jad", "text/vnd.sun.j2me.app-descriptor"},
{"wml", "text/vnd.wap.wml"},
{"htc", "text/x-component"},
{"png", "image/png"},
{"tif", "image/tiff"},
{"tiff", "image/tiff"},
{"wbmp", "image/vnd.wap.wbmp"},
{"ico", "image/x-icon"},
{"jng", "image/x-jng"},
{"bmp", "image/x-ms-bmp"},
{"svg", "image/svg+xml"},
{"svgz", "image/svg+xml"},
{"webp", "image/webp"},
{"jar", "application/java-archive"},
{"war", "application/java-archive"},
{"ear", "application/java-archive"},
{"hqx", "application/mac-binhex40"},
{"doc ", "application/msword"},
{"pdf", "application/pdf"},
{"ps", "application/postscript"},
{"eps", "application/postscript"},
{"ai", "application/postscript"},
{"rtf", "application/rtf"},
{"xls", "application/vnd.ms-excel"},
{"ppt", "application/vnd.ms-powerpoint"},
{"wmlc", "application/vnd.wap.wmlc"},
{"kml", "application/vnd.google-earth.kml+xml"},
{"kmz", "application/vnd.google-earth.kmz"},
{"7z", "application/x-7z-compressed"},
{"cco", "application/x-cocoa"},
{"jardiff", "application/x-java-archive-diff"},
{"jnlp", "application/x-java-jnlp-file"},
{"run", "application/x-makeself"},
{"pl", "application/x-perl"},
{"pm", "application/x-perl"},
{"prc", "application/x-pilot"},
{"pdb", "application/x-pilot"},
{"rar", "application/x-rar-compressed"},
{"rpm", "application/x-redhat-package-manager"},
{"sea", "application/x-sea"},
{"swf", "application/x-shockwave-flash"},
{"sit", "application/x-stuffit"},
{"tcl", "application/x-tcl"},
{"tk", "application/x-tcl"},
{"der", "application/x-x509-ca-cert"},
{"pem", "application/x-x509-ca-cert"},
{"crt", "application/x-x509-ca-cert"},
{"xpi", "application/x-xpinstall"},
{"xhtml", "application/xhtml+xml"},
{"zip", "application/zip"},
{"wgz", "application/x-nokia-widget"},
{"bin", "application/octet-stream"},
{"exe", "application/octet-stream"},
{"dll", "application/octet-stream"},
{"deb", "application/octet-stream"},
{"dmg", "application/octet-stream"},
{"eot", "application/octet-stream"},
{"iso", "application/octet-stream"},
{"img", "application/octet-stream"},
{"msi", "application/octet-stream"},
{"msp", "application/octet-stream"},
{"msm", "application/octet-stream"},
{"mid", "audio/midi"},
{"midi", "audio/midi"},
{"kar", "audio/midi"},
{"mp3", "audio/mpeg"},
{"ogg", "audio/ogg"},
{"m4a", "audio/x-m4a"},
{"ra", "audio/x-realaudio"},
{"3gpp", "video/3gpp"},
{"3gp", "video/3gpp"},
{"mp4", "video/mp4"},
{"mpeg", "video/mpeg"},
{"mpg", "video/mpeg"},
{"mov", "video/quicktime"},
{"webm", "video/webm"},
{"flv", "video/x-flv"},
{"m4v", "video/x-m4v"},
{"mng", "video/x-mng"},
{"asx", "video/x-ms-asf"},
{"asf", "video/x-ms-asf"},
{"wmv", "video/x-ms-wmv"},
{"avi", "video/x-msvideo"},
{"ts", "video/MP2T"},
{"m3u8", "application/x-mpegURL"},
{"apk", "application/vnd.android.package-archive"}
};
const static std::string defaultType("application/octet-stream");
std::string::size_type last_pos = name.find_last_of('.');
std::string::size_type first_pos = name.find_first_of('.');
std::string prefix, ext, ext2;
if (last_pos == std::string::npos) {
return defaultType;
}
// extract the last extension
if (last_pos != std::string::npos) {
ext = name.substr(1 + last_pos, std::string::npos);
}
if (last_pos != std::string::npos) {
if (first_pos != std::string::npos && first_pos < last_pos) {
prefix = name.substr(0, last_pos);
// Now get the second to last file extension
std::string::size_type next_pos = prefix.find_last_of('.');
if (next_pos != std::string::npos) {
ext2 = prefix.substr(1 + next_pos, std::string::npos);
}
}
}
ext = ToLower(ext.c_str());
auto iter = mimeType.find(ext);
if (iter != mimeType.end()) {
return (*iter).second;
}
if (first_pos == last_pos) {
return defaultType;
}
ext2 = ToLower(ext2.c_str());
iter = mimeType.find(ext2);
if (iter != mimeType.end()) {
return (*iter).second;
}
return defaultType;
}
std::string AlibabaCloud::OSS::CombineHostString(
const std::string &endpoint,
const std::string &bucket,
bool isCname)
{
Url url(endpoint);
if (url.scheme().empty()) {
url.setScheme(Http::SchemeToString(Http::HTTP));
}
if (!bucket.empty() && !isCname && !IsIp(url.host())) {
std::string host(bucket);
host.append(".").append(url.host());
url.setHost(host);
}
std::ostringstream out;
out << url.scheme() << "://" << url.authority();
return out.str();
}
std::string AlibabaCloud::OSS::CombinePathString(
const std::string &endpoint,
const std::string &bucket,
const std::string &key)
{
Url url(endpoint);
std::string path;
path = "/";
if (IsIp(url.host())) {
path.append(bucket).append("/");
}
path.append(UrlEncode(key));
return path;
}
std::string AlibabaCloud::OSS::CombineRTMPString(
const std::string &endpoint,
const std::string &bucket,
bool isCname)
{
Url url(endpoint);
if (!bucket.empty() && !isCname && !IsIp(url.host())) {
std::string host(bucket);
host.append(".").append(url.host());
url.setHost(host);
}
std::ostringstream out;
out << "rtmp://" << url.authority();
return out.str();
}
std::string AlibabaCloud::OSS::CombineQueryString(const ParameterCollection ¶meters)
{
std::stringstream ss;
if (!parameters.empty()) {
for (const auto &p : parameters)
{
if (p.second.empty())
ss << "&" << UrlEncode(p.first);
else
ss << "&" << UrlEncode(p.first) << "=" << UrlEncode(p.second);
}
}
return ss.str().substr(1);
}
std::streampos AlibabaCloud::OSS::GetIOStreamLength(std::iostream &stream)
{
auto currentPos = stream.tellg();
if (currentPos == static_cast<std::streampos>(-1)) {
currentPos = 0;
stream.clear();
}
stream.seekg(0, stream.end);
auto streamSize = stream.tellg();
stream.seekg(currentPos, stream.beg);
return streamSize;
}
const char *AlibabaCloud::OSS::ToStorageClassName(StorageClass storageClass)
{
static const char *StorageClassName[] = { "Standard", "IA", "Archive", "ColdArchive" };
return StorageClassName[storageClass - StorageClass::Standard];
}
StorageClass AlibabaCloud::OSS::ToStorageClassType(const char *name)
{
std::string storageName = ToLower(name);
if(!storageName.compare("ia")) return StorageClass::IA;
else if (!storageName.compare("archive")) return StorageClass::Archive;
else if (!storageName.compare("coldarchive")) return StorageClass::ColdArchive;
else return StorageClass::Standard;
}
const char *AlibabaCloud::OSS::ToAclName(CannedAccessControlList acl)
{
static const char *AclName[] = { "private", "public-read", "public-read-write", "default"};
return AclName[acl - CannedAccessControlList::Private];
}
CannedAccessControlList AlibabaCloud::OSS::ToAclType(const char *name)
{
std::string aclName = ToLower(name);
if (!aclName.compare("private")) return CannedAccessControlList::Private;
else if (!aclName.compare("public-read")) return CannedAccessControlList::PublicRead;
else if (!aclName.compare("public-read-write")) return CannedAccessControlList::PublicReadWrite;
else return CannedAccessControlList::Default;
}
const char *AlibabaCloud::OSS::ToCopyActionName(CopyActionList action)
{
static const char *ActionName[] = { "COPY", "REPLACE"};
return ActionName[action - CopyActionList::Copy];
}
const char *AlibabaCloud::OSS::ToRuleStatusName(RuleStatus status)
{
static const char *StatusName[] = { "Enabled", "Disabled" };
return StatusName[status - RuleStatus::Enabled];
}
RuleStatus AlibabaCloud::OSS::ToRuleStatusType(const char *name)
{
std::string statusName = ToLower(name);
if (!statusName.compare("enabled")) return RuleStatus::Enabled;
else return RuleStatus::Disabled;
}
const char *AlibabaCloud::OSS::ToLiveChannelStatusName(LiveChannelStatus status)
{
if(status > LiveChannelStatus::LiveStatus)
return "";
static const char *StatusName[] = { "enabled", "disabled", "idle", "live" };
return StatusName[status - LiveChannelStatus::EnabledStatus];
}
LiveChannelStatus AlibabaCloud::OSS::ToLiveChannelStatusType(const char *name)
{
std::string statusName = ToLower(name);
if (!statusName.compare("enabled")) return LiveChannelStatus::EnabledStatus;
else if (!statusName.compare("disabled")) return LiveChannelStatus::DisabledStatus;
else if (!statusName.compare("idle")) return LiveChannelStatus::IdleStatus;
else if (!statusName.compare("live")) return LiveChannelStatus::LiveStatus;
else return LiveChannelStatus::UnknownStatus;
}
const char* AlibabaCloud::OSS::ToRequestPayerName(RequestPayer payer)
{
static const char* PayerName[] = { "NotSet", "BucketOwner", "Requester"};
return PayerName[static_cast<int>(payer) - static_cast<int>(RequestPayer::NotSet)];
}
RequestPayer AlibabaCloud::OSS::ToRequestPayer(const char* name)
{
std::string statusName = ToLower(name);
if (!statusName.compare("bucketowner")) return RequestPayer::BucketOwner;
else if (!statusName.compare("requester")) return RequestPayer::Requester;
else return RequestPayer::NotSet;
}
const char* AlibabaCloud::OSS::ToSSEAlgorithmName(SSEAlgorithm sse)
{
static const char* StatusName[] = { "NotSet", "KMS", "AES256" };
return StatusName[static_cast<int>(sse) - static_cast<int>(SSEAlgorithm::NotSet)];
}
SSEAlgorithm AlibabaCloud::OSS::ToSSEAlgorithm(const char* name)
{
std::string statusName = ToLower(name);
if (!statusName.compare("kms")) return SSEAlgorithm::KMS;
else if (!statusName.compare("aes256")) return SSEAlgorithm::AES256;
else return SSEAlgorithm::NotSet;
}
DataRedundancyType AlibabaCloud::OSS::ToDataRedundancyType(const char* name)
{
std::string storageName = ToLower(name);
if (!storageName.compare("lrs")) return DataRedundancyType::LRS;
else if (!storageName.compare("zrs")) return DataRedundancyType::ZRS;
else return DataRedundancyType::NotSet;
}
const char* AlibabaCloud::OSS::ToDataRedundancyTypeName(DataRedundancyType type)
{
static const char* typeName[] = { "NotSet", "LRS", "ZRS" };
return typeName[static_cast<int>(type) - static_cast<int>(DataRedundancyType::NotSet)];
}
const char * AlibabaCloud::OSS::ToVersioningStatusName(VersioningStatus status)
{
static const char *StatusName[] = { "NotSet", "Enabled", "Suspended" };
return StatusName[static_cast<int>(status) - static_cast<int>(VersioningStatus::NotSet)];
}
VersioningStatus AlibabaCloud::OSS::ToVersioningStatusType(const char *name)
{
std::string statusName = ToLower(name);
if (!statusName.compare("enabled")) return VersioningStatus::Enabled;
else if (!statusName.compare("suspended")) return VersioningStatus::Suspended;
else return VersioningStatus::NotSet;
}
const char* AlibabaCloud::OSS::ToInventoryFormatName(InventoryFormat status)
{
static const char* StatusName[] = { "NotSet", "CSV"};
return StatusName[static_cast<int>(status) - static_cast<int>(InventoryFormat::NotSet)];
}
InventoryFormat AlibabaCloud::OSS::ToInventoryFormatType(const char* name)
{
std::string statusName = ToLower(name);
if (!statusName.compare("csv")) return InventoryFormat::CSV;
else return InventoryFormat::NotSet;
}
const char* AlibabaCloud::OSS::ToInventoryFrequencyName(InventoryFrequency status)
{
static const char* StatusName[] = { "NotSet", "Daily", "Weekly" };
return StatusName[static_cast<int>(status) - static_cast<int>(InventoryFrequency::NotSet)];
}
InventoryFrequency AlibabaCloud::OSS::ToInventoryFrequencyType(const char* name)
{
std::string statusName = ToLower(name);
if (!statusName.compare("daily")) return InventoryFrequency::Daily;
else if (!statusName.compare("weekly")) return InventoryFrequency::Weekly;
else return InventoryFrequency::NotSet;
}
const char* AlibabaCloud::OSS::ToInventoryOptionalFieldName(InventoryOptionalField status)
{
static const char* StatusName[] = { "NotSet", "Size", "LastModifiedDate", "ETag", "StorageClass", "IsMultipartUploaded", "EncryptionStatus" };
return StatusName[static_cast<int>(status) - static_cast<int>(InventoryOptionalField::NotSet)];
}
InventoryOptionalField AlibabaCloud::OSS::ToInventoryOptionalFieldType(const char* name)
{
std::string statusName = ToLower(name);
if (!statusName.compare("size")) return InventoryOptionalField::Size;
else if (!statusName.compare("lastmodifieddate")) return InventoryOptionalField::LastModifiedDate;
else if (!statusName.compare("etag")) return InventoryOptionalField::ETag;
else if (!statusName.compare("storageclass")) return InventoryOptionalField::StorageClass;
else if (!statusName.compare("ismultipartuploaded")) return InventoryOptionalField::IsMultipartUploaded;
else if (!statusName.compare("encryptionstatus")) return InventoryOptionalField::EncryptionStatus;
else return InventoryOptionalField::NotSet;
}
const char* AlibabaCloud::OSS::ToInventoryIncludedObjectVersionsName(InventoryIncludedObjectVersions status)
{
static const char* StatusName[] = { "NotSet", "All", "Current" };
return StatusName[static_cast<int>(status) - static_cast<int>(InventoryIncludedObjectVersions::NotSet)];
}
InventoryIncludedObjectVersions AlibabaCloud::OSS::ToInventoryIncludedObjectVersionsType(const char* name)
{
std::string statusName = ToLower(name);
if (!statusName.compare("all")) return InventoryIncludedObjectVersions::All;
else if (!statusName.compare("current")) return InventoryIncludedObjectVersions::Current;
else return InventoryIncludedObjectVersions::NotSet;
}
std::string AlibabaCloud::OSS::ToInventoryBucketFullName(const std::string& name)
{
std::string fullName = "acs:oss:::";
return fullName.append(name);
}
std::string AlibabaCloud::OSS::ToInventoryBucketShortName(const char* name)
{
std::string name_ = ToLower(name);
std::string shortName;
if (!name_.compare(0, 10, "acs:oss:::")) {
shortName.append(name + 10);
}
return shortName;
}
const char * AlibabaCloud::OSS::ToTierTypeName(TierType status)
{
static const char *StatusName[] = { "Expedited", "Standard", "Bulk" };
return StatusName[static_cast<int>(status) - static_cast<int>(TierType::Expedited)];
}
TierType AlibabaCloud::OSS::ToTierType(const char *name)
{
std::string statusName = ToLower(name);
if (!statusName.compare("expedited")) return TierType::Expedited;
else if (!statusName.compare("bulk")) return TierType::Bulk;
else return TierType::Standard;
}
#if (!OSS_DISABLE_RESUAMABLE) || (!OSS_DISABLE_ENCRYPTION)
std::map<std::string, std::string> AlibabaCloud::OSS::JsonStringToMap(const std::string& jsonStr)
{
std::map<std::string, std::string> valueMap;
Json::Value root;
Json::CharReaderBuilder rbuilder;
std::stringstream input(jsonStr);
std::string errMsg;
if (Json::parseFromStream(rbuilder, input, &root, &errMsg)) {
for (auto it = root.begin(); it != root.end(); ++it)
{
valueMap[it.key().asString()] = (*it).asString();
}
}
return valueMap;
}
std::string AlibabaCloud::OSS::MapToJsonString(const std::map<std::string, std::string>& map)
{
if (map.empty()) {
return "";
}
Json::Value root;
for (const auto& it : map) {
root[it.first] = it.second;
}
Json::StreamWriterBuilder builder;
builder["indentation"] = "";
return Json::writeString(builder, root);
}
#endif
| YifuLiu/AliOS-Things | components/oss/src/utils/Utils.cc | C++ | apache-2.0 | 39,021 |
/*
* 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 <ctime>
#include <iostream>
#include <alibabacloud/oss/Types.h>
namespace AlibabaCloud
{
namespace OSS
{
#define UNUSED_PARAM(x) ((void)(x))
std::string ComputeContentMD5(const std::string& data);
std::string ComputeContentMD5(const char *data, size_t size);
std::string ComputeContentMD5(std::istream & stream);
std::string ComputeContentETag(const std::string& data);
std::string ComputeContentETag(const char *data, size_t size);
std::string ComputeContentETag(std::istream & stream);
std::string GenerateUuid();
std::string UrlEncode(const std::string &src);
std::string UrlDecode(const std::string &src);
std::string Base64Encode(const std::string &src);
std::string Base64Encode(const ByteBuffer& buffer);
std::string Base64Encode(const char *src, int len);
std::string Base64EncodeUrlSafe(const std::string &src);
std::string Base64EncodeUrlSafe(const char *src, int len);
std::string XmlEscape(const std::string& value);
ByteBuffer Base64Decode(const char *src, int len);
ByteBuffer Base64Decode(const std::string &src);
void StringReplace(std::string &src, const std::string &s1, const std::string &s2);
std::string LeftTrim(const char* source);
std::string RightTrim(const char* source);
std::string Trim(const char* source);
std::string LeftTrimQuotes(const char* source);
std::string RightTrimQuotes(const char* source);
std::string TrimQuotes(const char* source);
std::string ToLower(const char* source);
std::string ToUpper(const char* source);
std::string ToGmtTime(std::time_t &t);
std::string ToUtcTime(std::time_t &t);
std::time_t UtcToUnixTime(const std::string &t);
bool IsIp(const std::string &host);
bool IsValidBucketName(const std::string &bucketName);
bool IsValidObjectKey(const std::string &key);
bool IsValidLoggingPrefix(const std::string &prefix);
bool IsValidChannelName(const std::string &channelName);
bool IsValidPlayListName(const std::string &playListName);
bool IsValidTagKey(const std::string &key);
bool IsValidTagValue(const std::string &value);
const std::string &LookupMimeType(const std::string& name);
std::string CombineHostString(const std::string &endpoint, const std::string &bucket, bool isCname);
std::string CombinePathString(const std::string &endpoint, const std::string &bucket, const std::string &key);
std::string CombineQueryString(const ParameterCollection ¶meters);
std::string CombineRTMPString(const std::string &endpoint, const std::string &bucket, bool isCname);
std::streampos GetIOStreamLength(std::iostream &stream);
const char *ToStorageClassName(StorageClass storageClass);
StorageClass ToStorageClassType(const char *name);
const char *ToAclName(CannedAccessControlList acl);
CannedAccessControlList ToAclType(const char *name);
const char * ToCopyActionName(CopyActionList action);
const char * ToRuleStatusName(RuleStatus status);
RuleStatus ToRuleStatusType(const char *name);
const char * ToLiveChannelStatusName(LiveChannelStatus status);
LiveChannelStatus ToLiveChannelStatusType(const char *name);
const char* ToRequestPayerName(RequestPayer payer);
RequestPayer ToRequestPayer(const char* name);
const char* ToSSEAlgorithmName(SSEAlgorithm sse);
SSEAlgorithm ToSSEAlgorithm(const char* name);
DataRedundancyType ToDataRedundancyType(const char* name);
const char* ToDataRedundancyTypeName(DataRedundancyType type);
const char * ToVersioningStatusName(VersioningStatus status);
VersioningStatus ToVersioningStatusType(const char *name);
const char * ToInventoryFormatName(InventoryFormat status);
InventoryFormat ToInventoryFormatType(const char* name);
const char * ToInventoryFrequencyName(InventoryFrequency status);
InventoryFrequency ToInventoryFrequencyType(const char* name);
const char * ToInventoryOptionalFieldName(InventoryOptionalField status);
InventoryOptionalField ToInventoryOptionalFieldType(const char* name);
const char * ToInventoryIncludedObjectVersionsName(InventoryIncludedObjectVersions status);
InventoryIncludedObjectVersions ToInventoryIncludedObjectVersionsType(const char* name);
std::string ToInventoryBucketFullName(const std::string& name);
std::string ToInventoryBucketShortName(const char* name);
const char * ToTierTypeName(TierType status);
TierType ToTierType(const char *name);
#if (!OSS_DISABLE_RESUAMABLE) || (!OSS_DISABLE_ENCRYPTION)
std::map<std::string, std::string> JsonStringToMap(const std::string& jsonStr);
std::string MapToJsonString(const std::map<std::string, std::string>& map);
#endif
}
}
| YifuLiu/AliOS-Things | components/oss/src/utils/Utils.h | C++ | apache-2.0 | 5,419 |
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <aos/flashpart.h>
#include <aos/hal/flash.h>
#include "ota_log.h"
#include "ota_import.h"
#include "ota_hal_os.h"
int ota_is_download_mode(void)
{
int ret = 0;
ota_boot_param_t param = { 0, };
memset(¶m, 0, sizeof(ota_boot_param_t));
ret = ota_read_parameter(¶m);
if (ret < 0) {
return 0;
}
if ((param.upg_status == OTA_TRANSPORT) && (param.upg_flag != 0xffff)) {
OTA_LOG_I("OTA running status:0x%04x\n", param.upg_status);
return 1;
}
OTA_LOG_I("ota is status:%d param crc:0x%04x\n", param.upg_status, param.param_crc);
return ret;
}
int ota_read_parameter(ota_boot_param_t *ota_param)
{
int ret = 0;
unsigned short patch_crc = 0;
aos_flashpart_ref_t part_ref = AOS_DEV_REF_INIT_VAL;
aos_status_t r;
if (ota_param == NULL) {
ret = OTA_UPGRADE_PARAM_FAIL;
goto OTA_READ_PARAM_OVER;
}
if (aos_flashpart_get(&part_ref, HAL_PARTITION_PARAMETER_1)) {
OTA_LOG_E("open ota param1 partition failed");
ret = OTA_UPGRADE_PARAM_FAIL;
goto OTA_READ_PARAM_OVER;
}
memset(ota_param, 0, sizeof(ota_boot_param_t));
r = aos_flashpart_read(&part_ref, 0, ota_param, sizeof(ota_boot_param_t));
if (r < 0 || r == AOS_FLASH_ECC_ERROR) {
OTA_LOG_E("read failed:%d", (int)r);
ret = OTA_UPGRADE_PARAM_FAIL;
goto OTA_READ_PARAM_OVER;
}
patch_crc = ota_get_data_crc16((const unsigned char *)ota_param, sizeof(ota_boot_param_t) - sizeof(unsigned short));
OTA_LOG_I("ota param crc:0x%04x cal:0x%04x\n", ota_param->param_crc, patch_crc);
if (patch_crc != ota_param->param_crc) {
OTA_LOG_E("ota param crc err");
ret = OTA_UPGRADE_PARAM_FAIL;
}
OTA_READ_PARAM_OVER:
if (aos_dev_ref_is_valid(&part_ref))
aos_flashpart_put(&part_ref);
return ret;
}
int ota_update_parameter(ota_boot_param_t *ota_param)
{
int ret = 0;
ota_boot_param_t comp_buf;
size_t len = sizeof(ota_boot_param_t);
size_t block_size;
aos_flashpart_ref_t part_ref = AOS_DEV_REF_INIT_VAL;
aos_flashpart_info_t part_info;
aos_flash_info_t flash_info;
aos_status_t r;
if (ota_param == NULL) {
ret = OTA_UPGRADE_PARAM_FAIL;
goto OTA_UPGRADE_PARAN_OVER;
}
ota_param->param_crc = ota_get_data_crc16((const unsigned char *)ota_param,
sizeof(ota_boot_param_t) - sizeof(unsigned short));
OTA_LOG_I("ota update param crc:0x%04x flag:0x%04x boot_type:%d len = %d\n",
ota_param->param_crc, ota_param->upg_flag, ota_param->boot_type, len);
memset(&comp_buf, 0, len);
if (aos_flashpart_get(&part_ref, HAL_PARTITION_PARAMETER_1) ||
aos_flashpart_get_info(&part_ref, &part_info, &flash_info)) {
OTA_LOG_E("open ota param1 partition failed");
ret = OTA_UPGRADE_PARAM_FAIL;
goto OTA_UPGRADE_PARAN_OVER;
}
block_size = flash_info.page_data_size * flash_info.pages_per_block;
if (aos_flashpart_erase(&part_ref, 0, (len + block_size - 1) / block_size * block_size)) {
OTA_LOG_E("erase fail!");
ret = OTA_UPGRADE_PARAM_FAIL;
goto OTA_UPGRADE_PARAN_OVER;
}
if (aos_flashpart_write(&part_ref, 0, ota_param, len)) {
OTA_LOG_E("write fail!");
ret = OTA_UPGRADE_PARAM_FAIL;
goto OTA_UPGRADE_PARAN_OVER;
}
r = aos_flashpart_read(&part_ref, 0, &comp_buf, len);
if (r < 0 || r == AOS_FLASH_ECC_ERROR) {
OTA_LOG_E("read failed:%d", (int)r);
ret = OTA_UPGRADE_PARAM_FAIL;
goto OTA_UPGRADE_PARAN_OVER;
}
if (memcmp(ota_param, &comp_buf, len) != 0) {
ret = OTA_UPGRADE_PARAM_FAIL;
OTA_LOG_E("ota save param failed\r");
}
OTA_UPGRADE_PARAN_OVER:
if (aos_dev_ref_is_valid(&part_ref))
aos_flashpart_put(&part_ref);
OTA_LOG_I("ota update param over\n");
return ret;
}
unsigned short ota_get_upgrade_flag(void)
{
int ret = 0;
unsigned short flag = 0;
ota_boot_param_t ota_param = { 0, };
ret = ota_read_parameter(&ota_param);
if (ret < 0) {
return 0xffff;
}
flag = ota_param.upg_flag;
return flag;
}
int ota_update_upg_flag(unsigned short flag)
{
int ret = 0;
ota_boot_param_t ota_param = { 0, };
OTA_LOG_I("upg_flag:0x%x\n", flag);
ret = ota_read_parameter(&ota_param);
if (ret < 0) {
return ret;
}
ota_param.upg_flag = flag;
ret = ota_update_parameter(&ota_param);
return 0;
}
int ota_clear_paramters()
{
int ret = 0;
size_t block_size;
aos_flashpart_ref_t part_ref = AOS_DEV_REF_INIT_VAL;
aos_flashpart_info_t part_info;
aos_flash_info_t flash_info;
if (aos_flashpart_get(&part_ref, HAL_PARTITION_PARAMETER_1) ||
aos_flashpart_get_info(&part_ref, &part_info, &flash_info)) {
OTA_LOG_E("open ota param1 partition failed");
ret = OTA_UPGRADE_PARAM_FAIL;
goto OTA_CLEAR_PARAM_OVER;
}
block_size = flash_info.page_data_size * flash_info.pages_per_block;
if (aos_flashpart_erase(&part_ref, 0, (sizeof(ota_boot_param_t) + block_size - 1) / block_size * block_size)) {
OTA_LOG_E("erase fail! ");
ret = OTA_UPGRADE_PARAM_FAIL;
goto OTA_CLEAR_PARAM_OVER;
}
OTA_CLEAR_PARAM_OVER:
if (aos_dev_ref_is_valid(&part_ref))
aos_flashpart_put(&part_ref);
return ret;
}
unsigned int ota_parse_ota_type(unsigned char *buf, unsigned int len)
{
int upg_flag = 0;
unsigned char xz_header[6] = { 0xFD, '7', 'z', 'X', 'Z', 0x00, };
if ((buf != NULL) && (len >= 8)) {
if (memcmp(buf, "BSDIFF40", 8) == 0) {
upg_flag = OTA_UPGRADE_DIFF;
} else if (memcmp(buf, xz_header, 6) == 0) {
upg_flag = OTA_UPGRADE_XZ;
} else {
upg_flag = OTA_UPGRADE_ALL;
}
}
OTA_LOG_I("ota header:0x%x", upg_flag);
return upg_flag;
}
| YifuLiu/AliOS-Things | components/ota/hal/ota_hal_aos_param.c | C | apache-2.0 | 6,012 |
#include <string.h>
#include <stdlib.h>
#include <stdint.h>
#include <aos/flashpart.h>
#include <aos/hal/flash.h>
#include "ota_log.h"
#include "ota_hal.h"
#include "ota_import.h"
#include "ota_hal_os.h"
unsigned char *ota_cache = NULL;
unsigned int ota_cache_len = 0;
unsigned int ota_fw_size = 0;
unsigned int ota_receive_total_len = 0;
static uint32_t boot_part = HAL_PARTITION_OTA_TEMP;
static ota_crc16_ctx ctx = { 0, };
static aos_flashpart_ref_t ota_part = AOS_DEV_REF_INIT_VAL;
OTA_WEAK int ota_get_running_index(void)
{
return 0;
}
OTA_WEAK int ota_hal_init(ota_boot_param_t *param)
{
int ret = 0;
size_t erase_len;
uint32_t part_id;
aos_flashpart_info_t part_info;
aos_flash_info_t flash_info;
if (param == NULL) {
ret = OTA_INIT_FAIL;
goto OTA_HAL_INIT_EXIT;
}
if (ota_get_running_index() == 0)
part_id = HAL_PARTITION_OTA_TEMP;
else
part_id = HAL_PARTITION_APPLICATION;
OTA_LOG_I("update partition %d\r\n", (int)part_id);
if (aos_flashpart_get(&ota_part, part_id) || aos_flashpart_get_info(&ota_part, &part_info, &flash_info)) {
OTA_LOG_E("open ota temp partition failed");
ret = OTA_INIT_FAIL;
goto OTA_HAL_INIT_EXIT;
}
if (param->len == 0 ||
param->len > part_info.block_count * flash_info.pages_per_block * flash_info.page_data_size) {
OTA_LOG_E("bin file size error!");
ret = OTA_INIT_FAIL;
goto OTA_HAL_INIT_EXIT;
}
ota_receive_total_len = 0;
ota_fw_size = param->len;
ota_cache = ota_malloc(OTA_FLASH_WRITE_CACHE_SIZE);
if (NULL == ota_cache) {
ret = OTA_INIT_FAIL;
goto OTA_HAL_INIT_EXIT;
}
erase_len = param->len + flash_info.pages_per_block * flash_info.page_data_size - 1;
erase_len /= flash_info.pages_per_block * flash_info.page_data_size;
erase_len *= flash_info.pages_per_block * flash_info.page_data_size;
if (aos_flashpart_erase(&ota_part, 0, erase_len)) {
ret = OTA_INIT_FAIL;
OTA_LOG_E("erase fail!");
goto OTA_HAL_INIT_EXIT;
}
ota_crc16_init(&ctx);
OTA_LOG_I("ota init part:%d len:%d\n", (int)part_id, param->len);
OTA_HAL_INIT_EXIT:
if (ret != 0) {
if (NULL != ota_cache) {
ota_free(ota_cache);
ota_cache = NULL;
}
if (aos_dev_ref_is_valid(&ota_part))
aos_flashpart_put(&ota_part);
OTA_LOG_E("ota init fail!");
}
return ret;
}
OTA_WEAK int ota_hal_final(void)
{
return 0;
}
OTA_WEAK int ota_hal_write(unsigned int *off, char *in_buf, unsigned int in_buf_len)
{
int ret = 0;
int tocopy = 0;
if (off == NULL || in_buf_len > OTA_FLASH_WRITE_CACHE_SIZE) {
return OTA_UPGRADE_WRITE_FAIL;
}
if (in_buf_len <= OTA_FLASH_WRITE_CACHE_SIZE - ota_cache_len) {
tocopy = in_buf_len;
} else {
tocopy = OTA_FLASH_WRITE_CACHE_SIZE - ota_cache_len;
}
/* Start from last byte of remaing data */
memcpy(ota_cache + ota_cache_len, in_buf, tocopy);
ota_cache_len += tocopy;
if (ota_cache_len == OTA_FLASH_WRITE_CACHE_SIZE) {
if (aos_flashpart_write(&ota_part, *off, ota_cache, OTA_FLASH_WRITE_CACHE_SIZE)) {
ret = OTA_UPGRADE_WRITE_FAIL;
goto EXIT;
}
*off += OTA_FLASH_WRITE_CACHE_SIZE;
ota_cache_len = 0;
ota_crc16_update(&ctx, ota_cache, OTA_FLASH_WRITE_CACHE_SIZE);
}
/* keep remaining data */
if (in_buf_len - tocopy > 0) {
/* Now ota_cache only contains remaining data */
memcpy(ota_cache, in_buf + tocopy, in_buf_len - tocopy);
ota_cache_len = in_buf_len - tocopy;
}
ota_receive_total_len += in_buf_len;
if (ota_receive_total_len == ota_fw_size) {
if (ota_cache_len != 0) {
if (aos_flashpart_write(&ota_part, *off, ota_cache, ota_cache_len)) {
ret = OTA_UPGRADE_WRITE_FAIL;
goto EXIT;
}
*off += ota_cache_len;
ota_crc16_update(&ctx, ota_cache, ota_cache_len);
}
if (ota_cache != NULL) {
ota_free(ota_cache);
ota_cache = NULL;
}
if (aos_dev_ref_is_valid(&ota_part))
aos_flashpart_put(&ota_part);
}
EXIT:
if (ret < 0) {
if (ota_cache != NULL) {
ota_free(ota_cache);
ota_cache = NULL;
}
if (aos_dev_ref_is_valid(&ota_part))
aos_flashpart_put(&ota_part);
OTA_LOG_E("ota_write err:%d", ret);
}
return ret;
}
OTA_WEAK int ota_hal_rollback_platform_hook(void)
{
return 0;
}
OTA_WEAK int ota_hal_rollback(void)
{
int ret = 0;
ota_boot_param_t param;
aos_flashpart_ref_t temp_part = AOS_DEV_REF_INIT_VAL;
aos_status_t r;
memset(¶m, 0, sizeof(ota_boot_param_t));
if (aos_flashpart_get(&temp_part, HAL_PARTITION_PARAMETER_1)) {
OTA_LOG_E("open ota temp partition failed");
ret = -1;
goto OTA_ROLLBACK;
}
r = aos_flashpart_read(&temp_part, 0, ¶m, sizeof(ota_boot_param_t));
if (r < 0 || r == AOS_FLASH_ECC_ERROR) {
OTA_LOG_E("rollback err1:%d", (int)r);
ret = -1;
goto OTA_ROLLBACK;
}
if ((param.boot_count != 0) && (param.boot_count != 0xff)) {
param.upg_flag = 0;
param.boot_count = 0; /* clear bootcount to avoid rollback */
ret = ota_update_parameter(¶m);
if (ret < 0) {
OTA_LOG_E("rollback err2:%d", ret);
goto OTA_ROLLBACK;
}
ret = ota_hal_rollback_platform_hook();
if (ret < 0) {
OTA_LOG_E("ota_hal_rollback_platform_hook fail!");
goto OTA_ROLLBACK;
}
}
OTA_ROLLBACK:
if (aos_dev_ref_is_valid(&temp_part))
aos_flashpart_put(&temp_part);
if (ret != 0)
OTA_LOG_E("rollback err3:%d", ret);
return ret;
}
OTA_WEAK int ota_hal_reboot_bank(void)
{
return 0;
}
OTA_WEAK void ota_hal_image_crc16(unsigned short *outResult)
{
ota_crc16_final(&ctx, outResult);
}
OTA_WEAK int ota_hal_platform_boot_type(void)
{
return 0;
}
OTA_WEAK int ota_hal_boot_type()
{
int ret = -1;
ret = ota_hal_platform_boot_type();
if (ret < 0) {
OTA_LOG_E("get boot type failed!");
}
return ret;
}
OTA_WEAK int ota_hal_boot(ota_boot_param_t *param)
{
int ret = OTA_UPGRADE_WRITE_FAIL;
uint32_t src_part_id;
uint32_t dst_part_id;
aos_flashpart_ref_t temp_part = AOS_DEV_REF_INIT_VAL;
aos_flashpart_info_t part_info;
aos_flash_info_t flash_info;
if (ota_get_running_index() == 0) {
src_part_id = HAL_PARTITION_OTA_TEMP;
dst_part_id = HAL_PARTITION_APPLICATION;
} else {
src_part_id = HAL_PARTITION_APPLICATION;
dst_part_id = HAL_PARTITION_OTA_TEMP;
}
if (aos_flashpart_get(&temp_part, src_part_id) || aos_flashpart_get_info(&temp_part, &part_info, &flash_info)) {
if (aos_dev_ref_is_valid(&temp_part))
aos_flashpart_put(&temp_part);
goto OTA_HAL_BOOT_OVER;
}
aos_flashpart_put(&temp_part);
param->src_adr = part_info.block_start * flash_info.pages_per_block * flash_info.page_data_size;
if (aos_flashpart_get(&temp_part, dst_part_id) || aos_flashpart_get_info(&temp_part, &part_info, &flash_info)) {
if (aos_dev_ref_is_valid(&temp_part))
aos_flashpart_put(&temp_part);
goto OTA_HAL_BOOT_OVER;
}
aos_flashpart_put(&temp_part);
param->dst_adr = part_info.block_start * flash_info.pages_per_block * flash_info.page_data_size;
param->old_size = part_info.block_count * flash_info.pages_per_block * flash_info.page_data_size;
if (param->crc == 0 || param->crc == 0xffff) {
OTA_LOG_I("calculate image crc");
ota_hal_image_crc16(¶m->crc);
}
if (param->upg_flag == OTA_UPGRADE_ALL) {
int tmp_type = ota_hal_boot_type();
if (tmp_type < 0) {
OTA_LOG_E("get platform boot type err!");
goto OTA_HAL_BOOT_OVER;
}
param->boot_type = (unsigned char)tmp_type;
} else {
param->boot_type = 0;
}
ret = ota_update_parameter(param);
if (ret < 0) {
OTA_LOG_E("update param err!");
goto OTA_HAL_BOOT_OVER;
}
if (param->upg_flag == OTA_UPGRADE_ALL) {
ret = ota_hal_final();
if (ret < 0) {
OTA_LOG_E("clear user boot count fail!");
goto OTA_HAL_BOOT_OVER;
}
}
OTA_LOG_I("OTA after finish dst:0x%08x src:0x%08x len:0x%08x, crc:0x%04x param crc:0x%04x upg_flag:0x%04x \r\n", param->dst_adr, param->src_adr, param->len, param->crc, param->param_crc, param->upg_flag);
OTA_HAL_BOOT_OVER:
if (ret < 0) {
OTA_LOG_E("set boot info failed!");
}
return ret;
}
OTA_WEAK int ota_hal_read(unsigned int *off, char *out_buf, unsigned int out_buf_len)
{
int ret = 0;
uint32_t part_id;
aos_flashpart_ref_t temp_part = AOS_DEV_REF_INIT_VAL;
aos_status_t r;
if (ota_get_running_index() == 0)
part_id = HAL_PARTITION_OTA_TEMP;
else
part_id = HAL_PARTITION_APPLICATION;
boot_part = part_id;
if (aos_flashpart_get(&temp_part, part_id)) {
OTA_LOG_E("open ota temp partition failed");
ret = -1;
goto OTA_HAL_READ;
}
r = aos_flashpart_read(&temp_part, *off, out_buf, out_buf_len);
if (r < 0 || r == AOS_FLASH_ECC_ERROR) {
OTA_LOG_E("read failed:%d", (int)r);
ret = -1;
goto OTA_HAL_READ;
}
OTA_HAL_READ:
if (aos_dev_ref_is_valid(&temp_part))
aos_flashpart_put(&temp_part);
return ret;
}
| YifuLiu/AliOS-Things | components/ota/hal/ota_hal_aos_plat.c | C | apache-2.0 | 9,749 |
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include "ota_log.h"
#include "ota_import.h"
#include "ota_hal_os.h"
#include "ota_hal_digest.h"
#include "ota_hal.h"
static ota_hash_ctx_t hash_ctx = {0};
static unsigned short upg_flag = 0;
static unsigned char is_header = 0;
#ifdef OTA_CONFIG_LOCAL_RSA
static unsigned int valid_image_len = 0;
static unsigned int calculated_len = 0;
#endif
int ota_int(ota_boot_param_t *param)
{
int ret = 0;
if (param == NULL) {
return OTA_UPGRADE_PARAM_FAIL;
}
is_header = 0;
upg_flag = 0;
#ifdef OTA_CONFIG_LOCAL_RSA
calculated_len = 0;
valid_image_len = param->len - sizeof(ota_image_info_t) - sizeof(ota_sign_info_t);
#endif
ret = ota_hal_init(param);
if (ret == 0) {
ret = ota_hash_init(&hash_ctx, param->hash_type);
}
OTA_LOG_I("ota init ret = %d\r\n", ret);
return ret;
}
int ota_write(unsigned int *off, char *in_buf, unsigned int in_buf_len)
{
int ret = 0;
if ((*off == 0) && (is_header == 0)) {
unsigned char xz_header[6] = { 0xFD, '7', 'z', 'X', 'Z', 0x00 };
if (memcmp(in_buf, "BSDIFF40", 8) == 0) {
upg_flag = OTA_UPGRADE_DIFF;
} else if (memcmp(in_buf, xz_header, 6) == 0) {
upg_flag = OTA_UPGRADE_XZ;
}
OTA_LOG_I("ota header:0x%x\n", upg_flag);
is_header = 1;
}
ret = ota_hal_write(off, in_buf, in_buf_len);
if (ret >= 0) {
#ifdef OTA_CONFIG_LOCAL_RSA
if (calculated_len <= valid_image_len) {
ota_hash_ctx_t tmp_ctx = hash_ctx;
unsigned int tmp_len = 0;
((calculated_len + in_buf_len) <= valid_image_len) ? (tmp_len = in_buf_len) :
(tmp_len = valid_image_len - calculated_len);
ret = ota_hash_update(&hash_ctx, (const unsigned char *)in_buf, tmp_len);
if (ret >= 0) {
calculated_len += in_buf_len;
} else {
hash_ctx = tmp_ctx;
}
}
#else
ret = ota_hash_update(&hash_ctx, (const unsigned char *)in_buf, in_buf_len);
#endif
}
return ret;
}
int ota_read(unsigned int *off, char *out_buf, unsigned int out_buf_len)
{
int ret = 0;
ret = ota_hal_read(off, out_buf, out_buf_len);
return ret;
}
int ota_clear()
{
is_header = 0;
upg_flag = 0;
return ota_clear_paramters();
}
int ota_verify(ota_boot_param_t *param)
{
int ret = OTA_UPGRADE_SET_BOOT_FAIL;
unsigned char hash[32] = {0};
char dst_hash[65] = {0};
if (param == NULL) {
return ret;
}
is_header = 0;
if (upg_flag != 0) {
param->upg_flag = upg_flag;
} else if (param->upg_flag == 0) {
param->upg_flag = OTA_UPGRADE_ALL;
}
memset(hash, 0x00, sizeof(hash));
ret = ota_hash_final(&hash_ctx, hash);
if (ret == 0) {
ret = ota_hex2str(dst_hash, hash, sizeof(dst_hash), sizeof(hash));
if (ret == 0) {
ret = ota_check_hash(param->hash_type, param->hash, (char *)dst_hash);
if (ret < 0) {
OTA_LOG_E("ota verify hash failed!");
return ret;
}
/* verify RSA signature */
#if OTA_CONFIG_LOCAL_RSA
ret = ota_verify_rsa((unsigned char *)param->sign, (const char *)dst_hash, param->hash_type);
if (ret < 0) {
ret = OTA_VERIFY_RSA_FAIL;
return ret;
}
#else
if (strlen(param->sign) > 0) {
ret = ota_verify_rsa((unsigned char *)param->sign, (const char *)dst_hash, param->hash_type);
if (ret < 0) {
ret = OTA_VERIFY_RSA_FAIL;
return ret;
}
}
#endif
/* verify image */
#if !defined CONFIG_PING_PONG_OTA
if ((param->upg_flag != OTA_UPGRADE_DIFF) && (param->upg_flag != OTA_UPGRADE_CUST)) {
ret = ota_check_image(param->len);
if (ret < 0) {
ret = OTA_VERIFY_IMAGE_FAIL;
}
}
#endif
}
}
OTA_LOG_I("ota boot finish ret:%d crc:0x%04x", ret, param->crc);
return ret;
}
int ota_verify_fsfile(ota_boot_param_t *param, char *file_path)
{
int fd = -1;
int ret = OTA_UPGRADE_SET_BOOT_FAIL;
unsigned char hash[32] = {0};
char dst_hash[65] = {0};
char tmp_buf[128] = {0};
unsigned int offset = 0;
unsigned int read_len = 0;
ota_hash_ctx_t tmp_hash_ctx;
if ((param == NULL) || (file_path == NULL)) {
return ret;
}
memset(hash, 0x00, sizeof(hash));
ret = ota_hash_init(&tmp_hash_ctx, param->hash_type);
if (ret < 0) {
OTA_LOG_E("subdev fs file hash init failed\n");
return ret;
}
fd = ota_fopen(file_path, O_RDONLY);
if (fd < 0) {
ret = OTA_UPGRADE_SET_BOOT_FAIL;
OTA_LOG_E("open %s failed\n", file_path);
return ret;
}
OTA_LOG_I("fs size = %d\n", param->len);
while (offset < param->len) {
(param->len - offset >= sizeof(tmp_buf)) ? (read_len = sizeof(tmp_buf)) : (read_len = param->len - offset);
ret = ota_fread(fd, (void *)tmp_buf, read_len);
if (ret < 0) {
OTA_LOG_E("verify fs file read file failed\r\n");
ret = OTA_VERIFY_IMAGE_FAIL;
break;
}
ret = ota_hash_update(&tmp_hash_ctx, (const unsigned char *)tmp_buf, read_len);
if (ret < 0) {
break;
}
offset += read_len;
ota_msleep(5);
}
if (fd >= 0) {
(void)ota_fclose(fd);
}
if (ret < 0) {
OTA_LOG_E("get fs file hash value failed\n");
return ret;
}
ret = ota_hash_final(&tmp_hash_ctx, hash);
if (ret == 0) {
ret = ota_hex2str(dst_hash, hash, sizeof(dst_hash), sizeof(hash));
if (ret == 0) {
ret = ota_check_hash(param->hash_type, param->hash, (char *)dst_hash);
if (ret < 0) {
OTA_LOG_E("ota verify hash failed!");
return ret;
}
/* verify RSA signature */
#if OTA_CONFIG_LOCAL_RSA
ret = ota_verify_rsa((unsigned char *)param->sign, (const char *)dst_hash, param->hash_type);
if (ret < 0) {
ret = OTA_VERIFY_RSA_FAIL;
return ret;
}
#else
if (strlen(param->sign) > 0) {
ret = ota_verify_rsa((unsigned char *)param->sign, (const char*)dst_hash, param->hash_type);
if (ret < 0) {
ret = OTA_VERIFY_RSA_FAIL;
return ret;
}
}
#endif
}
}
OTA_LOG_I("verfiy fs over ret:%d\n", ret);
return ret;
}
| YifuLiu/AliOS-Things | components/ota/hal/ota_hal_ctrl.c | C | apache-2.0 | 6,889 |
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#include <stdlib.h>
#include <string.h>
#include "ota_log.h"
#include "ota_import.h"
#include "ota_hal_digest.h"
#include "mbedtls/sha256.h"
#include "mbedtls/md5.h"
#include "mbedtls/bignum.h"
#include "mbedtls/rsa.h"
/* RSA Public Key:User needs sign in alibaba cloud to get and replace them. */
static unsigned char ota_pubn_buf[256] = {0x00};
static unsigned char ota_pube_buf[3] = {0x01, 0x00, 0x01};
/* SHA256 */
void ota_sha256_free(ota_sha256_context *ctx)
{
mbedtls_sha256_free((mbedtls_sha256_context *)ctx);
}
void ota_sha256_init(ota_sha256_context *ctx)
{
mbedtls_sha256_init((mbedtls_sha256_context *)ctx);
}
void ota_sha256_starts(ota_sha256_context *ctx, int is224)
{
mbedtls_sha256_starts((mbedtls_sha256_context *)ctx, is224);
}
void ota_sha256_update(ota_sha256_context *ctx, const unsigned char *input, unsigned int ilen)
{
mbedtls_sha256_update((mbedtls_sha256_context *)ctx, input, ilen);
}
void ota_sha256_finish(ota_sha256_context *ctx, unsigned char output[32])
{
mbedtls_sha256_finish((mbedtls_sha256_context *)ctx, output);
}
/*MD5*/
void ota_md5_free(ota_md5_context *ctx)
{
mbedtls_md5_free((mbedtls_md5_context *)ctx);
}
void ota_md5_init(ota_md5_context *ctx)
{
mbedtls_md5_init((mbedtls_md5_context *)ctx);
}
void ota_md5_starts(ota_md5_context *ctx)
{
mbedtls_md5_starts_ret((mbedtls_md5_context *)ctx);
}
void ota_md5_update(ota_md5_context *ctx, const unsigned char *input, unsigned int ilen)
{
mbedtls_md5_update((mbedtls_md5_context *)ctx, input, ilen);
}
void ota_md5_finish(ota_md5_context *ctx, unsigned char output[16])
{
mbedtls_md5_finish((mbedtls_md5_context *)ctx, output);
}
/*RSA*/
const unsigned char *ota_rsa_pubkey_n(void)
{
return ota_pubn_buf;
}
const unsigned char *ota_rsa_pubkey_e(void)
{
return ota_pube_buf;
}
unsigned int ota_rsa_pubkey_n_size(void)
{
return sizeof(ota_pubn_buf);
}
unsigned int ota_rsa_pubkey_e_size(void)
{
return sizeof(ota_pube_buf);
}
int ota_rsa_pubkey_verify(const unsigned char *pubkey_n,
const unsigned char *pubkey_e,
unsigned int pubkey_n_size,
unsigned int pubkey_e_size,
const unsigned char *dig,
unsigned int dig_size,
const unsigned char *sig,
unsigned int sig_size)
{
int ret = 0;
mbedtls_rsa_context ctx = {0};
if (pubkey_n == NULL || pubkey_n == NULL || dig == NULL || sig == NULL) {
ret = OTA_VERIFY_RSA_FAIL;
goto EXIT;
}
if (pubkey_n_size == 0 || pubkey_e_size == 0 || sig_size == 0 || dig_size != OTA_SHA256_HASH_SIZE) {
ret = OTA_VERIFY_RSA_FAIL;
goto EXIT;
}
mbedtls_rsa_init(&ctx, MBEDTLS_RSA_PKCS_V15, MBEDTLS_MD_SHA256);
ret = mbedtls_mpi_read_binary(&ctx.N, pubkey_n, pubkey_n_size);
if (0 != ret) {
goto EXIT;
}
ret = mbedtls_mpi_read_binary(&ctx.E, pubkey_e, pubkey_e_size);
if (0 != ret) {
goto EXIT;
}
ctx.len = pubkey_n_size;
ret = mbedtls_rsa_check_pubkey(&ctx);
if (0 != ret) {
goto EXIT;
}
ret = mbedtls_rsa_pkcs1_verify(&ctx, NULL, NULL, MBEDTLS_RSA_PUBLIC, MBEDTLS_MD_SHA256, (unsigned int)0, (const unsigned char *)dig, (const unsigned char *)sig);
if (0 != ret) {
goto EXIT;
}
EXIT:
if (ret != 0) {
OTA_LOG_E("rsa verify ret: 0x%x", ret);
}
mbedtls_rsa_free(&ctx);
return ret;
}
| YifuLiu/AliOS-Things | components/ota/hal/ota_hal_digest.c | C | apache-2.0 | 3,603 |
/**@defgroup ota_hal_digest_api
* @{
* This is an include file of OTA verify interface.
*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#ifndef OTA_HAL_DIGEST_H
#define OTA_HAL_DIGEST_H
#include "ota_agent.h"
#ifdef __cplusplus
extern "C" {
#endif
/***************************************************************
*** OTA verify module: hash:md5/sha256 sign:RSA ***
****************************************************************/
/**
* Struct: MD5 Context.
*/
typedef struct {
unsigned int total[2];
unsigned int state[4];
unsigned char buffer[64];
} ota_md5_context;
/**
* Struct: SHA256 Context.
*/
typedef struct {
unsigned int total[2];
unsigned int state[8];
unsigned char buffer[64];
int is224;
} ota_sha256_context;
/**
* Struct: ota sign context.
*/
typedef struct {
char sign_enable; /* enable sign */
unsigned char sign_value[256]; /* sign value */
} ota_sign_t;
/**
* Struct: ota hash context.
*/
typedef struct {
unsigned char hash_method; /* hash method: md5, sha256 */
union {
ota_md5_context md5_ctx; /* md5 hash context */
ota_sha256_context sha256_ctx; /* sh256 hash context */
};
} ota_hash_ctx_t;
/**
* ota_hash_init ota hash init.
*
* @param[in] ota_hash_ctx_t *ctx OTA hash context
* @param[in] unsigned char type OTA hash type
*
* @return OTA_SUCCESS OTA success.
* @return OTA_VERIFY_MD5_FAIL OTA verfiy MD5 fail.
* @return OTA_VERIFY_SHA2_FAIL OTA verfiy SH256 fail.
* @return OTA_VERIFY_RSA_FAIL OTA verfiy RSA fail.
* @return OTA_VERIFY_IMAGE_FAIL OTA verfiy image fail.
*/
int ota_hash_init(ota_hash_ctx_t *ctx, unsigned char type);
/**
* ota_hash_update ota hash update.
*
* @param[in] ota_hash_ctx_t *ctx OTA hash context
* @param[in] const unsigned char *buf OTA hash buf
* @param[in] unsigned int len OTA hash len
*
* @return OTA_SUCCESS OTA success.
* @return OTA_VERIFY_MD5_FAIL OTA verfiy MD5 fail.
* @return OTA_VERIFY_SHA2_FAIL OTA verfiy SH256 fail.
* @return OTA_VERIFY_RSA_FAIL OTA verfiy RSA fail.
* @return OTA_VERIFY_IMAGE_FAIL OTA verfiy image fail.
*/
int ota_hash_update(ota_hash_ctx_t *ctx, const unsigned char *buf, unsigned int len);
/**
* ota_hash_final OTA final hash.
*
* @param[in] ota_hash_ctx_t *ctx OTA hash context
* @param[in] unsigned char *buf OTA hash digest
*
* @return OTA_SUCCESS OTA success.
* @return OTA_VERIFY_MD5_FAIL OTA verfiy MD5 fail.
* @return OTA_VERIFY_SHA2_FAIL OTA verfiy SH256 fail.
* @return OTA_VERIFY_RSA_FAIL OTA verfiy RSA fail.
* @return OTA_VERIFY_IMAGE_FAIL OTA verfiy image fail.
*/
int ota_hash_final(ota_hash_ctx_t *ctx, unsigned char *dgst);
/**
* ota_verify_rsa OTA verify RSA sign.
*
* @param[in] unsigned char *sign OTA firmware sign
* @param[in] const char *hash OTA firmware hash
* @param[in] unsigned char hash_type OTA hash type
*
* @return OTA_SUCCESS OTA success.
* @return OTA_VERIFY_MD5_FAIL OTA verfiy MD5 fail.
* @return OTA_VERIFY_SHA2_FAIL OTA verfiy SH256 fail.
* @return OTA_VERIFY_RSA_FAIL OTA verfiy RSA fail.
* @return OTA_VERIFY_IMAGE_FAIL OTA verfiy image fail.
*/
int ota_verify_rsa(unsigned char *sign, const char *hash, unsigned char hash_type);
/*Verify API*/
/*SHA256*/
void ota_sha256_free(ota_sha256_context *ctx);
void ota_sha256_init(ota_sha256_context *ctx);
void ota_sha256_starts(ota_sha256_context *ctx, int is224);
void ota_sha256_update(ota_sha256_context *ctx, const unsigned char *input, unsigned int ilen);
void ota_sha256_finish(ota_sha256_context *ctx, unsigned char output[32]);
/*MD5*/
void ota_md5_free(ota_md5_context *ctx);
void ota_md5_init(ota_md5_context *ctx);
void ota_md5_starts(ota_md5_context *ctx);
void ota_md5_update(ota_md5_context *ctx, const unsigned char *input, unsigned int ilen);
void ota_md5_finish(ota_md5_context *ctx, unsigned char output[16]);
/*RSA*/
const unsigned char *ota_rsa_pubkey_n(void);
const unsigned char *ota_rsa_pubkey_e(void);
unsigned int ota_rsa_pubkey_n_size(void);
unsigned int ota_rsa_pubkey_e_size(void);
int ota_rsa_pubkey_verify(const unsigned char *pubkey_n,
const unsigned char *pubkey_e,
unsigned int pubkey_n_size,
unsigned int pubkey_e_size,
const unsigned char *dig,
unsigned int dig_size,
const unsigned char *sig,
unsigned int sig_size);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /*OTA_HAL_DIGEST_H*/
| YifuLiu/AliOS-Things | components/ota/hal/ota_hal_digest.h | C | apache-2.0 | 4,743 |
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include "ota_log.h"
#include "ota_import.h"
#include "ota_hal_os.h"
#include "ota_hal.h"
#include "upack_data_file.h"
OTA_WEAK int ota_fopen(const char *filename, int mode)
{
int fd = -1;
if (filename != NULL) {
fd = open(filename, mode);
}
return fd;
}
OTA_WEAK int ota_fwrite(int fd, const void *buf, unsigned int size)
{
int ret = -1;
if ((fd >= 0) && (buf != NULL)) {
ret = write(fd, buf, size);
}
return ret;
}
OTA_WEAK int ota_fread(int fd, void *buf, unsigned int size)
{
int ret = -1;
if ((fd >= 0) && (buf != NULL)) {
ret = read(fd, buf, size);
}
return ret;
}
OTA_WEAK int ota_fclose(int fd)
{
int ret = -1;
if (fd >= 0) {
ret = close(fd);
}
return ret;
}
| YifuLiu/AliOS-Things | components/ota/hal/ota_hal_fs_plat.c | C | apache-2.0 | 885 |
/*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#include <stdlib.h>
#include <sys/time.h>
#include <time.h>
#include <signal.h>
#include <string.h>
#include "aos/kernel.h"
#include "ota_log.h"
#include "ota_hal_os.h"
#ifdef OTA_LINUX
#include <unistd.h>
#include <pthread.h>
#include <sys/reboot.h>
#else
#include "aos/kernel.h"
#endif
/*Memory realloc*/
void *ota_realloc(void *ptr, int size)
{
#if !defined OTA_LINUX
return aos_realloc(ptr, size);
#else
return realloc(ptr, size);
#endif
}
/*Memory calloc*/
void *ota_calloc(int n, int size)
{
#if !defined OTA_LINUX
return aos_calloc(n, size);
#else
return calloc(n, size);
#endif
}
/*Reboot*/
void ota_reboot(void)
{
#if !defined OTA_LINUX
aos_reboot();
#else
reboot(0x1234567);
#endif
}
/*Memory malloc*/
void *ota_malloc(int size)
{
#if !defined OTA_LINUX
return aos_malloc(size);
#else
return malloc(size);
#endif
}
/*Memory free*/
void ota_free(void *ptr)
{
#if !defined OTA_LINUX
aos_free(ptr);
#else
free(ptr);
#endif
}
/*Sleep ms*/
void ota_msleep(int ms)
{
#if !defined OTA_LINUX
aos_msleep(ms);
#else
usleep(1000 * ms);
#endif
}
int ota_thread_create(void **thread_handle, void *(*work_routine)(void *), void *arg, void *pm, int stack_size)
{
return 0;
}
void ota_thread_destroy(void *ptread)
{
aos_task_exit(0);
}
/*Strings*/
int ota_to_capital(char *value, int len)
{
int i = 0;
int ret = -1;
if ((value != NULL) && (len > 0)) {
ret = 0;
for (; i < len; i++) {
if (*(value + i) >= 'a' && *(value + i) <= 'z') {
*(value + i) -= 'a' - 'A';
}
}
}
return ret;
}
int ota_hex2str(char *dest_buf, const unsigned char *src_buf, unsigned int dest_len, unsigned int src_len)
{
int i = 0;
int ret = -1;
if ((dest_buf != NULL) && (src_buf != NULL) && (dest_len > 2 * src_len)) {
ret = 0;
memset(dest_buf, 0x00, dest_len);
for (i = 0; i < src_len; i++) {
ota_snprintf(dest_buf + i * 2, 2 + 1, "%02X", src_buf[i]);
}
}
return ret;
}
int ota_str2hex(const char *src, char *dest, unsigned int dest_len)
{
int i, n = 0;
int ret = -1;
if ((src != NULL) && (dest != NULL) && (strlen(src) % 2 == 0) && (dest_len >= strlen(src) / 2)) {
ret = 0;
for (i = 0; src[i]; i += 2) {
if (src[i] >= 'A' && src[i] <= 'F') {
dest[n] = src[i] - 'A' + 10;
} else {
dest[n] = src[i] - '0';
}
if (src[i + 1] >= 'A' && src[i + 1] <= 'F') {
dest[n] = (dest[n] << 4) | (src[i + 1] - 'A' + 10);
} else {
dest[n] = (dest[n] << 4) | (src[i + 1] - '0');
}
++n;
}
}
return ret;
}
/*CRC16*/
static unsigned short update_crc16(unsigned short crcIn, unsigned char byte)
{
unsigned int crc = crcIn;
unsigned int in = byte | 0x100;
do {
crc <<= 1;
in <<= 1;
if (in & 0x100) {
++crc;
}
if (crc & 0x10000) {
crc ^= 0x1021;
}
} while (!(in & 0x10000));
return crc & 0xffffu;
}
void ota_crc16_init(ota_crc16_ctx *inCtx)
{
inCtx->crc = 0;
}
void ota_crc16_update(ota_crc16_ctx *inCtx, const void *inSrc, unsigned int inLen)
{
const unsigned char *src = (const unsigned char *) inSrc;
const unsigned char *srcEnd = src + inLen;
while (src < srcEnd) {
inCtx->crc = update_crc16(inCtx->crc, *src++);
}
}
void ota_crc16_final(ota_crc16_ctx *inCtx, unsigned short *outResult)
{
inCtx->crc = update_crc16(inCtx->crc, 0);
inCtx->crc = update_crc16(inCtx->crc, 0);
*outResult = inCtx->crc & 0xffffu;
}
unsigned short ota_get_data_crc16(const unsigned char *buf, unsigned int len)
{
ota_crc16_ctx ctx;
unsigned short crc16 = 0xffff;
if ((buf != NULL) && (len > 0)) {
ota_crc16_init(&ctx);
ota_crc16_update(&ctx, buf, len);
ota_crc16_final(&ctx, &crc16);
}
return crc16;
}
/*base64*/
static const unsigned char base64_dec_map[128] = {
127, 127, 127, 127, 127, 127, 127, 127, 127, 127,
127, 127, 127, 127, 127, 127, 127, 127, 127, 127,
127, 127, 127, 127, 127, 127, 127, 127, 127, 127,
127, 127, 127, 127, 127, 127, 127, 127, 127, 127,
127, 127, 127, 62, 127, 127, 127, 63, 52, 53,
54, 55, 56, 57, 58, 59, 60, 61, 127, 127,
127, 64, 127, 127, 127, 0, 1, 2, 3, 4,
5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 127, 127, 127, 127, 127, 127, 26, 27, 28,
29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
49, 50, 51, 127, 127, 127, 127, 127
};
int ota_base64_decode(const unsigned char *src, unsigned int slen, unsigned char *dst, unsigned int *dlen)
{
unsigned int i, n;
unsigned int j, x;
unsigned char *p;
for (i = n = j = 0; i < slen; i++) {
if ((slen - i) >= 2 &&
src[i] == '\r' && src[i + 1] == '\n')
continue;
if (src[i] == '\n')
continue;
if (src[i] == '=' && ++j > 2)
return -1;
if (src[i] > 127 || base64_dec_map[src[i]] == 127)
return -1;
if (base64_dec_map[src[i]] < 64 && j != 0)
return -1;
n++;
}
if (n == 0)
return 0;
n = ((n * 6) + 7) >> 3;
n -= j;
if (dst == 0 || *dlen < n) {
*dlen = n;
return -2;
}
for (j = 3, n = x = 0, p = dst; i > 0; i--, src++) {
if (*src == '\r' || *src == '\n')
continue;
j -= (base64_dec_map[*src] == 64);
x = (x << 6) | (base64_dec_map[*src] & 0x3F);
if (++n == 4) {
n = 0;
if (j > 0)
*p++ = (unsigned char)(x >> 16);
if (j > 1)
*p++ = (unsigned char)(x >> 8);
if (j > 2)
*p++ = (unsigned char)(x);
}
}
*dlen = p - dst;
return 0;
} | YifuLiu/AliOS-Things | components/ota/hal/ota_hal_os.c | C | apache-2.0 | 6,130 |
/** @defgroup ota_hal_os_api
* @{
*
* This is an include file of OTA OS adapt interface.
*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#ifndef OTA_HAL_OS_H
#define OTA_HAL_OS_H
#ifdef __cplusplus
extern "C" {
#endif
#define ota_snprintf snprintf
/*memory*/
void ota_free(void *ptr);
void *ota_malloc(int size);
void *ota_calloc(int n, int size);
void *ota_realloc(void *ptr, int size);
void ota_msleep(int ms);
/*Reboot*/
void ota_reboot(void);
/* String */
int ota_to_capital(char *value, int len);
int ota_str2hex(const char *src, char *dest, unsigned int dest_len);
int ota_hex2str(char *dest_buf, const unsigned char *src_buf, unsigned int dest_len, unsigned int src_len);
/*Base64*/
int ota_base64_decode(const unsigned char *input, unsigned int input_len, unsigned char *output, unsigned int *output_len);
/*CRC16*/
typedef struct {
unsigned short crc;
} ota_crc16_ctx;
void ota_crc16_init(ota_crc16_ctx *ctx);
void ota_crc16_update(ota_crc16_ctx *ctx, const void *inSrc, unsigned int inLen);
void ota_crc16_final(ota_crc16_ctx *ctx, unsigned short *outResult);
unsigned short ota_get_data_crc16(const unsigned char *buf, unsigned int len);
void ota_thread_destroy(void *ptread);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /*OTA_HAL_OS_H*/
| YifuLiu/AliOS-Things | components/ota/hal/ota_hal_os.h | C | apache-2.0 | 1,287 |
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include "ota_log.h"
#include "ota_import.h"
#include "ota_hal_os.h"
#include "aos_hal_flash.h"
static int boot_part = HAL_PARTITION_OTA_TEMP;
int ota_is_download_mode(void)
{
int ret = 0;
ota_boot_param_t param = {0};
memset(¶m, 0, sizeof(ota_boot_param_t));
ret = ota_read_parameter(¶m);
if(ret < 0) {
return 0;
}
if((param.upg_status == OTA_TRANSPORT) && (param.upg_flag != 0xffff)){
OTA_LOG_I("OTA running status :0x%04x \n",param.upg_status);
return 1;
}
OTA_LOG_I("ota is status:%d param crc:0x%04x \n",param.upg_status, param.param_crc);
return ret;
}
int ota_read_parameter(ota_boot_param_t *ota_param)
{
int ret = OTA_UPGRADE_PARAM_FAIL;
int param_part = HAL_PARTITION_PARAMETER_1;
unsigned int offset = 0;
unsigned short patch_crc = 0;
if(ota_param == NULL) {
return ret;
}
memset(ota_param, 0, sizeof(ota_boot_param_t));
ret = aos_hal_flash_read(param_part, &offset, ota_param, sizeof(ota_boot_param_t));
if(ret < 0) {
return ret;
}
patch_crc = ota_get_data_crc16((const unsigned char *)ota_param, sizeof(ota_boot_param_t) - sizeof(unsigned short));
OTA_LOG_I("ota param crc:0x%04x cal:0x%04x \n", ota_param->param_crc, patch_crc);
if(patch_crc == ota_param->param_crc) {
return 0;
}
return ret;
}
int ota_update_parameter(ota_boot_param_t *ota_param)
{
int ret = OTA_UPGRADE_PARAM_FAIL;
unsigned int offset = 0x00;
unsigned int len = sizeof(ota_boot_param_t);
ota_boot_param_t comp_buf;
if(ota_param == NULL) {
return ret;
}
ota_param->param_crc = ota_get_data_crc16((const unsigned char *)ota_param, sizeof(ota_boot_param_t) - sizeof(unsigned short));
OTA_LOG_I("ota update param crc:0x%04x flag:0x%04x\n", ota_param->param_crc, ota_param->upg_flag);
memset(&comp_buf, 0, len);
ret = aos_hal_flash_erase(HAL_PARTITION_PARAMETER_1, offset, len);
if(ret >= 0) {
ret = aos_hal_flash_write(HAL_PARTITION_PARAMETER_1, &offset, ota_param, len);
offset = 0x00;
if(ret >= 0) {
ret = aos_hal_flash_read(HAL_PARTITION_PARAMETER_1, &offset, (unsigned char *)&comp_buf, len);
if(ret >= 0) {
if(memcmp(ota_param, (unsigned char*)&comp_buf, len) != 0) {
ret = OTA_UPGRADE_PARAM_FAIL;
OTA_LOG_E("save param failed\r\n");
}
}
}
}
return 0;
}
unsigned short ota_get_upgrade_flag(void)
{
int ret = 0;
unsigned short flag = 0;
ota_boot_param_t ota_param = {0};
ret = ota_read_parameter(&ota_param);
if(ret < 0) {
return 0xffff;
}
flag = ota_param.upg_flag;
return flag;
}
int ota_update_upg_flag(unsigned short flag)
{
int ret = 0;
ota_boot_param_t ota_param = {0};
OTA_LOG_I("upg_flag:0x%x \n", flag);
ret = ota_read_parameter(&ota_param);
if(ret < 0) {
return ret;
}
ota_param.upg_flag = flag;
ret = ota_update_parameter(&ota_param);
return 0;
}
int ota_clear_paramters()
{
int ret = 0;
unsigned int offset = 0x00;
unsigned int len = sizeof(ota_boot_param_t);
ret = aos_hal_flash_erase(HAL_PARTITION_PARAMETER_1, offset, len);
OTA_LOG_I("ota clear ret = %d\r\n", ret);
return ret;
}
unsigned int ota_parse_ota_type(unsigned char *buf, unsigned int len)
{
int upg_flag = 0;
unsigned char xz_header[6] = { 0xFD, '7', 'z', 'X', 'Z', 0x00 };
if((buf != NULL) && (len >= 8)) {
if (memcmp(buf, "BSDIFF40", 8) == 0) {
upg_flag = OTA_UPGRADE_DIFF;
}
else if (memcmp(buf, xz_header, 6) == 0) {
upg_flag = OTA_UPGRADE_XZ;
}
else {
upg_flag = OTA_UPGRADE_ALL;
}
}
OTA_LOG_I("ota header:0x%x", upg_flag);
return upg_flag;
}
int ota_hal_rollback(void)
{
int ret = 0;
unsigned int offset = 0;
ota_boot_param_t param;
memset(¶m, 0, sizeof(ota_boot_param_t));
ret = aos_hal_flash_read(HAL_PARTITION_PARAMETER_1, &offset, ¶m, sizeof(ota_boot_param_t));
if (ret < 0) {
OTA_LOG_E("rollback err:%d", ret);
return ret;
}
if ((param.boot_count != 0) && (param.boot_count != 0xff)) {
param.upg_flag = 0;
param.boot_count = 0; /*Clear bootcount to avoid rollback*/
ret = ota_update_parameter(¶m);
}
if (ret != 0) {
OTA_LOG_E("rollback err:%d", ret);
}
return ret;
}
int ota_hal_boot(ota_boot_param_t *param)
{
int ret = OTA_UPGRADE_WRITE_FAIL;
hal_logic_partition_t ota_info;
hal_logic_partition_t app_info;
hal_logic_partition_t *p_ota_info = &ota_info;
hal_logic_partition_t *p_app_info = &app_info;
memset(p_ota_info, 0, sizeof(hal_logic_partition_t));
memset(p_app_info, 0, sizeof(hal_logic_partition_t));
aos_hal_flash_info_get(boot_part, &p_ota_info);
aos_hal_flash_info_get(HAL_PARTITION_APPLICATION, &p_app_info);
if (param != NULL) {
if (param->crc == 0 || param->crc == 0xffff) {
OTA_LOG_I("calculate image crc");
ota_hal_image_crc16(¶m->crc);
}
param->src_adr = p_ota_info->partition_start_addr;
param->dst_adr = p_app_info->partition_start_addr;
param->old_size = p_app_info->partition_length;
param->boot_type = ota_hal_boot_type();
ret = ota_update_parameter(param);
if (ret < 0) {
return OTA_UPGRADE_WRITE_FAIL;
}
OTA_LOG_I("OTA after finish dst:0x%08x src:0x%08x len:0x%08x, crc:0x%04x param crc:0x%04x upg_flag:0x%04x \r\n", param->dst_adr, param->src_adr, param->len, param->crc, param->param_crc, param->upg_flag);
}
return ret;
}
| YifuLiu/AliOS-Things | components/ota/hal/ota_hal_param.c | C | apache-2.0 | 5,864 |
#include <string.h>
#include <stdlib.h>
#include <stdint.h>
#include "ota_log.h"
#include "ota_import.h"
#include "ota_hal_os.h"
#include "ota_hal.h"
#include "aos_hal_flash.h"
unsigned char *ota_cache = NULL;
unsigned int ota_cache_len = 0;
unsigned int ota_fw_size = 0;
unsigned int ota_receive_total_len = 0;
static int boot_part = HAL_PARTITION_OTA_TEMP;
static ota_crc16_ctx ctx = {0};
OTA_WEAK int ota_hal_init(ota_boot_param_t *param)
{
int ret = OTA_INIT_FAIL;
if(param != NULL) {
ret = 0;
hal_logic_partition_t part_info;
hal_logic_partition_t *p_part_info;
p_part_info = &part_info;
memset(p_part_info, 0, sizeof(hal_logic_partition_t));
ret = aos_hal_flash_info_get(boot_part, &p_part_info);
if(ret != 0 || param->len == 0) {
ret = OTA_INIT_FAIL;
}
else {
ota_receive_total_len = 0;
ota_fw_size = param->len;
ota_cache = ota_malloc(OTA_FLASH_WRITE_CACHE_SIZE);
if (NULL == ota_cache) {
ret = OTA_INIT_FAIL;
}
else {
unsigned int len = p_part_info->partition_length;
unsigned int off = 0;
unsigned int block_size = 0;
while(len > 0) {
block_size = (len > OTA_FLASH_BLOCK_SIZE) ? OTA_FLASH_BLOCK_SIZE : len;
ret = aos_hal_flash_erase(boot_part, ota_receive_total_len + off, block_size);
if(ret < 0) {
ret = OTA_INIT_FAIL;
if(NULL != ota_cache) {
ota_free(ota_cache);
ota_cache = NULL;
}
OTA_LOG_E("erase fail! ");
return ret;
}
off += block_size;
len -= block_size;
ota_msleep(10);
}
}
ota_crc16_init(&ctx);
}
OTA_LOG_I("ota init part:%d len:%d \n", boot_part, param->len);
}
if(ret != 0) {
if(NULL != ota_cache) {
ota_free(ota_cache);
ota_cache = NULL;
}
OTA_LOG_E("ota init fail!");
}
return ret;
}
OTA_WEAK int ota_hal_write(unsigned int *off, char *in_buf, unsigned int in_buf_len)
{
int ret = 0;
int tocopy = 0;
static char buf[2048];
if(off == NULL || in_buf_len > OTA_FLASH_WRITE_CACHE_SIZE) {
return OTA_UPGRADE_WRITE_FAIL;
}
if (in_buf_len <= OTA_FLASH_WRITE_CACHE_SIZE - ota_cache_len) {
tocopy = in_buf_len;
} else {
tocopy = OTA_FLASH_WRITE_CACHE_SIZE - ota_cache_len;
}
/*Start from last byte of remaing data*/
memcpy(ota_cache + ota_cache_len, in_buf, tocopy);
ota_cache_len += tocopy;
if (ota_cache_len == OTA_FLASH_WRITE_CACHE_SIZE) {
ret = aos_hal_flash_write(boot_part, off, ota_cache, OTA_FLASH_WRITE_CACHE_SIZE);
if(ret < 0) {
goto EXIT;
}
*off += OTA_FLASH_WRITE_CACHE_SIZE;
ota_crc16_update(&ctx, ota_cache, OTA_FLASH_WRITE_CACHE_SIZE);
ota_cache_len = 0;
}
/*keep remaining data*/
if (in_buf_len - tocopy > 0) {
/*Now ota_cache only contains remaing data*/
memcpy(ota_cache, in_buf + tocopy, in_buf_len - tocopy);
ota_cache_len = in_buf_len - tocopy;
}
ota_receive_total_len += in_buf_len;
if(ota_receive_total_len == ota_fw_size) {
if (ota_cache_len != 0) {
ret = aos_hal_flash_write(boot_part, off, ota_cache, ota_cache_len);
if (ret < 0) {
goto EXIT;
}
*off += ota_cache_len;
ota_crc16_update(&ctx, ota_cache, ota_cache_len);
}
if(ota_cache != NULL) {
ota_free(ota_cache);
ota_cache = NULL;
}
}
EXIT:
if(ret < 0) {
if(ota_cache != NULL) {
ota_free(ota_cache);
ota_cache = NULL;
}
OTA_LOG_E("ota_write err:%d", ret);
}
return ret;
}
OTA_WEAK int ota_hal_rollback(void)
{
int ret = 0;
unsigned int offset = 0;
ota_boot_param_t param;
memset(¶m, 0, sizeof(ota_boot_param_t));
ret = aos_hal_flash_read(HAL_PARTITION_PARAMETER_1, &offset, ¶m, sizeof(ota_boot_param_t));
if(ret < 0) {
OTA_LOG_E("rollback err:%d", ret);
return ret;
}
if((param.boot_count != 0) && (param.boot_count != 0xff)) {
param.upg_flag = 0;
param.boot_count = 0; /*Clear bootcount to avoid rollback*/
ret = ota_update_parameter(¶m);
}
if(ret != 0) {
OTA_LOG_E("rollback err:%d", ret);
}
return ret;
}
OTA_WEAK unsigned char ota_hal_boot_type()
{
return 0;
}
OTA_WEAK void ota_hal_image_crc16(unsigned short *outResult)
{
ota_crc16_final(&ctx, outResult);
}
OTA_WEAK int ota_hal_boot(ota_boot_param_t *param)
{
int ret = OTA_UPGRADE_WRITE_FAIL;
hal_logic_partition_t ota_info;
hal_logic_partition_t app_info;
hal_logic_partition_t *p_ota_info = &ota_info;
hal_logic_partition_t *p_app_info = &app_info;
memset(p_ota_info, 0, sizeof(hal_logic_partition_t));
memset(p_app_info, 0, sizeof(hal_logic_partition_t));
aos_hal_flash_info_get(boot_part, &p_ota_info);
aos_hal_flash_info_get(HAL_PARTITION_APPLICATION, &p_app_info);
if(param != NULL) {
if(param->crc == 0 || param->crc == 0xffff) {
OTA_LOG_I("calculate image crc");
ota_hal_image_crc16(¶m->crc);
}
param->src_adr = p_ota_info->partition_start_addr;
param->dst_adr = p_app_info->partition_start_addr;
param->old_size = p_app_info->partition_length;
param->boot_type = ota_hal_boot_type();
ret = ota_update_parameter(param);
if(ret < 0) {
return OTA_UPGRADE_WRITE_FAIL;
}
OTA_LOG_I("OTA after finish dst:0x%08x src:0x%08x len:0x%08x, crc:0x%04x param crc:0x%04x upg_flag:0x%04x \r\n", param->dst_adr, param->src_adr, param->len, param->crc, param->param_crc, param->upg_flag);
}
return ret;
}
int ota_hal_read(unsigned int *off, char *out_buf, unsigned int out_buf_len)
{
int ret = 0;
ret = aos_hal_flash_read(boot_part, off, out_buf, out_buf_len);
return ret;
}
int ota_hal_reboot_bank(void)
{
return 0;
}
| YifuLiu/AliOS-Things | components/ota/hal/ota_hal_plat.c | C | apache-2.0 | 6,485 |
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#include <stdlib.h>
#include "ota_hal_trans.h"
#include "aiot_mqtt_api.h"
/*MQTT API*/
int ota_hal_mqtt_publish(void *mqtt_client, char *topic, int qos, void *data, int len)
{
return aiot_mqtt_pub(mqtt_client, topic, data, len, qos);
}
int ota_hal_mqtt_subscribe(void *mqtt_client, char *topic, void* cb, void *ctx)
{
return aiot_mqtt_sub(mqtt_client, topic, cb, 0, ctx);
}
int ota_hal_mqtt_type_is_pub(void *msg)
{
aiot_mqtt_recv_t *mqtt_msg = (aiot_mqtt_recv_t *)msg;
if (mqtt_msg == NULL) {
return 0;
}
if (mqtt_msg->type == AIOT_MQTTRECV_PUB) {
return 1;
}
return 0;
}
void *ota_hal_mqtt_get_payload(void *msg)
{
void *payload = NULL;
aiot_mqtt_recv_t *mqtt_msg = (aiot_mqtt_recv_t *)msg;
payload = (char *)mqtt_msg->data.pub.payload;
return payload;
}
| YifuLiu/AliOS-Things | components/ota/hal/ota_hal_trans.c | C | apache-2.0 | 890 |
/** @defgroup ota_hal_transport_api
* @{
*
* This is an include file of OTA transport interface.
*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#ifndef OTA_HAL_TRANSPORT_H
#define OTA_HAL_TRANSPORT_H
#ifdef __cplusplus
extern "C" {
#endif
/*MQTT*/
typedef struct {
unsigned short packet_id;
unsigned char qos;
unsigned char dup;
unsigned char retain;
unsigned short topic_len;
unsigned int payload_len;
const char *ptopic;
const char *payload;
} ota_mqtt_topic_t;
typedef enum {
OTA_MQTT_EVENT_SUB_SUCCESS = 3,
OTA_MQTT_EVENT_PUB_RECEIVED = 12,
OTA_MQTT_EVENT_BUF_OVERFLOW = 13,
} ota_mqtt_event_t;
typedef struct {
ota_mqtt_event_t event;
ota_mqtt_topic_t *topic;
} ota_mqtt_msg_t;
int ota_hal_mqtt_subscribe(void *mqtt_client, char *topic, void* cb, void *ctx);
int ota_hal_mqtt_publish(void *mqtt_client, char *topic, int qos, void *data, int len);
int ota_hal_mqtt_type_is_pub(void *msg);
void *ota_hal_mqtt_get_payload(void *msg);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /*OTA_HAL_TRANSPORT_H*/
| YifuLiu/AliOS-Things | components/ota/hal/ota_hal_trans.h | C | apache-2.0 | 1,108 |
/** @defgroup ota_agent_api
* @{
*
* This is an include file of OTA agent transporting with clould.
*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#ifndef OTA_AGENT_H
#define OTA_AGENT_H
/*******************************************************************
*********** OTA Agent **************
*********** | **************
*********** V **************
*********** Service manager **************
*********** device ----- inform version -----> cloud **************
*********** device ---- subcribe upgrade ----> cloud **************
*********** | **************
*********** V **************
*********** Transport module **************
*********** device <---- transport message --- cloud **************
*********** device <-- new version:url,sign -- cloud **************
*********** | **************
*********** V **************
*********** Download module **************
*********** device <---- download firmware --- cloud **************
*********** | **************
*********** V **************
*********** Common hal module **************
*********** device ---- update image ----> ota part **************
*********** | **************
*********** V **************
*********** Verify module **************
*********** device ---- verfiy firmware ----- verify **************
*********** device ----- report status ----- reboot **************
*********** | **************
*********** V **************
*********** MCU module **************
*********** device ----- send FW ------> MCU **************
********************************************************************/
#define OTA_VERSION "3.3.0"
#define OTA_TRANSTYPE "1"
#define OTA_OS_TYPE "0"
#define OTA_BOARD_TYPE "0"
#ifdef __cplusplus
extern "C" {
#endif
/** @addtogroup aos_ota OTA
* OTA upgrade service.
*
* @{
*/
/* OTA upgrade flag */
#define OTA_UPGRADE_CUST 0x8778 /* upgrade user customize image */
#define OTA_UPGRADE_ALL 0x9669 /* upgrade all image: kernel+framework+app */
#define OTA_UPGRADE_XZ 0xA55A /* upgrade xz compressed image */
#define OTA_UPGRADE_DIFF 0xB44B /* upgrade diff compressed image */
#define OTA_UPGRADE_KERNEL 0xC33C /* upgrade kernel image only */
#define OTA_UPGRADE_APP 0xD22D /* upgrade app image only */
#define OTA_UPGRADE_FS 0x7083 /* upgrade fs image only */
#define OTA_BIN_MAGIC_APP 0xabababab
#define OTA_BIN_MAGIC_KERNEL 0xcdcdcdcd
#define OTA_BIN_MAGIC_ALL 0xefefefef
#define OTA_BIN_MAGIC_MCU 0xefcdefcd
#define OTA_BIN_MAGIC_FS 0xabcdabcd
/**
* ENUM: OTA Agent ERRNO.
*/
typedef enum {
OTA_FINISH = 4, /*OTA finish status*/
OTA_DOWNLOAD = 3, /*OTA download status*/
OTA_TRANSPORT = 2, /*OTA transport status*/
OTA_INIT = 1, /*OTA init status*/
OTA_SUCCESS = 0,
OTA_INIT_FAIL = -1, /*OTA init failed.*/
OTA_TRANSPORT_INT_FAIL = -2, /*OTA transport init failed.*/
OTA_TRANSPORT_PAR_FAIL = -3, /*OTA transport parse failed.*/
OTA_TRANSPORT_VER_FAIL = -4, /*OTA transport verion is too old.*/
OTA_DOWNLOAD_INIT_FAIL = -5, /*OTA download init failed.*/
OTA_DOWNLOAD_HEAD_FAIL = -6, /*OTA download header failed.*/
OTA_DOWNLOAD_CON_FAIL = -7, /*OTA download connect failed.*/
OTA_DOWNLOAD_REQ_FAIL = -8, /*OTA download request failed.*/
OTA_DOWNLOAD_RECV_FAIL = -9, /*OTA download receive failed.*/
OTA_VERIFY_MD5_FAIL = -10, /*OTA verfiy MD5 failed.*/
OTA_VERIFY_SHA2_FAIL = -11, /*OTA verfiy SH256 failed.*/
OTA_VERIFY_RSA_FAIL = -12, /*OTA verfiy RSA failed.*/
OTA_VERIFY_IMAGE_FAIL = -13, /*OTA verfiy image failed.*/
OTA_UPGRADE_WRITE_FAIL = -14, /*OTA upgrade write failed.*/
OTA_UPGRADE_PARAM_FAIL = -15, /*OTA upgrade parameter failed.*/
OTA_UPGRADE_FW_SIZE_FAIL = -16, /*OTA upgrade FW too big.*/
OTA_UPGRADE_SET_BOOT_FAIL = -17, /*OTA upgrade set boot failed.*/
OTA_CUSTOM_CALLBAK_FAIL = -18, /*OTA custom callback failed.*/
OTA_MCU_INIT_FAIL = -19, /*OTA MCU init failed.*/
OTA_MCU_VERSION_FAIL = -20, /*OTA MCU version failed.*/
OTA_MCU_NOT_READY = -21, /*OTA MCU not ready.*/
OTA_MCU_REBOOT_FAIL = -22, /*OTA MCU fail to reboot.*/
OTA_MCU_HEADER_FAIL = -23, /*OTA MCU header error.*/
OTA_MCU_UPGRADE_FAIL = -24, /*OTA MCU upgrade fail.*/
OTA_INVALID_PARAMETER = -25, /*OTA INVALID PARAMETER.*/
} OTA_ERRNO_E;
typedef enum {
OTA_REPORT_UPGRADE_ERR = -1, /* ota report upgrading failed to cloud*/
OTA_REPORT_DOWNLOAD_ERR = -2, /* ota report downloading failed to cloud*/
OTA_REPORT_VERIFY_ERR = -3, /* ota report image verified err to cloud*/
OTA_REPORT_BURN_ERR = -4, /* ota report image burning failed to cloud*/
} OTA_REPORT_CLOUD_ERRNO_E;
#define OTA_URL_LEN 256 /*OTA download url max len*/
#define OTA_HASH_LEN 66 /*OTA download file hash len*/
#define OTA_SIGN_LEN 256 /*OTA download file sign len*/
#define OTA_VER_LEN 64 /*OTA version string max len*/
typedef enum {
OTA_EVENT_UPGRADE_TRIGGER,
OTA_EVENT_DOWNLOAD,
OTA_EVENT_INSTALL,
OTA_EVENT_LOAD,
OTA_EVENT_REPORT_VER,
} OTA_EVENT_ID;
/**
* Struct: OTA boot parameter.
*/
typedef struct {
unsigned int dst_adr; /*Single Bank: Destination Address: APP partition.*/
unsigned int src_adr; /*Single Bank: Copy from Source Address: OTA partition.*/
unsigned int len; /*Single Bank: Download file len */
unsigned short crc; /*Single Bank: Download file CRC */
unsigned short upg_flag; /*Upgrade flag: OTA_UPGRADE_ALL OTA_UPGRADE_XZ OTA_UPGRADE_DIFF*/
unsigned char boot_count; /*Boot count: When >=3 Rollback to old version in BL for dual-banker boot*/
int upg_status; /*OTA upgrade status*/
unsigned char hash_type; /*OTA download hash type*/
char url[OTA_URL_LEN]; /*OTA download url*/
char sign[OTA_SIGN_LEN]; /*OTA download file sign*/
char hash[OTA_HASH_LEN]; /*OTA download file hash*/
char ver[OTA_VER_LEN]; /*OTA get version*/
unsigned int old_size; /*Diff upgrade: patch old data size*/
unsigned short patch_num; /*Diff upgrade: patch num*/
unsigned short patch_status; /*Diff upgrade: patch status*/
unsigned int patch_off; /*Diff upgrade: patch offset*/
unsigned int new_off; /*Diff upgrade: patch new data offset*/
unsigned int new_size; /*Diff upgrade: patch new data size*/
unsigned int upg_magic; /*OTA upgrade image magic*/
unsigned char boot_type; /*OS boot type:Single boot(0x00), dual boot(0x01)*/
unsigned char reserved[13]; /*OTA Reserved*/
unsigned short param_crc; /*OTA Parameter crc*/
} ota_boot_param_t;
/**
* Struct: OTA sign info.
*/
typedef struct {
unsigned int encrypto_magic; /*encrypto type: RSA:0xAABBCCDD or ECC:0xDDCCBBAA*/
char padding_mode; /*sign padding mode:PKCS1 or OAEP*/
char sign_hash_type; /*sign hash type*/
char abstract_hash_type; /*calculate image hash type*/
char reserved[97]; /*reserved buf*/
char hash[32]; /*image hash value(sha256)*/
char signature[256]; /*image digest signature*/
} ota_sign_info_t;
/**
* Struct: OTA image info.
*/
typedef struct {
unsigned int image_magic; /* image magic */
unsigned int image_size; /* image size */
unsigned char image_md5[16]; /* image md5 info */
unsigned char image_num; /* image number */
unsigned char image_res; /* image resouce */
unsigned short image_crc16; /* image crc16 */
} ota_image_info_t;
typedef struct {
ota_sign_info_t *sign_info; /* Image sign info */
ota_image_info_t *image_info; /* Package Image info */
} ota_image_header_t;
typedef struct {
void (*on_user_event_cb)(int event, int errnumb, void *param);
void *param; /* users paramter */
} ota_feedback_msg_func_t;
typedef int (*report_func)(void *, uint32_t);
typedef int (*triggered_func)(void *, char *, char *, void *);
typedef struct {
report_func report_status_cb;
void *param; /* users paramter */
} ota_report_status_func_t;
typedef struct {
triggered_func triggered_ota_cb;
void *param; /* users paramter */
} ota_triggered_func_t;
typedef struct {
char module_name[33];
char store_path[77];
int module_type;
} ota_store_module_info_t;
/* OTA service manager */
typedef struct ota_service_s {
char pk[20+1]; /* Product Key */
char ps[64+1]; /* Product secret */
char dn[32+1]; /* Device name */
char ds[64+1]; /* Device secret */
unsigned char dev_type; /* device type: 0-->main dev 1-->sub dev*/
char module_name[33]; /* module name*/
unsigned char ota_process;
int module_numb;
ota_store_module_info_t *module_queue_ptr;
ota_feedback_msg_func_t feedback_func;
ota_report_status_func_t report_func; /* report percentage to clould */
ota_triggered_func_t ota_triggered_func; /* new version ready, if OTA upgrade or not by User */
int (*on_boot)(ota_boot_param_t *ota_param); /* Upgrade complete to reboot to the new version */
ota_image_header_t header; /* OTA Image header */
void *mqtt_client; /* mqtt client */ /* OTA Upgrade parameters */
} ota_service_t;
/* OTA service APIs */
/**
* ota_service_init ota service init .
*
* @param[in] ota_service_t *ctx ota service context
*
* @return OTA_SUCCESS OTA success.
* @return OTA_TRANSPORT_INT_FAIL OTA transport init fail.
* @return OTA_TRANSPORT_PAR_FAIL OTA transport parse fail.
* @return OTA_TRANSPORT_VER_FAIL OTA transport verion is too old.
*/
int ota_service_init(ota_service_t *ctx);
/**
* ota_service_start ota service start and file store in flash
*
* @param[in] ota_service_t *ctx ota service context
*
* @return OTA_SUCCESS OTA success.
* @return OTA_TRANSPORT_INT_FAIL OTA transport init fail.
* @return OTA_TRANSPORT_PAR_FAIL OTA transport parse fail.
* @return OTA_TRANSPORT_VER_FAIL OTA transport verion is too old.
*/
int ota_service_start(ota_service_t *ctx);
/**
* ota_download_to_fs_service ota service submodule start.
*
* @param[in] void *ctx ota service context
*
* @return OTA_SUCCESS OTA success.
* @return OTA_TRANSPORT_INT_FAIL OTA transport init fail.
* @return OTA_TRANSPORT_PAR_FAIL OTA transport parse fail.
* @return OTA_TRANSPORT_VER_FAIL OTA transport verion is too old.
*/
int ota_download_to_fs_service(void *ota_ctx , char *file_path);
/**
* ota_install_jsapp ota service submodule start.
*
* @param[in] void *ota_ctx ota service context
*
* @return OTA_SUCCESS OTA success.
* @return OTA_TRANSPORT_INT_FAIL OTA transport init fail.
* @return OTA_TRANSPORT_PAR_FAIL OTA transport parse fail.
* @return OTA_TRANSPORT_VER_FAIL OTA transport verion is too old.
*/
int ota_install_jsapp(void *ota_ctx, char *store_file, int store_file_len, char *install_path);
/**
* ota_report_module_version ota report module version.
*
* @param[in] void *ctx ota service context
* @param[in] char *module_name want tp report module name
* @param[in] char *version module file version
*
* @return OTA_SUCCESS OTA success.
* @return -1 OTA transport init fail.
*/
int ota_report_module_version(void *ota_ctx, char *module_name, char *version);
/**
* ota_service_param_reset;
*
* @param[in] ota_service_t *ctx ota service context
*
* @return NULL
*/
void ota_service_param_reset(ota_service_t *ctx);
/**
* ota_sevice_parse_msg ota service parse message.
*
* @param[in] ota_service_t *ctx ota service context
*
* @return OTA_SUCCESS OTA success.
* @return OTA_TRANSPORT_INT_FAIL OTA transport init fail.
* @return OTA_TRANSPORT_PAR_FAIL OTA transport parse fail.
* @return OTA_TRANSPORT_VER_FAIL OTA transport verion is too old.
*/
int ota_sevice_parse_msg(ota_service_t *ctx, const char *json);
/**
* ota_register_module_store ota register store moudle information buf to ctx;
*
*
* @param[in] ota_service_t *ctx ota service context
* @param[in] ota_store_module_info_t *queue store moudle information buf ptr
* @param[in] int queue_len module buf size
*
* @return OTA_SUCCESS OTA success.
* @return OTA_TRANSPORT_INT_FAIL Get information failed.
*/
int ota_register_module_store(ota_service_t *ctx, ota_store_module_info_t *queue, int queue_len);
/**
* ota_set_module_information ota set module information to DB, include:
* module name, store path, module type.
*
* @param[in] ota_service_t *ctx ota service context
* @param[in] char *module_name ota module name
* @param[in] char *store_path want to store module file path
* @param[in] int module_type upgrade type: OTA_UPGRADE_ALL.etc.
*
* @return OTA_SUCCESS OTA success.
* @return OTA_TRANSPORT_INT_FAIL Get information failed.
*/
int ota_set_module_information(ota_service_t *ctx, char *module_name,
char *store_path, int module_type);
/**
* ota_get_module_information ota get module information,include:
* module name, store path, module type.
*
* @param[in] ota_service_t *ctx ota service context
* @param[in] char *module_name ota module name
* @param[in] ota_store_module_info_t *module_info want to store module information var
*
* @return OTA_SUCCESS OTA success.
* @return OTA_TRANSPORT_INT_FAIL Get information failed.
*/
int ota_get_module_information(ota_service_t *ctx, char *module_name, ota_store_module_info_t *module_info);
/**
* ota_register_boot_cb ota register boot callback.
*
* @param[in] ota_service_t *ctx ota service context
*
* @return OTA_SUCCESS OTA success.
* @return OTA_TRANSPORT_INT_FAIL OTA transport init fail.
* @return OTA_TRANSPORT_PAR_FAIL OTA transport parse fail.
* @return OTA_TRANSPORT_VER_FAIL OTA transport verion is too old.
*/
int ota_register_boot_cb(ota_service_t *ctx, void *cb, void *param);
/**
* ota_register_trigger_msg_cb ota register trigger ota callback.
*
* @param[in] ota_service_t *ctx ota service context
*
* @return OTA_SUCCESS OTA success.
* @return OTA_TRANSPORT_INT_FAIL OTA transport init fail.
* @return OTA_TRANSPORT_PAR_FAIL OTA transport parse fail.
* @return OTA_TRANSPORT_VER_FAIL OTA transport verion is too old.
*/
int ota_register_trigger_msg_cb(ota_service_t *ctx, void *cb, void *param);
/**
* ota_register_report_percent_cb ota register file download process callback.
*
* @param[in] ota_service_t *ctx ota service context
*
* @return OTA_SUCCESS OTA success.
* @return OTA_TRANSPORT_INT_FAIL OTA transport init fail.
* @return OTA_TRANSPORT_PAR_FAIL OTA transport parse fail.
* @return OTA_TRANSPORT_VER_FAIL OTA transport verion is too old.
*/
int ota_register_report_percent_cb(ota_service_t *ctx, void *cb, void *param);
/**
* ota_register_feedback_msg_cb ota service register callback.
*
* @param[in] ota_service_t *ctx ota service context
*
* @return OTA_SUCCESS OTA success.
* @return OTA_TRANSPORT_INT_FAIL OTA transport init fail.
* @return OTA_TRANSPORT_PAR_FAIL OTA transport parse fail.
* @return OTA_TRANSPORT_VER_FAIL OTA transport verion is too old.
*/
int ota_register_feedback_msg_cb(ota_service_t *ctx, void *cb, void *param);
/***************************************************************
*** OTA transport module:transport message with MQTT or CoAP ***
****************************************************************/
/**
* ota_transport_inform OTA inform version to cloud.
*
* @param[in] void *mqttclient mqtt client ptr
* @param[in] char *pk product key value
* @param[in] char *dn device name
* @param[in] char *module_name want to report module name, when module_name == NULL, report default module ver
* @param[in] char *ver version string
*
* @return OTA_SUCCESS OTA success.
* @return OTA_TRANSPORT_INT_FAIL OTA transport init fail.
* @return OTA_TRANSPORT_PAR_FAIL OTA transport parse fail.
* @return OTA_TRANSPORT_VER_FAIL OTA transport verion is too old.
*/
int ota_transport_inform(void *mqttclient, char *pk, char *dn, char *module_name, char *ver);
/**
* ota_transport_upgrade subscribe OTA upgrade to clould.
*
* @param[in] ota_service_t *ctx ota service context
*
* @return OTA_SUCCESS OTA success.
* @return OTA_TRANSPORT_INT_FAIL OTA transport init fail.
* @return OTA_TRANSPORT_PAR_FAIL OTA transport parse fail.
* @return OTA_TRANSPORT_VER_FAIL OTA transport verion is too old.
*/
int ota_transport_upgrade(ota_service_t *ctx);
/**
* ota_transport_upgrade report status to cloud.
*
* @param[in] void *param ota service context
* @param[in] int status ota upgrade status
*
* @return OTA_SUCCESS OTA success.
* @return OTA_TRANSPORT_INT_FAIL OTA transport init fail.
* @return OTA_TRANSPORT_PAR_FAIL OTA transport parse fail.
* @return OTA_TRANSPORT_VER_FAIL OTA transport verion is too old.
*/
int ota_transport_status(void *param, int status);
/***************************************************************
*** OTA download module: download image with HTTP or CoaP ***
****************************************************************/
/**
* ota_download_start OTA download start
*
* @param[in] char *url download url
* @param[in] unsigned int url_len download url length
* @param[in] report_func repot_func report http downloading status function
* @param[in] void *user_param user's param for repot_func
*
* @return OTA_SUCCESS OTA success.
* @return OTA_DOWNLOAD_INIT_FAIL OTA download init failed.
* @return OTA_DOWNLOAD_CON_FAIL OTA download connect failed.
* @return OTA_DOWNLOAD_REQ_FAIL OTA download request failed.
* @return OTA_DOWNLOAD_RECV_FAIL OTA download receive failed.
*/
int ota_download_start(char *url, unsigned int url_len, report_func repot_func, void *user_param);
/**
* ota_download_store_fs_start OTA download file start and store in fs
*
* @param[in] char *url download url
* @param[in] unsigned int url_len download url length
* @param[in] char *store_path store file path and name eg:/root/test.bin
* @param[in] report_func report_func report http downloading status function
* @param[in] void *user_param user's param for repot_func
*
* @return OTA_SUCCESS OTA success.
* @return OTA_DOWNLOAD_INIT_FAIL OTA download init failed.
* @return OTA_DOWNLOAD_CON_FAIL OTA download connect failed.
* @return OTA_DOWNLOAD_REQ_FAIL OTA download request failed.
* @return OTA_DOWNLOAD_RECV_FAIL OTA download receive failed.
*/
int ota_download_store_fs_start(char *url, unsigned int url_len, char *store_path,
report_func report_func, void *user_param);
/**
* ota_download_image_header ota download image header.
*
* @param[in] ota_service_t *ctx ota service context
* @param[in] char *url download url
* @param[in] unsigned int url_len download url length
* @param[in] unsigned int size ota image size
*
* @return OTA_SUCCESS OTA success.
* @return OTA_DOWNLOAD_INIT_FAIL OTA download init fail.
* @return OTA_DOWNLOAD_HEAD_FAIL OTA download header fail.
* @return OTA_DOWNLOAD_CON_FAIL OTA download connect fail.
* @return OTA_DOWNLOAD_REQ_FAIL OTA download request fail.
* @return OTA_DOWNLOAD_RECV_FAIL OTA download receive fail.
*/
int ota_download_image_header(ota_service_t *ctx, char *url, unsigned int url_len, unsigned int size);
/***************************************************************
*** OTA hal module: update image to OTA partition:ota_hal.h ***
****************************************************************/
/**
* ota_read_parameter ota read parameter from flash.
*
* @param[in] ota_boot_param_t *param ota parameter
*
* @return OTA_SUCCESS OTA success.
* @return OTA_UPGRADE_WRITE_FAIL OTA upgrade write fail.
* @return OTA_UPGRADE_PARAM_FAIL OTA upgrade parameter fail.
* @return OTA_UPGRADE_FW_SIZE_FAIL OTA upgrade FW too big.
* @return OTA_UPGRADE_SET_BOOT_FAIL OTA upgrade set boot fail.
*/
int ota_read_parameter(ota_boot_param_t *param);
/**
* ota_update_parameter ota update parameter to flash.
*
* @param[in] ota_boot_param_t *param ota parameter
*
* @return OTA_SUCCESS OTA success.
* @return OTA_UPGRADE_WRITE_FAIL OTA upgrade write fail.
* @return OTA_UPGRADE_PARAM_FAIL OTA upgrade parameter fail.
* @return OTA_UPGRADE_FW_SIZE_FAIL OTA upgrade FW too big.
* @return OTA_UPGRADE_SET_BOOT_FAIL OTA upgrade set boot fail.
*/
int ota_update_parameter(ota_boot_param_t *param);
/**
* ota_get_fs_version ota get fs image version.
*
* @param[in] char *ver_buf store version buffer
* @param[in] cint ver_buf_len store version buffer len
*
* @return 0 get version success.
* @return -1 get version fail.
*/
int ota_get_fs_version(char *ver_buf, int ver_buf_len);
/**
* ota_check_image OTA check image.
*
* @param[in] unsigned int size OTA image size.
*
* @return OTA_SUCCESS OTA success.
* @return OTA_VERIFY_MD5_FAIL OTA verfiy MD5 fail.
* @return OTA_VERIFY_SHA2_FAIL OTA verfiy SH256 fail.
* @return OTA_VERIFY_RSA_FAIL OTA verfiy RSA fail.
* @return OTA_VERIFY_IMAGE_FAIL OTA verfiy image fail.
*/
int ota_check_image(unsigned int size);
/**
* ota_jsapp_version_get OTA parase js script version
*
* @param[in] char *version store version buf.
* @param[in] char *file_path js.app json file store path.
*
* @return 0 get version success.
* @return -1 get version failed.
*/
int ota_jsapp_version_get(char *version, char *file_path);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* OTA_AGNET_H */ | YifuLiu/AliOS-Things | components/ota/include/ota_agent.h | C | apache-2.0 | 23,309 |
/** @defgroup ota_hal_api
* @{
*
* This is an include file of OTA HAL interface.
*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#ifndef OTA_HAL_H
#define OTA_HAL_H
#include "ota_agent.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* ota_hal_init ota hal init main OTA partition.
*
* @param[in] ota_boot_param_t *param ota parameter
*
* @return OTA_SUCCESS OTA success.
* @return OTA_UPGRADE_WRITE_FAIL OTA upgrade write fail.
* @return OTA_UPGRADE_PARAM_FAIL OTA upgrade parameter fail.
* @return OTA_UPGRADE_FW_SIZE_FAIL OTA upgrade FW too big.
* @return OTA_UPGRADE_SET_BOOT_FAIL OTA upgrade set boot fail.
*/
int ota_hal_init(ota_boot_param_t *param);
/**
* ota_hal_read ota hal read main OTA partition.
*
* @param[in] unsigned int *off read offset.
* @param[in] char *buf read buffer.
* @param[in] unsigned int len read buffer len.
*
* @return OTA_SUCCESS OTA success.
* @return OTA_UPGRADE_WRITE_FAIL OTA upgrade write fail.
* @return OTA_UPGRADE_PARAM_FAIL OTA upgrade parameter fail.
* @return OTA_UPGRADE_FW_SIZE_FAIL OTA upgrade FW too big.
* @return OTA_UPGRADE_SET_BOOT_FAIL OTA upgrade set boot fail.
*/
int ota_hal_read(unsigned int *off, char *buf, unsigned int len);
/**
* ota_hal_write ota hal write main OTA partition.
*
* @param[in] unsigned int *off write offset.
* @param[in] char *buf write buf.
* @param[in] unsigned int len write buf len.
*
* @return OTA_SUCCESS OTA success.
* @return OTA_UPGRADE_WRITE_FAIL OTA upgrade write fail.
* @return OTA_UPGRADE_PARAM_FAIL OTA upgrade parameter fail.
* @return OTA_UPGRADE_FW_SIZE_FAIL OTA upgrade FW too big.
* @return OTA_UPGRADE_SET_BOOT_FAIL OTA upgrade set boot fail.
*/
int ota_hal_write(unsigned int *off, char *buf, unsigned int len);
/**
* ota_hal_boot ota hal boot.
*
* @param[in] ota_boot_param_t *param ota parameter
*
* @return OTA_SUCCESS OTA success.
* @return OTA_UPGRADE_WRITE_FAIL OTA upgrade write fail.
* @return OTA_UPGRADE_PARAM_FAIL OTA upgrade parameter fail.
* @return OTA_UPGRADE_FW_SIZE_FAIL OTA upgrade FW too big.
* @return OTA_UPGRADE_SET_BOOT_FAIL OTA upgrade set boot fail.
*/
int ota_hal_boot(ota_boot_param_t *parm);
/**
* ota_hal_reboot_bank ota hal reboot banker
*
* @param[in] void
*
* @return OTA_SUCCESS OTA success.
* @return OTA_UPGRADE_WRITE_FAIL OTA upgrade write fail.
* @return OTA_UPGRADE_PARAM_FAIL OTA upgrade parameter fail.
* @return OTA_UPGRADE_FW_SIZE_FAIL OTA upgrade FW too big.
* @return OTA_UPGRADE_SET_BOOT_FAIL OTA upgrade set boot fail.
*/
int ota_hal_reboot_bank(void);
/**
* ota_hal_rollback ota hal rollback.
*
* @return OTA_SUCCESS OTA success.
* @return OTA_UPGRADE_WRITE_FAIL OTA upgrade write fail.
* @return OTA_UPGRADE_PARAM_FAIL OTA upgrade parameter fail.
* @return OTA_UPGRADE_FW_SIZE_FAIL OTA upgrade FW too big.
* @return OTA_UPGRADE_SET_BOOT_FAIL OTA upgrade set boot fail.
*/
int ota_hal_rollback(void);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* OTA_HAL_H */
| YifuLiu/AliOS-Things | components/ota/include/ota_hal.h | C | apache-2.0 | 3,158 |
/** @defgroup ota_internal_api
* @{
*
* This is an include file of OTA internal interface.
*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#ifndef OTA_API_H
#define OTA_API_H
#include "ota_agent.h"
#ifdef __cplusplus
extern "C" {
#endif
#define OTA_INFO (UAGENT_FUNC_USER_BASE) /* ota process */
#define OTA_UPGRADE_CMD (UAGENT_FUNC_USER_BASE+1) /* upgrade command */
#define VERSION_INFORM (UAGENT_FUNC_USER_BASE+2) /* version inform */
#define OTA_COAP_OPTION_BLOCK 23 /*OTA coap option block*/
#ifndef OTA_DOWNLOAD_RETRY_CNT
#define OTA_DOWNLOAD_RETRY_CNT 5 /*OTA download retry count default:5*/
#endif
#ifndef OTA_DOWNLOAD_TIMEOUT
#define OTA_DOWNLOAD_TIMEOUT 20000 /*OTA download timeout Unit:ms default:20s*/
#endif
#ifndef OTA_DOWNLOAD_BLOCK_SIZE
#define OTA_DOWNLOAD_BLOCK_SIZE 2048 /*OTA download block size:2048*/
#endif
#ifndef OTA_FLASH_BLOCK_SIZE
#define OTA_FLASH_BLOCK_SIZE 0x10000 /*OTA erase/write block size:64K*/
#endif
#ifndef OTA_FLASH_WRITE_CACHE_SIZE
#define OTA_FLASH_WRITE_CACHE_SIZE 2048 /*OTA write flash cache size*/
#endif
#define OTA_MSG_LEN 256 /*OTA topic message max len*/
#define L_EXTRACT_U16(d) ((*((unsigned char *)(d)) << 8) | *((unsigned char *)(d) + 1))
#define L_EXTRACT_U32(d) \
((*((unsigned char *)(d)) << 24) | (*((unsigned char *)(d) + 1) << 16) | \
(*((unsigned char *)(d) + 2) << 8) | *((unsigned char *)(d) + 3))
#define EXTRACT_U16(d) (*((unsigned char *)(d)) | (*((unsigned char *)(d) + 1) << 8))
#define EXTRACT_U32(d) \
(*((unsigned char *)(d)) | (*((unsigned char *)(d) + 1) << 8) | \
(*((unsigned char *)(d) + 2) << 16) | (*((unsigned char *)(d) + 3) << 24))
#define ENCODE_U16(d, val) \
{ \
*((unsigned char *)(d)) = (val)&0xFF; \
*((unsigned char *)(d) + 1) = ((val) >> 8) & 0xFF; \
}
#define ENCODE_U32(d, val) \
{ \
*((unsigned char *)(d)) = (val)&0xFF; \
*((unsigned char *)(d) + 1) = ((val) >> 8) & 0xFF; \
*((unsigned char *)(d) + 2) = ((val) >> 16) & 0xFF; \
*((unsigned char *)(d) + 3) = ((val) >> 24) & 0xFF; \
}
enum {
OTA_PROCESS_NORMAL = 0,
OTA_PROCESS_UAGENT_OTA
};
typedef enum {
OTA_REQ_VERSION = 0,
OTA_UPGRADE_SOC = 1,
OTA_UPGRADE_MCU = 2
} OTA_UPGRADE_CMD_T;
/**
*
* ota transport
*
**/
typedef enum {
OTA_PAR_SUCCESS = 0,
OTA_ARGS_PAR_FAIL = -1,
OTA_MESSAGE_PAR_FAIL = -2,
OTA_SUCCESS_PAR_FAIL = -3,
OTA_DATA_PAR_FAIL = -4,
OTA_URL_PAR_FAIL = -5,
OTA_VER_PAR_FAIL = -6,
OTA_HASH_PAR_FAIL = -7,
OTA_MD5_PAR_FAIL = -8,
OTA_SHA256_PAR_FAIL = -9,
OTA_SIZE_PAR_FAIL = -10,
OTA_SIGN_PAR_FAIL = -11,
} OTA_TRANSPORT_ERR_E;
/*
*
* ota verify
*/
#define OTA_HASH_NONE (0)
#define OTA_SHA256 (1)
#define OTA_MD5 (2)
#define OTA_SHA256_HASH_SIZE (32)
#define OTA_MD5_HASH_SIZE (16)
#define OTA_SIGN_BITNUMB (2048)
#if defined(__ICCARM__)
#define OTA_WEAK __weak
#else
#define OTA_WEAK __attribute__((weak))
#endif
int ota_read_parameter(ota_boot_param_t *ota_param);
int ota_update_parameter(ota_boot_param_t *ota_param);
int ota_clear();
int hal_reboot_bank(void);
int ota_clear_paramters();
int ota_is_download_mode(void);
int ota_int(ota_boot_param_t *param);
int ota_verify(ota_boot_param_t *param);
int ota_verify_fsfile(ota_boot_param_t *param, char *file_path);
int ota_write(unsigned int *off, char *in_buf, unsigned int in_buf_len);
int ota_read(unsigned int *off, char *out_buf, unsigned int out_buf_len);
int ota_fclose(int fd);
int ota_fopen(const char *filename, int mode);
int ota_fread(int fd, void *buf, unsigned int size);
int ota_fwrite(int fd, const void *buf, unsigned int size);
int ota_check_hash(unsigned char type, char *src, char *dst); /* ota compare hash value. */
unsigned short ota_get_upgrade_flag(void); /* ota get upgrade flag. */
int ota_update_upg_flag(unsigned short flag); /* ota update upgrade flag. */
int ota_update_process(const char *err, const int step);
unsigned int ota_parse_ota_type(unsigned char *buf, unsigned int len); /* parse ota type:diff xz or normal*/
int ota_transport_inform_otaver(ota_service_t *ctx);
void ota_set_upgrade_status(char is_upgrade);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /*__OTA_API_H__*/
| YifuLiu/AliOS-Things | components/ota/include/ota_import.h | C | apache-2.0 | 4,746 |
/** @defgroup ota_log_api
* @{
*
* This is an include file of OTA log interface.
*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#ifndef OTA_LOG_H
#define OTA_LOG_H
#include <stdarg.h>
#include <stdio.h>
#include "ulog/ulog.h"
#ifdef __cplusplus
extern "C" {
#endif
#define OTA_LOG_D(fmt, ...) LOGD("ota",fmt,##__VA_ARGS__)
#define OTA_LOG_I(fmt, ...) LOGI("ota",fmt,##__VA_ARGS__)
#define OTA_LOG_W(fmt, ...) LOGW("ota",fmt,##__VA_ARGS__)
#define OTA_LOG_E(fmt, ...) LOGE("ota",fmt,##__VA_ARGS__)
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif/*OTA_LOG_H*/
| YifuLiu/AliOS-Things | components/ota/include/ota_log.h | C | apache-2.0 | 581 |
/* *@defgroup ota_updater_api
* @{
*
* This is an include file of OTA updater to install new Firmware.
*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#ifndef OTA_UPDATE_H
#define OTA_UPDATE_H
#include "ota_agent.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* ENUM: OTA Updater ERRNO.
*/
typedef enum {
OTA_UPDATER_OK = 0,
OTA_NB_INVALID_PARAM = -1, /* ota patch invalid parameter */
OTA_NB_HEADER_FAIL = -2, /* ota patch header fail */
OTA_NB_MEMORY_FAIL = -3, /* ota patch memory fail */
OTA_NB_READ_CTRL_FAIL = -4, /* ota patch read control fail */
OTA_NB_READ_DIFF_FAIL = -5, /* ota patch read diff fail */
OTA_NB_READ_OLD_FAIL = -6, /* ota patch read old fail */
OTA_NB_READ_EXTRA_FAIL = -7, /* ota patch read extra fail */
OTA_NB_WRITE_DATA_FAIL = -8, /* ota patch write data fail */
OTA_NB_CRC_COMP_FAIL = -9, /* ota patch crc fail */
OTA_XZ_PARAM_FAIL = -10, /* ota XZ parameter fail */
OTA_XZ_CRC_FAIL = -11, /* ota XZ crc fail */
OTA_XZ_UNCOMP_FAIL = -12, /* ota XZ uncompress fail */
OTA_XZ_VERIFY_FAIL = -13, /* ota XZ verify fail */
OTA_XZ_MEM_FAIL = -14, /* ota XZ memory fail */
OTA_YMODEM_UP_FAIL = -15, /* ota Ymodem upgrade fail */
OTA_USB_UP_FAIL = -16, /* ota USB upgrade fail */
OTA_IMAGE_CRC_FAIL = -17, /* ota image crc fail */
OTA_IMAGE_COPY_FAIL = -18, /* ota image copy fail */
} OTA_UPDATER_E;
/**
* ota_nbpatch_main ota nbpatch main.
*
* @return OTA_SUCCESS OTA success.
* @return OTA_NB_INVALID_PARAM OTA patch invalid parameter.
* @return OTA_NB_HEADER_FAIL OTA patch header fail.
* @return OTA_NB_MEMORY_FAIL OTA patch memory fail.
* @return OTA_NB_READ_CTRL_FAIL OTA patch read control fail.
* @return OTA_NB_READ_DIFF_FAIL OTA patch read diff fail.
* @return OTA_NB_READ_OLD_FAIL OTA patch read old fail.
* @return OTA_NB_READ_EXTRA_FAIL OTA patch read extra fail.
* @return OTA_NB_WRITE_DATA_FAIL OTA patch write data fail.
* @return OTA_NB_CRC_COMP_FAIL OTA patch crc fail.
*/
int ota_nbpatch_main(void);
/**
* ota_xz_main ota xz uncompress main.
*
* @return OTA_SUCCESS OTA success.
* @return OTA_XZ_PARAM_FAIL OTA XZ parameter fail.
* @return OTA_XZ_CRC_FAIL OTA XZ crc fail.
* @return OTA_XZ_UNCOMP_FAIL OTA XZ uncompress fail.
* @return OTA_XZ_VERIFY_FAIL OTA XZ verify fail.
* @return OTA_XZ_MEM_FAIL OTA XZ memory fail.
*/
int ota_xz_main(void);
/**
* ota_image_check ota image crc check.
*
* @param[in] unsigned int addr OTA check addr.
* @param[in] unsigned int size OTA image size.
* @param[in] unsigned int crc OTA image crc.
*
* @return OTA_SUCCESS OTA success.
* @return OTA_IMAGE_CRC_FAIL OTA image crc fail.
* @return OTA_IMAGE_COPY_FAIL OTA image copy fail.
*/
int ota_image_check(unsigned int addr, unsigned int size, unsigned int crc);
/**
* ota_image_copy ota image copy.
*
* @param[in] unsigned int addr OTA image des addr.
* @param[in] unsigned int src OTA image src addr.
* @param[in] unsigned int size OTA image size.
*
* @return OTA_SUCCESS OTA success.
* @return OTA_IMAGE_CRC_FAIL OTA image crc fail.
* @return OTA_IMAGE_COPY_FAIL OTA image copy fail.
*/
int ota_image_copy(unsigned int dst, unsigned int src, unsigned int size);
/**
* ota_read_parameter ota read parameter from flash.
*
* @param[in] ota_boot_param_t *param ota parameter
*
* @return OTA_SUCCESS OTA success.
* @return OTA_UPGRADE_WRITE_FAIL OTA upgrade write fail.
* @return OTA_UPGRADE_PARAM_FAIL OTA upgrade parameter fail.
* @return OTA_UPGRADE_FW_SIZE_FAIL OTA upgrade FW too big.
* @return OTA_UPGRADE_SET_BOOT_FAIL OTA upgrade set boot fail.
*/
int ota_patch_read_param(ota_boot_param_t *param);
/**
* ota_update_parameter ota update parameter to flash.
*
* @param[in] ota_boot_param_t *param ota parameter
*
* @return OTA_SUCCESS OTA success.
* @return OTA_UPGRADE_WRITE_FAIL OTA upgrade write fail.
* @return OTA_UPGRADE_PARAM_FAIL OTA upgrade parameter fail.
* @return OTA_UPGRADE_FW_SIZE_FAIL OTA upgrade FW too big.
* @return OTA_UPGRADE_SET_BOOT_FAIL OTA upgrade set boot fail.
*/
int ota_patch_write_param(ota_boot_param_t *param);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif
| YifuLiu/AliOS-Things | components/ota/include/ota_updater.h | C | apache-2.0 | 4,484 |
/*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include "ota_log.h"
#include "ota_hal_os.h"
#include "ota_import.h"
#include "ota_hal_trans.h"
#include "httpclient.h"
int ota_get_upgrade_status(void);
void ota_set_upgrade_status(char is_upgrade);
int ota_download_extract_url(char *src_url, char *dest_url, unsigned int dest_buf_len);
int ota_httpc_request_send(httpclient_t *client, char *url, httpclient_data_t *client_data);
int ota_httpc_recv_data(httpclient_t *client, httpclient_data_t *client_data);
int ota_httpc_settings_init(httpclient_t *client, httpclient_data_t *client_data);
void ota_httpc_settings_destory(httpclient_t *client);
/**
* ota_download_store_fs_start OTA download file start and store in fs
*
* @param[in] char *url download url
* @param[in] unsigned int url_len download url length
* @param[in] char *store_path store file path and name eg:/root/test.bin
* @param[in] report_func report_func report http downloading status function
* @param[in] void *user_param user's param for report_func
*
* @return OTA_SUCCESS OTA success.
* @return OTA_DOWNLOAD_INIT_FAIL OTA download init failed.
* @return OTA_DOWNLOAD_CON_FAIL OTA download connect failed.
* @return OTA_DOWNLOAD_REQ_FAIL OTA download request failed.
* @return OTA_DOWNLOAD_RECV_FAIL OTA download receive failed.
*/
int ota_download_store_fs_start(char *url, unsigned int url_len, char *store_path,
report_func report_func, void *user_param)
{
int j = 0;
int fd = -1;
int ret = OTA_DOWNLOAD_INIT_FAIL;
unsigned int off_size = 0;
int ota_rx_size = 0;
int ota_file_size = 0;
char tmp_header[64] = {0};
unsigned char ota_header_found = false;
httpclient_t client = {0};
httpclient_data_t client_data = {0};
char *new_url = NULL;
int tmp_url_len = 0;
int percent = 0;
int divisor = 5;
if ((store_path == NULL) || (url == NULL)) {
ret = OTA_DOWNLOAD_INIT_FAIL;
return ret;
}
if (ota_get_upgrade_status() == 1) {
ret = OTA_DOWNLOAD_INIT_FAIL;
return ret;
}
tmp_url_len = url_len + 1;
new_url = ota_malloc(tmp_url_len);
if (new_url == NULL) {
ret = OTA_DOWNLOAD_INIT_FAIL;
return ret;
}
memset(new_url, 0, tmp_url_len);
if (ota_download_extract_url(url, new_url, tmp_url_len) < 0) {
if (new_url != NULL) {
ota_free(new_url);
}
ret = OTA_DOWNLOAD_INIT_FAIL;
return ret;
}
fd = ota_fopen(store_path, O_WRONLY | O_CREAT | O_TRUNC);
if (fd < 0) {
if (new_url != NULL) {
ota_free(new_url);
}
ret = OTA_DOWNLOAD_INIT_FAIL;
OTA_LOG_E("open %s failed\n", store_path);
return ret;
}
for (j = OTA_DOWNLOAD_RETRY_CNT; (j > 0) && (ret < 0); j--) {
memset(&client_data, 0, sizeof(client_data));
memset(&client, 0 , sizeof(client));
ret = ota_httpc_settings_init(&client, &client_data);
if (ret < 0) {
ret = OTA_DOWNLOAD_INIT_FAIL;
goto EXIT;
}
memset(tmp_header, 0, sizeof(tmp_header));
if (j >= OTA_DOWNLOAD_RETRY_CNT) {
strncpy(tmp_header, "Accept: */*\r\n", sizeof(tmp_header));
tmp_header[sizeof(tmp_header) - 1] = 0;
} else {
ota_msleep(6000);
OTA_LOG_I("reconnect retry:%d ret:%d rx_size:%d\n", j, ret, off_size);
ota_snprintf(tmp_header, sizeof(tmp_header), "Range: bytes=%d-\r\n", off_size);
}
client.header = tmp_header;
ret = httpclient_conn(&client, new_url);
if (ret < 0) {
ret = OTA_DOWNLOAD_CON_FAIL;
goto EXIT;
}
ret = ota_httpc_request_send(&client, new_url, &client_data);
if (ret < 0) {
ret = OTA_DOWNLOAD_REQ_FAIL;
goto EXIT;
}
ota_set_upgrade_status(1);
OTA_LOG_E("ota download begin....\n");
while (ota_file_size == 0 || ota_rx_size < ota_file_size) {
ret = ota_httpc_recv_data(&client, &client_data);
if (ota_get_upgrade_status() == 0) {
OTA_LOG_E("download stop.\n");
ret = OTA_DOWNLOAD_RECV_FAIL;
break;
} else if (ret < 0) {
ret = OTA_DOWNLOAD_RECV_FAIL;
break;
} else {
if (ota_header_found == false) {
int val_pos, val_len;
ota_header_found = true;
if (0 == httpclient_get_response_header_value(client_data.header_buf, "Content-Length", (int *)&val_pos, (int *)&val_len)) {
sscanf(client_data.header_buf + val_pos, "%d", &ota_file_size);
}
}
ret = ota_fwrite(fd, client_data.response_buf, client_data.content_block_len);
if (ret < 0) {
ret = OTA_UPGRADE_WRITE_FAIL;
goto EXIT;
}
ota_rx_size += client_data.content_block_len;
ota_msleep(5);
off_size += client_data.content_block_len;
if (ota_file_size) {
percent = ((long)(ota_rx_size >> 6) * 100) / (long)(ota_file_size >> 6);
if (percent / divisor) {
divisor += 5;
if (report_func != NULL) {
ret = report_func(user_param, percent);
if (ret < 0) {
OTA_LOG_E("report http download process failed, ret = %d", ret);
}
}
OTA_LOG_I(" in fs recv data(%d/%d) off:%d\r\n", ota_rx_size, ota_file_size, off_size);
}
}
}
}
EXIT:
ota_set_upgrade_status(0);
ota_httpc_settings_destory(&client);
ota_header_found = false;
ota_file_size = 0;
ota_rx_size = 0;
}
if (fd >= 0) {
(void)ota_fclose(fd);
fd = -1;
}
if (new_url != NULL) {
ota_free(new_url);
new_url = NULL;
}
OTA_LOG_I("in fs download complete:%d\n", ret);
return ret;
}
| YifuLiu/AliOS-Things | components/ota/ota_agent/download/ota_download_file2fs_http.c | C | apache-2.0 | 6,502 |
/*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include "ota_log.h"
#include "ota_hal_os.h"
#include "ota_import.h"
#include "ota_hal_trans.h"
#include "httpclient.h"
static int ota_upgrading = 0;
static unsigned char dl_buf[OTA_DOWNLOAD_BLOCK_SIZE] = {0};
static unsigned char head_buf[OTA_DOWNLOAD_BLOCK_SIZE] = {0};
#if defined OTA_CONFIG_SECURE_DL_MODE
static const char *ca_cert = \
{ \
"-----BEGIN CERTIFICATE-----\r\n"
"MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkG\r\n" \
"A1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jv\r\n" \
"b3QgQ0ExGzAZBgNVBAMTEkdsb2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAw\r\n" \
"MDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9i\r\n" \
"YWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYDVQQDExJHbG9iYWxT\r\n" \
"aWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDaDuaZ\r\n" \
"jc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavp\r\n" \
"xy0Sy6scTHAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp\r\n" \
"1Wrjsok6Vjk4bwY8iGlbKk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdG\r\n" \
"snUOhugZitVtbNV4FpWi6cgKOOvyJBNPc1STE4U6G7weNLWLBYy5d4ux2x8gkasJ\r\n" \
"U26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrXgzT/LCrBbBlDSgeF59N8\r\n" \
"9iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8E\r\n" \
"BTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0B\r\n" \
"AQUFAAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOz\r\n" \
"yj1hTdNGCbM+w6DjY1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE\r\n" \
"38NflNUVyRRBnMRddWQVDf9VMOyGj/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymP\r\n" \
"AbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhHhm4qxFYxldBniYUr+WymXUad\r\n" \
"DKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveCX4XSQRjbgbME\r\n" \
"HMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\r\n" \
"-----END CERTIFICATE-----"
};
#endif
void ota_set_upgrade_status(char is_upgrade)
{
ota_upgrading = is_upgrade;
}
int ota_get_upgrade_status()
{
return ota_upgrading;
}
/**
* ota_httpc_settings_init init httpc settings
*
* @param[in] httpclient_t *client http client handle
* @param[in] httpclient_data_t *client_data httpc data
*
* @return 0 success
* @return -1 fail
*/
int ota_httpc_settings_init(httpclient_t *client, httpclient_data_t *client_data)
{
int ret = -1;
if ((client != NULL) && (client_data != NULL)) {
ret = 0;
#if defined OTA_CONFIG_SECURE_DL_MODE
OTA_LOG_I("init https ota.\n");
client->server_cert = ca_cert;
client->server_cert_len = strlen(ca_cert) + 1;
#else
OTA_LOG_I("init http.\n");
#endif
memset(head_buf, 0, sizeof(head_buf));
client_data->header_buf = (char *)head_buf;
client_data->header_buf_len = sizeof(head_buf);
memset(dl_buf, 0, sizeof(dl_buf));
client_data->response_buf = (char *)dl_buf;
client_data->response_buf_len = sizeof(dl_buf);
}
return ret;
}
/**
* ota_httpc_settings_destory destory httpc settings
*
* @param[in] httpc_connection_t *settings httpc settings
*
* @return void
*/
void ota_httpc_settings_destory(httpclient_t *client)
{
httpclient_clse(client);
}
/**
* ota_httpc_request_send OTA send request to server
*
* @param[in] httpclient_t *client httpc client
* @param[in] char *url host url
* @param[in] httpclient_data_t *client_data ttpc response infomation
*
* @return 0 success.
* @return -1 failed.
*/
int ota_httpc_request_send(httpclient_t *client, char *url, httpclient_data_t *client_data)
{
int ret = -1;
if (client == NULL || url == NULL || client_data == NULL) {
OTA_LOG_E("http recv fuc input parameter err\n");
} else {
ret = httpclient_send(client, url, HTTP_GET, client_data);
if (ret < 0) {
OTA_LOG_E("send data ret:%d\n", ret);
}
}
return ret;
}
/**
* ota_httpc_recv_data OTA receive data from httpc
*
* @param[in] httpclient_t *client httpc handle
* @param[in] httpclient_data_t *client_data httpc response infomation
*
* @return 0 success.
* @return -1 failed.
*/
int ota_httpc_recv_data(httpclient_t *client, httpclient_data_t *client_data)
{
int ret = -1;
if (client == NULL || client_data == NULL) {
OTA_LOG_E("http recv fuc input parameter err\n");
} else {
ret = httpclient_recv(client, client_data);
if ((ret == HTTP_ERECV) || (ret == HTTP_ETIMEOUT)) {
OTA_LOG_E("recv ret:%d\n", ret);
}
}
return ret;
}
/**
* ota_download_extract_url OTA extrack http url from https url
*
* @param[in] char *src_url src https url.
* @param[in] char *dest_url new url store buf.
* @param[in] char *dest_buf_len new url store buf len.
*
* @return 0 success, others fail
*/
int ota_download_extract_url(char *src_url, char *dest_url, unsigned int dest_buf_len)
{
int ret = 0;
unsigned int len = 0;
if ((src_url == NULL) || (strlen(src_url) == 0) || (dest_url == NULL)) {
OTA_LOG_E("url parms error!");
return OTA_DOWNLOAD_INIT_FAIL;
}
len = strlen(src_url);
if (len > dest_buf_len) {
OTA_LOG_E("url too long!");
return OTA_DOWNLOAD_INIT_FAIL;
}
OTA_LOG_I("cpy len = %d\r\n", len);
strncpy(dest_url, src_url, dest_buf_len);
dest_url[dest_buf_len - 1] = 0;
#ifndef OTA_CONFIG_SECURE_DL_MODE
if (dest_url[4] == 's') {
int i = 0;
for (i = 4; i < len; i++) {
dest_url[i] = dest_url[i + 1];
}
dest_url[i] = 0;
}
#endif
OTA_LOG_I("http_uri:%s\n", dest_url);
return ret;
}
/**
* ota_download_image_header OTA download image header
*
* @param[in] ota_service_t *ctx ota service context
* @param[in] char *url download url
* @param[in] unsigned int url_len download url length
* @param[in] unsigned int size image size
*
*
* @return OTA_SUCCESS OTA success.
* @return OTA_DOWNLOAD_INIT_FAIL OTA download init failed.
* @return OTA_DOWNLOAD_CON_FAIL OTA download connect failed.
* @return OTA_DOWNLOAD_REQ_FAIL OTA download request failed.
* @return OTA_DOWNLOAD_RECV_FAIL OTA download receive failed.
*/
int ota_download_image_header(ota_service_t *ctx, char *url, unsigned int url_len, unsigned int size)
{
int ret = OTA_DOWNLOAD_INIT_FAIL;
unsigned int off_size = 0;
char *content = NULL;
char tmp_header[64] = {0};
int retry_tm = 0;
int ota_rx_size = 0;
int want_download_size = 0;
unsigned char ota_header_found = false;
httpclient_t client = { 0 };
httpclient_data_t client_data = {0};
char *new_url = NULL;
int tmp_url_len = 0;
#ifdef OTA_CONFIG_LOCAL_RSA
char *sign_info_ptr = NULL;
#endif
char *image_info_ptr = NULL;
if ((ctx == NULL) || (url == NULL) || (ota_get_upgrade_status() == 1)) {
ret = OTA_DOWNLOAD_INIT_FAIL;
return ret;
}
#ifdef OTA_CONFIG_LOCAL_RSA
sign_info_ptr = (char *)ctx->header.sign_info;
if (sign_info_ptr == NULL) {
ret = OTA_DOWNLOAD_INIT_FAIL;
return ret;
}
#endif
image_info_ptr = (char *)ctx->header.image_info;
if (image_info_ptr == NULL) {
ret = OTA_DOWNLOAD_INIT_FAIL;
return ret;
}
tmp_url_len = url_len + 1;
OTA_LOG_I("URl len = %d\r\n", url_len);
new_url = ota_malloc(tmp_url_len);
if (new_url == NULL) {
ret = OTA_DOWNLOAD_INIT_FAIL;
return ret;
}
memset(new_url, 0, tmp_url_len);
if (ota_download_extract_url(url, new_url, tmp_url_len) < 0) {
if (new_url != NULL) {
ota_free(new_url);
}
ret = OTA_DOWNLOAD_INIT_FAIL;
return ret;
}
#ifdef OTA_CONFIG_LOCAL_RSA
off_size = size - sizeof(ota_image_info_t) - sizeof(ota_sign_info_t);
#else
off_size = size - sizeof(ota_image_info_t);
#endif
for (retry_tm = OTA_DOWNLOAD_RETRY_CNT; (retry_tm > 0) && (ret < 0); retry_tm--) {
if (retry_tm < OTA_DOWNLOAD_RETRY_CNT) {
OTA_LOG_I("retry count.\n");
ota_msleep(6000);
}
ret = ota_httpc_settings_init(&client, &client_data);
if (ret < 0) {
ret = OTA_DOWNLOAD_INIT_FAIL;
goto OVER;
}
memset(tmp_header, 0, sizeof(tmp_header));
OTA_LOG_I("retry:%d ret:%d rx_size:%d\n", retry_tm, ret, off_size);
ota_snprintf(tmp_header, sizeof(tmp_header), "Range: bytes=%d-\r\n", off_size);
client.header = tmp_header;
OTA_LOG_I("http conn.\n");
ret = httpclient_conn(&client, new_url);
if (ret < 0) {
ret = OTA_DOWNLOAD_INIT_FAIL;
goto OVER;
}
OTA_LOG_I("http request send.\n");
ret = ota_httpc_request_send(&client, new_url, &client_data);
if (ret < 0) {
ret = OTA_DOWNLOAD_REQ_FAIL;
goto OVER;
}
ota_set_upgrade_status(1);
OTA_LOG_I("http begin download.\n");
while (want_download_size == 0 || ota_rx_size < want_download_size) {
ret = ota_httpc_recv_data(&client, &client_data);
if (ret < 0) {
ret = OTA_DOWNLOAD_RECV_FAIL;
break;
} else {
int tmp_size = client_data.content_block_len;
content = (char *)client_data.response_buf;
if (ota_header_found == false) {
ota_header_found = true;
int val_pos, val_len;
if (0 == httpclient_get_response_header_value(client_data.header_buf, "Content-Length", (int *)&val_pos, (int *)&val_len)) {
sscanf(client_data.header_buf + val_pos, "%d", &want_download_size);
}
}
if (ota_rx_size + tmp_size <= off_size) {
#ifdef OTA_CONFIG_LOCAL_RSA
if (ota_rx_size + tmp_size <= sizeof(ota_sign_info_t)) {
memcpy(sign_info_ptr, content, tmp_size);
sign_info_ptr += tmp_size;
ota_rx_size += tmp_size;
} else {
if (ota_rx_size <= sizeof(ota_sign_info_t)) {
unsigned int remain_len = sizeof(ota_sign_info_t) - ota_rx_size;
memcpy(sign_info_ptr, content, remain_len);
sign_info_ptr += remain_len;
content += remain_len;
memcpy(image_info_ptr, content, tmp_size - remain_len);
image_info_ptr += tmp_size - remain_len;
ota_rx_size += tmp_size;
} else {
memcpy(image_info_ptr, content, tmp_size);
image_info_ptr += tmp_size;
ota_rx_size += tmp_size;
}
}
#else
memcpy(image_info_ptr, content, tmp_size);
image_info_ptr += tmp_size;
ota_rx_size += tmp_size;
#endif
} else {
OTA_LOG_E("image head buf full");
ret = OTA_DOWNLOAD_RECV_FAIL;
retry_tm = 0;
break;
}
}
}
OVER:
ota_set_upgrade_status(0);
ota_httpc_settings_destory(&client);
ota_header_found = false;
want_download_size = 0;
ota_rx_size = 0;
}
if (new_url != NULL) {
ota_free(new_url);
new_url = NULL;
}
OTA_LOG_I("parse image info:%d\n", ret);
return ret;
}
/**
* ota_download_start OTA download start
*
* @param[in] char *url download url
* @param[in] unsigned int url_len download url length
* @param[in] report_func repot_func report http downloading status function
* @param[in] void *user_param user's param for repot_func
*
* @return OTA_SUCCESS OTA success.
* @return OTA_DOWNLOAD_INIT_FAIL OTA download init failed.
* @return OTA_DOWNLOAD_CON_FAIL OTA download connect failed.
* @return OTA_DOWNLOAD_REQ_FAIL OTA download request failed.
* @return OTA_DOWNLOAD_RECV_FAIL OTA download receive failed.
*/
int ota_download_start(char *url, unsigned int url_len, report_func repot_func, void *user_param)
{
int ret = OTA_DOWNLOAD_INIT_FAIL;
unsigned int offset = 0;
unsigned int off_size = 0;
int j = 0;
int ota_rx_size = 0;
int ota_file_size = 0;
char tmp_header[64] = {0};
unsigned char ota_header_found = false;
httpclient_t client = {0};
httpclient_data_t client_data = {0};
char *new_url = NULL;
int tmp_url_len = 0;
int percent = 0;
int divisor = 5;
if (url == NULL) {
ret = OTA_DOWNLOAD_INIT_FAIL;
return ret;
}
if (ota_get_upgrade_status() == 1) {
ret = OTA_DOWNLOAD_INIT_FAIL;
return ret;
}
tmp_url_len = url_len + 1;
OTA_LOG_I("URl len = %d\r\n", url_len);
new_url = ota_malloc(tmp_url_len);
if (new_url == NULL) {
ret = OTA_DOWNLOAD_INIT_FAIL;
return ret;
}
memset(new_url, 0, tmp_url_len);
if (ota_download_extract_url(url, new_url, tmp_url_len) < 0) {
if (new_url != NULL) {
ota_free(new_url);
}
ret = OTA_DOWNLOAD_INIT_FAIL;
return ret;
}
for (j = OTA_DOWNLOAD_RETRY_CNT; (j > 0) && (ret < 0); j--) {
memset(&client_data, 0, sizeof(client_data));
memset(&client, 0 , sizeof(client));
ret = ota_httpc_settings_init(&client, &client_data);
if (ret < 0) {
ret = OTA_DOWNLOAD_INIT_FAIL;
goto EXIT;
}
memset(tmp_header, 0, sizeof(tmp_header));
if (j >= OTA_DOWNLOAD_RETRY_CNT) {
strncpy(tmp_header, "Accept: */*\r\n", sizeof(tmp_header));
tmp_header[sizeof(tmp_header) - 1] = 0;
} else {
ota_msleep(6000);
OTA_LOG_I("reconnect retry:%d ret:%d rx_size:%d\n", j, ret, off_size);
ota_snprintf(tmp_header, sizeof(tmp_header), "Range: bytes=%d-\r\n", off_size);
}
client.header = tmp_header;
ret = httpclient_conn(&client, new_url);
if (ret < 0) {
ret = OTA_DOWNLOAD_CON_FAIL;
goto EXIT;
}
ret = ota_httpc_request_send(&client, new_url, &client_data);
if (ret < 0) {
ret = OTA_DOWNLOAD_REQ_FAIL;
goto EXIT;
}
ota_set_upgrade_status(1);
while (ota_file_size == 0 || ota_rx_size < ota_file_size) {
ret = ota_httpc_recv_data(&client, &client_data);
if (ota_get_upgrade_status() == 0) {
OTA_LOG_E("download stop.\n");
ret = OTA_DOWNLOAD_RECV_FAIL;
break;
} else if (ret < 0) {
ret = OTA_DOWNLOAD_RECV_FAIL;
break;
} else {
if (ota_header_found == false) {
int val_pos, val_len;
ota_header_found = true;
if (0 == httpclient_get_response_header_value(client_data.header_buf, "Content-Length", (int *)&val_pos, (int *)&val_len)) {
sscanf(client_data.header_buf + val_pos, "%d", &ota_file_size);
printf("ota_file_size %d\r\n", ota_file_size);
}
}
ret = ota_write(&offset, client_data.response_buf, client_data.content_block_len);
if (ret < 0) {
ret = OTA_UPGRADE_WRITE_FAIL;
goto EXIT;
}
ota_rx_size += client_data.content_block_len;
ota_msleep(5);
off_size += client_data.content_block_len;
OTA_LOG_I("recv size = %d, has recv size = %d\r\n", client_data.content_block_len, off_size);
if (ota_file_size) {
percent = ((long)(ota_rx_size >> 6) * 100) / (long)(ota_file_size >> 6);
if (percent / divisor) {
divisor += 5;
if (repot_func != NULL) {
ret = repot_func(user_param, percent);
if (ret != 0) {
OTA_LOG_E("report http download process failed ret %d\r\n", ret);
}
}
OTA_LOG_I("ota recv data(%d/%d) off:%d \r\n", ota_rx_size, ota_file_size, off_size);
}
}
}
}
EXIT:
ota_set_upgrade_status(0);
ota_httpc_settings_destory(&client);
ota_header_found = false;
ota_file_size = 0;
ota_rx_size = 0;
}
if (new_url != NULL) {
ota_free(new_url);
new_url = NULL;
}
OTA_LOG_I("download complete:%d\n", ret);
return ret;
}
| YifuLiu/AliOS-Things | components/ota/ota_agent/download/ota_download_http.c | C | apache-2.0 | 17,268 |
/*
*Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#include <string.h>
#include "ota_log.h"
#include "ota_import.h"
#include "ota_hal_os.h"
#include "ota_hal.h"
#ifdef AOS_COMP_PWRMGMT
#include "aos/pwrmgmt.h"
#endif
#if !defined(OTA_LINUX) && defined OTA_CONFIG_SECURE_DL_MODE
static wdg_dev_t ota_wdg = {0};
static aos_timer_t ota_mon_tmr = {0};
static void ota_monitor_task(void *arg1, void* arg2)
{
hal_wdg_reload(&ota_wdg);
}
#endif
int ota_download_to_fs_service(void *ota_ctx , char *file_path)
{
/* OTA download init */
int ret = 0;
ota_boot_param_t ota_param = {0};
ota_service_t *ctx = ota_ctx;
if (ctx == NULL || file_path == NULL) {
goto SERVER_OVER;
}
ret = ota_read_parameter(&ota_param);
if (ret < 0) {
goto SERVER_OVER;
}
ota_param.url[sizeof(ota_param.url) - 1] = 0;
ret = ota_download_store_fs_start(ota_param.url, strlen(ota_param.url), file_path,
ctx->report_func.report_status_cb, ctx->report_func.param);
if (ret < 0) {
goto SERVER_OVER;
}
OTA_LOG_I("verify subdev ota fs file\n");
ret = ota_verify_fsfile(&ota_param, file_path);
if (ret < 0) {
OTA_LOG_E("verify subdev ota fs file failed\n");
goto SERVER_OVER;
}
SERVER_OVER:
OTA_LOG_I("Subdev download complete ret = %d\n", ret);
if (ret < 0) {
if ((ctx != NULL) && (ctx->report_func.report_status_cb != NULL)) {
ctx->report_func.report_status_cb(ctx->report_func.param, ret);
}
}
if ((ctx != NULL) && (ctx->feedback_func.on_user_event_cb != NULL)) {
ctx->feedback_func.on_user_event_cb(OTA_EVENT_DOWNLOAD, ret, ctx->feedback_func.param);
}
return ret;
}
int ota_report_module_version(void *ota_ctx, char *module_name, char *version)
{
int ret = -1;
ota_service_t *ctx = ota_ctx;
OTA_LOG_I("report submode version\n");
if (ctx == NULL) {
OTA_LOG_E("report submode version ctx is null\n");
goto OTA_REPORT_M_VER_OVER;
}
if (version == NULL) {
OTA_LOG_E("submode version is null\n");
goto OTA_REPORT_M_VER_OVER;
}
ret = ota_transport_inform(ctx->mqtt_client, ctx->pk, ctx->dn, module_name, version);
if (ctx->feedback_func.on_user_event_cb != NULL) {
ctx->feedback_func.on_user_event_cb(OTA_EVENT_REPORT_VER, ret, ctx->feedback_func.param);
}
OTA_REPORT_M_VER_OVER:
if (ret < 0) {
OTA_LOG_E("module report version failed\n");
}
return ret;
}
/**
* ota_service_start OTA service start: download and upgrade
*
* @param[in] void
*
* @return int
*/
int ota_service_start(ota_service_t *ctx)
{
int ret = 0;
unsigned int url_len = 0;
ota_boot_param_t ota_param = {0};
if (ctx == NULL) {
ret = OTA_DOWNLOAD_INIT_FAIL;
return ret;
}
ret = ota_read_parameter(&ota_param);
if (ret < 0) {
goto EXIT;
}
ota_param.url[sizeof(ota_param.url) - 1] = 0;
url_len = strlen(ota_param.url);
OTA_LOG_I("download start upg_flag:0x%x\n", ota_param.upg_flag);
#if !defined(OTA_LINUX) && defined OTA_CONFIG_SECURE_DL_MODE
ota_wdg.config.timeout = 180000;
hal_wdg_init(&ota_wdg);
aos_timer_new(&ota_mon_tmr, ota_monitor_task, NULL, 3000, 1);
if (ota_is_download_mode() == 0) {
ret = OTA_INIT_FAIL;
goto EXIT;
}
#endif
#ifdef AOS_COMP_PWRMGMT
aos_pwrmgmt_lowpower_suspend(PWRMGMT_OTA);
#endif
/* parse image header */
ctx->header.image_info = ota_malloc(sizeof(ota_image_info_t));
if (ctx->header.image_info == NULL) {
OTA_LOG_E("mem err.\n");
ret = OTA_INIT_FAIL;
goto EXIT;
}
#ifdef OTA_CONFIG_LOCAL_RSA
ctx->header.sign_info = ota_malloc(sizeof(ota_sign_info_t));
if (ctx->header.sign_info == NULL) {
OTA_LOG_E("mem err.\n");
ret = OTA_INIT_FAIL;
goto EXIT;
}
#endif
if (ota_param.upg_flag != OTA_UPGRADE_DIFF) {
ret = ota_download_image_header(ctx, ota_param.url, url_len, ota_param.len);
OTA_LOG_I("image header magic:0x%x ret:%d\n", ctx->header.image_info->image_magic, ret);
if (ret < 0) {
goto EXIT;
}
ota_param.upg_magic = ctx->header.image_info->image_magic;
#ifdef OTA_CONFIG_LOCAL_RSA
OTA_LOG_I("image sign magic:0x%x\n", ctx->header.sign_info->encrypto_magic);
if (ctx->header.sign_info->encrypto_magic == 0xAABBCCDD) {
char tmp_buf[65];
int result = 0;
memset(tmp_buf, 0x00, sizeof(tmp_buf));
memcpy(ota_param.sign, ctx->header.sign_info->signature, sizeof(ota_param.sign));
ota_param.hash_type = OTA_SHA256;
result = ota_hex2str(tmp_buf, (const unsigned char *)ctx->header.sign_info->hash, sizeof(tmp_buf), sizeof(ctx->header.sign_info->hash));
if (result >= 0) {
memcpy(ota_param.hash, tmp_buf, sizeof(tmp_buf));
} else {
OTA_LOG_E("sign info cpy err.");
ret = OTA_DOWNLOAD_HEAD_FAIL;
goto EXIT;
}
} else {
OTA_LOG_E("sign info err.");
ret = OTA_DOWNLOAD_HEAD_FAIL;
goto EXIT;
}
#endif
}
/* init ota partition */
ret = ota_int(&ota_param);
if (ret < 0) {
ret = OTA_INIT_FAIL;
goto EXIT;
}
OTA_LOG_I("ota init over\n");
/* download start */
ret = ota_download_start(ota_param.url, url_len, ctx->report_func.report_status_cb,
ctx->report_func.param);
if (ret < 0) {
goto EXIT;
}
/* verify image */
ret = ota_verify(&ota_param);
if (ret < 0) {
goto EXIT;
}
EXIT:
OTA_LOG_I("Download complete, rebooting ret:%d.\n", ret);
if (ret < 0) {
ota_param.upg_status = ret;
if ((ctx != NULL) && (ctx->report_func.report_status_cb != NULL)) {
ctx->report_func.report_status_cb(ctx->report_func.param, ret);
}
ret = ota_clear();
if (ret < 0) {
OTA_LOG_E("clear ota failed\n");
}
ota_msleep(3000); /*give same time to sync err msg to cloud*/
} else {
ota_param.crc = 0;
ret = ota_hal_boot(&ota_param);
if (ret < 0) {
if ((ctx != NULL) && (ctx->report_func.report_status_cb != NULL)) {
ctx->report_func.report_status_cb(ctx->report_func.param, ret);
}
}
}
if (ctx->header.image_info != NULL) {
ota_free(ctx->header.image_info);
ctx->header.image_info = NULL;
}
if (ctx->header.sign_info != NULL) {
ota_free(ctx->header.sign_info);
ctx->header.sign_info = NULL;
}
#ifdef AOS_COMP_PWRMGMT
aos_pwrmgmt_lowpower_resume(PWRMGMT_OTA);
#endif
if (ctx->on_boot != NULL) {
ctx->on_boot(&ota_param);
} else {
if (ota_param.upg_flag != OTA_UPGRADE_DIFF) {
ret = ota_hal_reboot_bank();
}
ota_reboot();
}
ota_thread_destroy(NULL);
return ret;
}
int ota_register_boot_cb(ota_service_t *ctx, void *cb, void *param)
{
int ret = OTA_CUSTOM_CALLBAK_FAIL;
if (ctx != NULL) {
ret = 0;
ctx->on_boot = cb;
}
return ret;
}
int ota_register_trigger_msg_cb(ota_service_t *ctx, void *cb, void *param)
{
int ret = OTA_CUSTOM_CALLBAK_FAIL;
if (ctx != NULL) {
ret = 0;
ctx->ota_triggered_func.triggered_ota_cb = cb;
ctx->ota_triggered_func.param = param;
}
return ret;
}
int ota_register_report_percent_cb(ota_service_t *ctx, void *cb, void *param)
{
int ret = OTA_CUSTOM_CALLBAK_FAIL;
if (ctx != NULL) {
ret = 0;
ctx->report_func.report_status_cb = cb;
ctx->report_func.param = param;
}
return ret;
}
int ota_register_feedback_msg_cb(ota_service_t *ctx, void *cb, void *param)
{
int ret = OTA_CUSTOM_CALLBAK_FAIL;
if (ctx != NULL) {
ret = 0;
ctx->feedback_func.on_user_event_cb = cb;
ctx->feedback_func.param = param;
}
return ret;
}
int ota_register_module_store(ota_service_t *ctx, ota_store_module_info_t *queue, int queue_len)
{
int ret = OTA_CUSTOM_CALLBAK_FAIL;
if ((queue != NULL) && (ctx != NULL)) {
ctx->module_queue_ptr = queue;
ctx->module_numb = queue_len;
ret = 0;
}
return ret;
}
int ota_set_module_information(ota_service_t *ctx, char *module_name,
char *store_path, int module_type)
{
int ret = OTA_CUSTOM_CALLBAK_FAIL;
int module_name_len = 0;
int store_path_len = 0;
int i = 0;
if ((ctx == NULL) || (module_name == NULL) || (store_path == NULL)) {
OTA_LOG_E("store module info input param err!");
return ret;
}
if (ctx->module_queue_ptr == NULL) {
OTA_LOG_E("store module need init, ptr is null!");
return ret;
}
module_name_len = strlen(module_name);
store_path_len = strlen(store_path);
if ((module_name_len <= sizeof(ctx->module_queue_ptr[0].module_name)) &&
(store_path_len <= sizeof(ctx->module_queue_ptr[0].store_path))) {
for (i = 0; i < ctx->module_numb; i++) {
if (ctx->module_queue_ptr[i].module_type == 0) {
strncpy(ctx->module_queue_ptr[i].module_name, module_name, module_name_len);
strncpy(ctx->module_queue_ptr[i].store_path, store_path, store_path_len);
ctx->module_queue_ptr[i].module_type = module_type;
ret = 0;
break;
}
}
if (i >= ctx->module_numb) {
OTA_LOG_E("module buf is full!");
}
}
return ret;
}
int ota_get_module_information(ota_service_t *ctx, char *module_name, ota_store_module_info_t *module_info)
{
int ret = OTA_CUSTOM_CALLBAK_FAIL;
int module_name_len = 0;
int i = 0;
if ((ctx == NULL) || (module_info == NULL) || (module_name == NULL)) {
OTA_LOG_E("store module info input param err!");
return ret;
}
if (ctx->module_queue_ptr == NULL) {
OTA_LOG_E("store module need init, ptr is null!");
return ret;
}
module_name_len = strlen(module_name);
if (module_name_len <= sizeof(ctx->module_queue_ptr[0].module_name)) {
for (i = 0; i < ctx->module_numb; i++) {
if (strncmp(module_name, ctx->module_queue_ptr[i].module_name, module_name_len) == 0) {
strncpy(module_info->module_name, module_name, strlen(module_name));
strncpy(module_info->store_path, ctx->module_queue_ptr[i].store_path,
strlen(ctx->module_queue_ptr[i].store_path));
module_info->module_type = ctx->module_queue_ptr[i].module_type;
ret = 0;
break;
}
}
if (i >= ctx->module_numb) {
OTA_LOG_E("module buf is full!");
}
}
return ret;
}
/**
* ota_service_init OTA service init
*
* @param[in] ota_service_t *ctx OTA service context
*
* @return OTA_SUCCESS OTA service init success.
* @return OTA_INIT_FAIL OTA service init fail.
*/
int ota_service_init(ota_service_t *ctx)
{
int ret = 0;
if (ctx == NULL) {
OTA_LOG_E("input ctx is null!");
ret = OTA_INIT_FAIL;
goto EXIT;
}
ctx->ota_process = OTA_PROCESS_NORMAL;
if (ctx->report_func.report_status_cb == NULL) {
OTA_LOG_I("register default status cb");
ota_register_report_percent_cb(ctx, (void *)ota_transport_status, (void *)ctx);
}
ret = ota_transport_upgrade(ctx);
if (ret < 0) {
OTA_LOG_E("transport upgrade sub failed!");
goto EXIT;
}
ret = ota_transport_inform_otaver(ctx);
if (ret < 0) {
OTA_LOG_E("infor otaver failed!");
goto EXIT;
}
if (ctx->dev_type == 0) {
ret = ota_hal_rollback();
if (ret < 0) {
ret = OTA_INIT_FAIL;
goto EXIT;
}
}
OTA_LOG_I("ota init success, ret:%d", ret);
return ret;
EXIT:
OTA_LOG_E("ota init fail, ret:%d", ret);
return ret;
}
/**
* ota_service_param_reset OTA service deinit
*
* @param[in] ota_service_t *ctx OTA service context
*
* @return NULL
*/
void ota_service_param_reset(ota_service_t *ctx)
{
ota_set_upgrade_status(0);
if (ctx != NULL) {
ctx->report_func.report_status_cb = NULL;
ctx->report_func.param = NULL;
ctx->feedback_func.on_user_event_cb = NULL;
ctx->feedback_func.param = NULL;
ctx->mqtt_client = NULL;
ctx->ota_triggered_func.param = NULL;
ctx->ota_triggered_func.triggered_ota_cb = NULL;
ctx->on_boot = NULL;
ctx->module_queue_ptr = NULL;
ctx->module_numb = 0;
ctx->ota_process = 0;
memset(ctx->pk, 0, sizeof(ctx->pk));
memset(ctx->dn, 0, sizeof(ctx->dn));
memset(ctx->ds, 0, sizeof(ctx->ds));
memset(ctx->ps, 0, sizeof(ctx->ps));
memset(ctx->module_name, 0, sizeof(ctx->module_name));
} else {
OTA_LOG_E("param reset input ctx is null.");
}
}
| YifuLiu/AliOS-Things | components/ota/ota_agent/ota_service.c | C | apache-2.0 | 13,160 |
/*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#include <string.h>
#include <cJSON.h>
#include <stdlib.h>
#include "ota_log.h"
#include "ota_hal.h"
#include "ota_import.h"
#include "ota_hal_os.h"
#include "ota_hal_trans.h"
#include "ota_agent.h"
/**
* ota_sevice_parse_msg OTA parse download info from cloud
*
* @param[in] ota_service_t *ctx service manager.
* char *json transport message from Cloud.
*
* @return OTA_TRANSPORT_FAIL transport errno.
*/
int ota_sevice_parse_msg(ota_service_t *ctx, const char *json)
{
int ret = 0;
int is_get_module = 0;
cJSON *root = NULL;
ota_boot_param_t ota_param = {0};
root = cJSON_Parse(json);
if (NULL == root || NULL == ctx) {
ret = OTA_TRANSPORT_PAR_FAIL;
OTA_LOG_E("parse msg param is null");
return ret;
} else {
/* recover the process type */
cJSON *cmd = cJSON_GetObjectItem(root, "cmd");
if (NULL == cmd) {
ctx->ota_process = OTA_PROCESS_NORMAL;
}
cJSON *message = cJSON_GetObjectItem(root, "message");
if (NULL == message) {
ret = OTA_MESSAGE_PAR_FAIL;
goto EXIT;
}
if ((strncmp(message->valuestring, "success", strlen("success")))) {
ret = OTA_SUCCESS_PAR_FAIL;
goto EXIT;
}
cJSON *json_obj = cJSON_GetObjectItem(root, "data");
if (NULL == json_obj) {
ret = OTA_DATA_PAR_FAIL;
goto EXIT;
}
cJSON *url = cJSON_GetObjectItem(json_obj, "url");
if (NULL == url) {
ret = OTA_URL_PAR_FAIL;
goto EXIT;
}
strncpy(ota_param.url, url->valuestring, OTA_URL_LEN - 1);
ota_param.url[sizeof(ota_param.url) - 1] = 0;
cJSON *submodule = cJSON_GetObjectItem(json_obj, "module");
if (NULL != submodule) {
is_get_module = 1;
strncpy(ctx->module_name, submodule->valuestring, sizeof(ctx->module_name) - 1);
OTA_LOG_I("submode = %s\r\n", submodule->valuestring);
}
cJSON *version = cJSON_GetObjectItem(json_obj, "version");
if (NULL == version) {
ret = OTA_VER_PAR_FAIL;
goto EXIT;
}
strncpy(ota_param.ver, version->valuestring, sizeof(ota_param.ver));
ota_param.ver[sizeof(ota_param.ver) - 1] = 0;
cJSON *signMethod = cJSON_GetObjectItem(json_obj, "signMethod");
if (signMethod != NULL) {
memset(ota_param.hash, 0x00, OTA_HASH_LEN);
ret = ota_to_capital(signMethod->valuestring, strlen(signMethod->valuestring));
if (ret != 0) {
ret = OTA_VER_PAR_FAIL;
goto EXIT;
}
if (0 == strncmp(signMethod->valuestring, "MD5", strlen("MD5"))) {
cJSON *md5 = cJSON_GetObjectItem(json_obj, "sign");
if (NULL == md5) {
ret = OTA_MD5_PAR_FAIL;
goto EXIT;
}
ota_param.hash_type = OTA_MD5;
strncpy(ota_param.hash, md5->valuestring, OTA_HASH_LEN - 1);
ret = ota_to_capital(ota_param.hash, strlen(ota_param.hash));
if (ret != 0) {
ret = OTA_VER_PAR_FAIL;
goto EXIT;
}
} else if (0 == strncmp(signMethod->valuestring, "SHA256", strlen("SHA256"))) {
cJSON *sha256 = cJSON_GetObjectItem(json_obj, "sign");
if (NULL == sha256) {
ret = OTA_SHA256_PAR_FAIL;
goto EXIT;
}
ota_param.hash_type = OTA_SHA256;
strncpy(ota_param.hash, sha256->valuestring, OTA_HASH_LEN - 1);
ret = ota_to_capital(ota_param.hash, strlen(ota_param.hash));
if (ret != 0) {
ret = OTA_VER_PAR_FAIL;
goto EXIT;
}
} else {
ret = OTA_HASH_PAR_FAIL;
goto EXIT;
}
} else { /* old protocol*/
memset(ota_param.hash, 0x00, OTA_HASH_LEN);
cJSON *md5 = cJSON_GetObjectItem(json_obj, "md5");
if (NULL == md5) {
ret = OTA_MD5_PAR_FAIL;
goto EXIT;
}
ota_param.hash_type = OTA_MD5;
strncpy(ota_param.hash, md5->valuestring, OTA_HASH_LEN - 1);
ret = ota_to_capital(ota_param.hash, strlen(ota_param.hash));
if (ret != 0) {
ret = OTA_VER_PAR_FAIL;
goto EXIT;
}
}
cJSON *size = cJSON_GetObjectItem(json_obj, "size");
if (NULL == size) {
ret = OTA_SIZE_PAR_FAIL;
goto EXIT;
}
ota_param.len = size->valueint;
cJSON *digestSign = cJSON_GetObjectItem(json_obj, "digestsign");
if (digestSign != NULL) {
unsigned int sign_len = OTA_SIGN_LEN;
memset(ota_param.sign, 0x00, OTA_SIGN_LEN);
if (ota_base64_decode((const unsigned char *)digestSign->valuestring, strlen(digestSign->valuestring), (unsigned char*)ota_param.sign, &sign_len) != 0) {
ret = OTA_SIGN_PAR_FAIL;
goto EXIT;
}
}
}
EXIT:
if (root != NULL) {
cJSON_Delete(root);
root = NULL;
}
OTA_LOG_I("Parse ota version:%s url:%s ret:%d\n", ota_param.ver, ota_param.url, ret);
if (ret < 0) {
ret = OTA_TRANSPORT_PAR_FAIL;
if (ctx->report_func.report_status_cb != NULL) {
ctx->report_func.report_status_cb(ctx->report_func.param, ret);
}
} else {
if (ctx->report_func.report_status_cb != NULL) {
ctx->report_func.report_status_cb(ctx->report_func.param, 1);
}
ota_param.upg_flag = 0x00;
if (ctx->dev_type == 0) {
if (is_get_module == 0) {
strncpy(ctx->module_name, "default", 7);
}
}
OTA_LOG_I("upg_flag = %04x", ota_param.upg_flag);
ota_param.upg_status = OTA_TRANSPORT;
ret = ota_update_parameter(&ota_param);
if (ret != 0) {
OTA_LOG_I("ota param err.\n");
if (ctx->report_func.report_status_cb != NULL) {
ctx->report_func.report_status_cb(ctx->report_func.param, OTA_TRANSPORT_PAR_FAIL);
}
}
if (ctx->ota_triggered_func.triggered_ota_cb != NULL) {
ctx->ota_triggered_func.triggered_ota_cb(ctx, ota_param.ver, ctx->module_name, ctx->ota_triggered_func.param);
}
}
return ret;
}
/**
* ota_mqtt_publish message to Cloud
*
* @param[in] mqtt_client mqtt client ptr
* @param[in] name topic name
* @param[in] msg message content
* @param[in] pk product key
* @param[in] dn device name
*
* @return OTA_SUCCESS OTA success.
* @return OTA_TRANSPORT_INT_FAIL OTA transport init fail.
* @return OTA_TRANSPORT_PAR_FAIL OTA transport parse fail.
* @return OTA_TRANSPORT_VER_FAIL OTA transport verion is too old.
*/
static int ota_mqtt_publish(void *mqtt_client, const char *name, char *msg, char *pk, char *dn)
{
int ret = 0;
char topic[OTA_MSG_LEN] = {0};
if (name == NULL || msg == NULL || pk == NULL || dn == NULL) {
return OTA_TRANSPORT_INT_FAIL;
}
ret = ota_snprintf(topic, OTA_MSG_LEN - 1, "/ota/device/%s/%s/%s", name, pk, dn);
if (ret < 0) {
return OTA_TRANSPORT_INT_FAIL;
}
OTA_LOG_I("Public topic:%s msg:%s", topic, msg);
ret = ota_hal_mqtt_publish(mqtt_client, topic, 1, (void *)msg, strlen(msg) + 1);
if (ret < 0) {
return OTA_TRANSPORT_INT_FAIL;
}
return ret;
}
/**
* ota_mqtt_sub_cb upgrade callback
*
* @param[in] pctx ota context
* @param[in] pclient mqtt pclient
* @param[in] msg mqtt message
*
* @return void
*/
static void ota_mqtt_sub_cb(void *mqtt_client, void *msg, void *pctx)
{
char *payload = NULL;
ota_service_t *ctx = (ota_service_t *)pctx;
if ((msg == NULL) && (ctx == NULL)) {
OTA_LOG_E("mqtt sub param err!");
return;
}
if (ota_hal_mqtt_type_is_pub(msg)) {
payload = (char *)ota_hal_mqtt_get_payload(msg);
if (payload != NULL) {
ota_sevice_parse_msg(ctx, payload);
}
} else {
OTA_LOG_E("mqtt receive err msg type!");
}
}
/**
* ota_transport_inform OTA inform version to cloud.
*
* @param[in] void *mqttclient mqtt client ptr
* @param[in] char *pk product key value
* @param[in] char *dn device name
* @param[in] char *module_name want to report module name, when module_name == NULL, report default module ver
* @param[in] char *ver version string
*
* @return OTA_SUCCESS OTA success.
* @return OTA_TRANSPORT_INT_FAIL OTA transport init fail.
* @return OTA_TRANSPORT_PAR_FAIL OTA transport parse fail.
* @return OTA_TRANSPORT_VER_FAIL OTA transport verion is too old.
*/
int ota_transport_inform(void *mqttclient, char *pk, char *dn, char *module_name, char *ver)
{
int ret = 0;
char msg[OTA_MSG_LEN] = {0};
if ((mqttclient == NULL) || (ver == NULL) || (pk == NULL) ||
(dn == NULL) || (module_name == NULL)) {
OTA_LOG_E("inform version input param err!");
goto OTA_TRANS_INFOR_OVER;
}
if (strncmp(module_name, "default", strlen("default")) == 0) {
ret = ota_snprintf(msg, OTA_MSG_LEN - 1, "{\"id\":%d,\"params\":{\"version\":\"%s\"}}", 0, ver);
} else {
ret = ota_snprintf(msg, OTA_MSG_LEN - 1, "{\"id\":%d,\"params\":{\"version\":\"%s\",\"module\":\"%s\"}}", 0, ver, module_name);
}
if (ret < 0) {
OTA_LOG_E("inform version pack msg err!");
goto OTA_TRANS_INFOR_OVER;
}
ret = ota_mqtt_publish(mqttclient, "inform", msg, pk, dn);
OTA_TRANS_INFOR_OVER:
if (ret < 0) {
OTA_LOG_E("inform version failed!");
}
return ret;
}
int ota_transport_inform_otaver(ota_service_t *ctx)
{
int ret = 0;
char topic[OTA_MSG_LEN] = {0};
char msg[OTA_MSG_LEN] = {0};
char keyver[20] = "SYS_OTA_ID";
char attver[64] = {0};
if (ctx == NULL) {
return OTA_TRANSPORT_PAR_FAIL;
}
ret = ota_snprintf(topic, OTA_MSG_LEN - 1, "/sys/%s/%s/thing/deviceinfo/update", ctx->pk, ctx->dn);
if (ret < 0) {
return OTA_TRANSPORT_PAR_FAIL;
}
ret = ota_snprintf(attver, sizeof(attver) - 1, "HOTA-%s-%s-%s-%s", OTA_VERSION, OTA_TRANSTYPE, OTA_OS_TYPE, OTA_BOARD_TYPE);
if (ret < 0) {
return OTA_TRANSPORT_PAR_FAIL;
}
OTA_LOG_I("Public topic:%s", topic);
ret = ota_snprintf(msg, OTA_MSG_LEN - 1, "{\"id\":\"%d\",\"version\":\"1.0\",\"params\":[{\"attrKey\":\"%s\",\"attrValue\":\"%s\"}],\"method\":\"thing.deviceinfo.update\"}",
0, keyver, attver);
if (ret < 0) {
return OTA_TRANSPORT_PAR_FAIL;
}
OTA_LOG_I("Public msg:%s", msg);
ret = ota_hal_mqtt_publish(ctx->mqtt_client, topic, 1, (void *)msg, strlen(msg) + 1);
if (ret < 0) {
return OTA_TRANSPORT_INT_FAIL;
}
return ret;
}
/**
* ota_transport_upgrade OTA subcribe message from Cloud.
*
* @param[in] ota_service_t *ctx ctx ota service context
*
* @return OTA_SUCCESS OTA success.
* @return OTA_TRANSPORT_INT_FAIL OTA transport init fail.
* @return OTA_TRANSPORT_PAR_FAIL OTA transport parse fail.
* @return OTA_TRANSPORT_VER_FAIL OTA transport verion is too old.
*/
int ota_transport_upgrade(ota_service_t *ctx)
{
int ret = OTA_TRANSPORT_INT_FAIL;
char topic[OTA_MSG_LEN] = {0};
if (ctx == NULL) {
return ret;
}
ret = ota_snprintf(topic, OTA_MSG_LEN - 1, "/ota/device/%s/%s/%s", "upgrade", ctx->pk, ctx->dn);
if (ret < 0) {
ret = OTA_TRANSPORT_INT_FAIL;
} else {
ret = ota_hal_mqtt_subscribe(ctx->mqtt_client, topic, ota_mqtt_sub_cb, ctx);
}
return ret;
}
/**
* ota_transport_status OTA report status to Cloud
*
* @param[in] void *param param ota service context
* @param[in] status [1-100] percent, [<0] error no.
*
* @return OTA_SUCCESS OTA success.
* @return OTA_TRANSPORT_INT_FAIL OTA transport init fail.
* @return OTA_TRANSPORT_PAR_FAIL OTA transport parse fail.
* @return OTA_TRANSPORT_VER_FAIL OTA transport verion is too old.
*/
int ota_transport_status(void *param, int status)
{
int ret = OTA_TRANSPORT_INT_FAIL;
ota_service_t *ctx = NULL;
char msg[OTA_MSG_LEN] = {0};
char *err_str = "";
int tmp_status = 0;
if (param == NULL) {
OTA_LOG_E("report status param is null!");
return ret;
}
ctx = (ota_service_t *)param;
tmp_status = status;
if (status < 0) {
switch (status) {
case OTA_INIT_FAIL:
err_str = "OTA init failed";
tmp_status = OTA_REPORT_UPGRADE_ERR;
break;
case OTA_TRANSPORT_INT_FAIL:
err_str = "OTA transport init failed";
tmp_status = OTA_REPORT_UPGRADE_ERR;
break;
case OTA_TRANSPORT_VER_FAIL:
err_str = "OTA transport verion is too old";
tmp_status = OTA_REPORT_UPGRADE_ERR;
break;
case OTA_TRANSPORT_PAR_FAIL:
err_str = "OTA transport parse failed";
tmp_status = OTA_REPORT_UPGRADE_ERR;
break;
case OTA_DOWNLOAD_INIT_FAIL:
err_str = "OTA download init failed";
tmp_status = OTA_REPORT_DOWNLOAD_ERR;
break;
case OTA_DOWNLOAD_HEAD_FAIL:
err_str = "OTA download header failed";
tmp_status = OTA_REPORT_DOWNLOAD_ERR;
break;
case OTA_DOWNLOAD_CON_FAIL:
err_str = "OTA download connect failed";
tmp_status = OTA_REPORT_DOWNLOAD_ERR;
break;
case OTA_DOWNLOAD_REQ_FAIL:
err_str = "OTA download request failed";
tmp_status = OTA_REPORT_DOWNLOAD_ERR;
break;
case OTA_DOWNLOAD_RECV_FAIL:
err_str = "OTA download receive failed";
tmp_status = OTA_REPORT_DOWNLOAD_ERR;
break;
case OTA_VERIFY_MD5_FAIL:
err_str = "OTA verfiy MD5 failed";
tmp_status = OTA_REPORT_VERIFY_ERR;
break;
case OTA_VERIFY_SHA2_FAIL:
err_str = "OTA verfiy SHA256 failed";
tmp_status = OTA_REPORT_VERIFY_ERR;
break;
case OTA_VERIFY_RSA_FAIL:
err_str = "OTA verfiy RSA failed";
tmp_status = OTA_REPORT_VERIFY_ERR;
break;
case OTA_VERIFY_IMAGE_FAIL:
err_str = "OTA verfiy image failed";
tmp_status = OTA_REPORT_VERIFY_ERR;
break;
case OTA_UPGRADE_WRITE_FAIL:
err_str = "OTA upgrade write failed";
tmp_status = OTA_REPORT_BURN_ERR;
break;
case OTA_UPGRADE_FW_SIZE_FAIL:
err_str = "OTA upgrade FW too big";
tmp_status = OTA_REPORT_BURN_ERR;
break;
case OTA_CUSTOM_CALLBAK_FAIL:
err_str = "OTA register callback failed";
tmp_status = OTA_REPORT_BURN_ERR;
break;
case OTA_MCU_INIT_FAIL:
err_str = "OTA MCU init failed";
tmp_status = OTA_REPORT_BURN_ERR;
break;
case OTA_MCU_VERSION_FAIL:
err_str = "OTA MCU init failed";
tmp_status = OTA_REPORT_BURN_ERR;
break;
case OTA_MCU_NOT_READY:
err_str = "OTA MCU not ready";
tmp_status = OTA_REPORT_BURN_ERR;
break;
case OTA_MCU_REBOOT_FAIL:
err_str = "OTA MCU fail to reboot";
tmp_status = OTA_REPORT_BURN_ERR;
break;
case OTA_MCU_HEADER_FAIL:
err_str = "OTA MCU header error";
tmp_status = OTA_REPORT_BURN_ERR;
break;
case OTA_MCU_UPGRADE_FAIL:
err_str = "OTA MCU upgrade fail";
tmp_status = OTA_REPORT_BURN_ERR;
break;
case OTA_INVALID_PARAMETER:
err_str = "OTA invalid parameter";
tmp_status = OTA_REPORT_BURN_ERR;
break;
default:
err_str = "OTA undefined failed";
tmp_status = OTA_REPORT_UPGRADE_ERR;
break;
}
}
if (strncmp(ctx->module_name, "default", strlen("default")) == 0) {
ret = ota_snprintf(msg, OTA_MSG_LEN - 1, "{\"id\":%d,\"params\":{\"step\": \"%d\",\"desc\":\"%s\"}}", 1, tmp_status, err_str);
} else {
ret = ota_snprintf(msg, OTA_MSG_LEN - 1, "{\"id\":%d,\"params\":{\"step\": \"%d\",\"desc\":\"%s\",\"module\":\"%s\"}}", 1, tmp_status, err_str, ctx->module_name);
}
if (ret < 0) {
return OTA_TRANSPORT_INT_FAIL;
}
ret = ota_mqtt_publish(ctx->mqtt_client, "progress", msg, ctx->pk, ctx->dn);
if (ret < 0) {
OTA_LOG_E("report status failed!");
return OTA_TRANSPORT_INT_FAIL;
}
return ret;
}
| YifuLiu/AliOS-Things | components/ota/ota_agent/transport/ota_transport_mqtt.c | C | apache-2.0 | 17,649 |
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#include <string.h>
#include "ota_log.h"
#include "ota_import.h"
#include "ota_hal_digest.h"
#include "ota_hal_os.h"
#define OTA_BUF_VERIFY 512
int ota_hash_init(ota_hash_ctx_t *ctx, unsigned char type)
{
int ret = 0;
if (ctx == NULL) {
OTA_LOG_E("Invalid hash param");
return OTA_INVALID_PARAMETER;
}
ctx->hash_method = type;
switch (type) {
case OTA_SHA256:
ota_sha256_init(&ctx->sha256_ctx);
ota_sha256_starts(&ctx->sha256_ctx, 0);
break;
case OTA_MD5:
ota_md5_init(&ctx->md5_ctx);
ota_md5_starts(&ctx->md5_ctx);
break;
default:
ret = OTA_INVALID_PARAMETER;
break;
}
return ret;
}
int ota_hash_update(ota_hash_ctx_t *ctx, const unsigned char *buf, unsigned int len)
{
int ret = 0;
if (ctx == NULL) {
OTA_LOG_E("Invalid hash param");
return OTA_INVALID_PARAMETER;
}
switch (ctx->hash_method) {
case OTA_SHA256:
ota_sha256_update(&ctx->sha256_ctx, buf, len);
break;
case OTA_MD5:
ota_md5_update(&ctx->md5_ctx, buf, len);
break;
default:
ret = OTA_INVALID_PARAMETER;
break;
}
return ret;
}
int ota_hash_final(ota_hash_ctx_t *ctx, unsigned char *dgst)
{
int ret = 0;
if (ctx == NULL) {
OTA_LOG_E("Invalid hash param");
return OTA_INVALID_PARAMETER;
}
switch (ctx->hash_method) {
case OTA_SHA256:
ota_sha256_finish(&ctx->sha256_ctx, dgst);
ota_sha256_free(&ctx->sha256_ctx);
break;
case OTA_MD5:
ota_md5_finish(&ctx->md5_ctx, dgst);
ota_md5_free(&ctx->md5_ctx);
break;
default:
ret = OTA_INVALID_PARAMETER;
break;
}
return ret;
}
int ota_check_hash(unsigned char type, char *src, char *dst)
{
int ret = 0;
switch (type) {
case OTA_SHA256:
OTA_LOG_I("SHA256 src:%s dst:%s", src, dst);
if (strncmp(dst, src, 64) != 0) {
ret = OTA_VERIFY_SHA2_FAIL;
}
break;
case OTA_MD5:
OTA_LOG_I("md5 src:%s dst:%s", src, dst);
if (strncmp(dst, src, 32) != 0) {
ret = OTA_VERIFY_MD5_FAIL;
}
break;
default:
ret = OTA_INVALID_PARAMETER;
break;
}
return ret;
}
int ota_check_image_hash(unsigned int image_len, unsigned char type, char *hash_value, int len)
{
int ret = 0;
char *rd_buf = NULL;
unsigned int read_size = 0;
unsigned int offset = 0;
ota_hash_ctx_t ctx = {0};
ota_crc16_ctx crc_ctx = {0};
unsigned short crc_result = 0;
if (NULL == hash_value) {
ret = OTA_VERIFY_IMAGE_FAIL;
goto EXIT;
}
switch (type) {
case OTA_SHA256:
if (len < 32) {
ret = OTA_VERIFY_SHA2_FAIL;
goto EXIT;
}
break;
case OTA_MD5:
if (len < 16) {
ret = OTA_VERIFY_MD5_FAIL;
goto EXIT;
}
break;
default:
ret = OTA_INVALID_PARAMETER;
goto EXIT;
}
rd_buf = ota_malloc(OTA_BUF_VERIFY);
if (rd_buf == NULL) {
ret = OTA_VERIFY_IMAGE_FAIL;
goto EXIT;
}
ret = ota_hash_init(&ctx, type);
if (ret != 0) {
goto EXIT;
}
ota_crc16_init(&crc_ctx);
while (offset < image_len) {
unsigned int off = offset;
(image_len - offset >= OTA_BUF_VERIFY) ? (read_size = OTA_BUF_VERIFY) : (read_size = image_len - offset);
ret = ota_read(&off, rd_buf, read_size);
if (ret < 0) {
ret = OTA_VERIFY_IMAGE_FAIL;
goto EXIT;
}
ret = ota_hash_update(&ctx, (const unsigned char *)rd_buf, read_size);
if (ret != 0) {
goto EXIT;
}
ota_crc16_update(&crc_ctx, (void *)rd_buf, read_size);
offset += read_size;
ota_msleep(5);
}
memset(hash_value, 0x00, len);
ota_crc16_final(&crc_ctx, &crc_result);
OTA_LOG_I("check image_crc16 = %x\r\n", crc_result);
ret = ota_hash_final(&ctx, (unsigned char *)hash_value);
EXIT:
if (NULL != rd_buf) {
ota_free(rd_buf);
rd_buf = NULL;
}
if (ret != 0) {
OTA_LOG_E("check image hash:%d", ret);
}
return ret;
}
int ota_get_image_info(unsigned int image_size, ota_image_info_t *tmp_info)
{
int ret = -1;
unsigned int off_set = 0;
if ((tmp_info == NULL) || (image_size <= sizeof(ota_image_info_t))) {
OTA_LOG_E("input param err for getting image info!");
return ret;
}
off_set = image_size - sizeof(ota_image_info_t);
OTA_LOG_I("bin size:%d off:%d\r\n", image_size, off_set);
ret = ota_read(&off_set, (char *)tmp_info, sizeof(ota_image_info_t));
if (ret < 0) {
OTA_LOG_E("read image info err!");
}
OTA_LOG_I("magic:0x%04x, size:%d, crc16:0x%02x\r\n", tmp_info->image_magic, tmp_info->image_size, tmp_info->image_crc16);
return ret;
}
int ota_check_image(unsigned int size)
{
int ret = 0;
char image_md5[16] = {0};
char download_md5[33] = {0};
char cal_md5[33] = {0};
ota_image_info_t image_info = {0};
ret = ota_get_image_info(size, &image_info);
if (ret < 0) {
ret = OTA_VERIFY_IMAGE_FAIL;
goto EXIT;
}
ret = ota_hex2str(download_md5, (const unsigned char *)image_info.image_md5, sizeof(download_md5), sizeof(image_info.image_md5));
if (ret != 0) {
ret = OTA_VERIFY_IMAGE_FAIL;
goto EXIT;
}
OTA_LOG_I("magic:0x%04x size:%d md5:%s crc16:0x%02x", image_info.image_magic, image_info.image_size, download_md5, image_info.image_crc16);
if ((image_info.image_magic != OTA_BIN_MAGIC_APP) &&
(image_info.image_magic != OTA_BIN_MAGIC_KERNEL) &&
(image_info.image_magic != OTA_BIN_MAGIC_ALL) &&
(image_info.image_magic != OTA_BIN_MAGIC_MCU) &&
(image_info.image_magic != OTA_BIN_MAGIC_FS)) {
ret = OTA_INVALID_PARAMETER;
goto EXIT;
}
if (image_info.image_size == 0) {
ret = OTA_VERIFY_IMAGE_FAIL;
goto EXIT;
}
ret = ota_check_image_hash(image_info.image_size, OTA_MD5, image_md5, 16);
if (ret != 0) {
goto EXIT;
}
ret = ota_hex2str(cal_md5, (const unsigned char *)image_md5, sizeof(cal_md5), sizeof(image_md5));
if (ret != 0) {
ret = OTA_VERIFY_IMAGE_FAIL;
goto EXIT;
}
ret = ota_check_hash(OTA_MD5, cal_md5, download_md5);
if (ret != 0) {
goto EXIT;
}
EXIT:
if (ret != 0) {
OTA_LOG_E("ota check_image :%d", ret);
}
return ret;
}
| YifuLiu/AliOS-Things | components/ota/ota_agent/verify/ota_verify_hash.c | C | apache-2.0 | 6,980 |
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#include "string.h"
#include "ota_log.h"
#include "ota_import.h"
#include "ota_hal_digest.h"
#include "ota_hal_os.h"
static char ota_get_sign_hash_method(void)
{
return OTA_SHA256;
}
static int ota_verify_rsa_hash(unsigned char *src, int src_len, unsigned char *dig, unsigned char type)
{
int ret = 0;
ota_hash_ctx_t ctx = {0};
if (src == NULL || dig == NULL) {
ret = OTA_VERIFY_RSA_FAIL;
return ret;
}
ret = ota_hash_init(&ctx, type);
if (ret != 0) {
ret = OTA_VERIFY_RSA_FAIL;
return ret;
}
ret = ota_hash_update(&ctx, (const unsigned char *)src, src_len);
if (ret != 0) {
ret = OTA_VERIFY_RSA_FAIL;
return ret;
}
ret = ota_hash_final(&ctx, dig);
if (ret != 0) {
ret = OTA_VERIFY_RSA_FAIL;
return ret;
}
return ret;
}
static int ota_verify_rsa_sign(unsigned char *src, int src_len, int rsabitnumb, unsigned char *signature)
{
int ret = 0;
int dig_len = 0;
unsigned char *dig = NULL;
unsigned char hash_method = OTA_HASH_NONE;
unsigned int pubkey_n_size = 0;
unsigned int pubkey_e_size = 0;
const unsigned char *pubkey_n = NULL;
const unsigned char *pubkey_e = NULL;
if ((rsabitnumb < OTA_SIGN_BITNUMB) || (NULL == src) ||
(src_len == 0) || (NULL == signature)) {
ret = OTA_INVALID_PARAMETER;
goto EXIT;
}
pubkey_n = ota_rsa_pubkey_n();
pubkey_e = ota_rsa_pubkey_e();
pubkey_n_size = ota_rsa_pubkey_n_size();
pubkey_e_size = ota_rsa_pubkey_e_size();
if ((pubkey_n_size != (rsabitnumb >> 3)) || (pubkey_e_size != 3)) {
ret = OTA_INVALID_PARAMETER;
goto EXIT;
}
hash_method = ota_get_sign_hash_method();
if (hash_method != OTA_SHA256) {
ret = OTA_INVALID_PARAMETER;
goto EXIT;
}
dig_len = OTA_SHA256_HASH_SIZE;
dig = ota_malloc(dig_len);
if (NULL == dig) {
ret = OTA_INVALID_PARAMETER;
goto EXIT;
}
ret = ota_verify_rsa_hash(src, src_len, dig, hash_method);
if (ret != 0) {
ret = OTA_VERIFY_RSA_FAIL;
goto EXIT;
}
ret = ota_rsa_pubkey_verify(pubkey_n, pubkey_e, pubkey_n_size, pubkey_e_size, dig, dig_len,
signature, rsabitnumb >> 3);
EXIT:
if (NULL != dig) {
ota_free(dig);
dig = NULL;
}
if (ret != 0)
OTA_LOG_E("rsa verify err:%d", ret);
return ret;
}
int ota_verify_rsa(unsigned char *sign_dat, const char *hash_dat, unsigned char type)
{
int ret = OTA_VERIFY_RSA_FAIL;
int src_dat_len = 0;
unsigned char tmp_buf[OTA_SHA256_HASH_SIZE] = {0};
if ((sign_dat != NULL) && (hash_dat != NULL)) {
ret = 0;
if (type == OTA_MD5) {
src_dat_len = OTA_MD5_HASH_SIZE;
} else if (type == OTA_SHA256) {
src_dat_len = OTA_SHA256_HASH_SIZE;
}
if (ret == 0) {
ret = ota_str2hex(hash_dat, (char *)tmp_buf, sizeof(tmp_buf));
if (ret == 0) {
ret = ota_verify_rsa_sign(tmp_buf, src_dat_len, OTA_SIGN_BITNUMB, sign_dat);
}
}
}
OTA_LOG_E("verify rsa ret:%d", ret);
return ret;
}
| YifuLiu/AliOS-Things | components/ota/ota_agent/verify/ota_verify_rsa.c | C | apache-2.0 | 3,409 |
#! /usr/bin/env python
import os, sys, re, struct, getopt
from sys import platform
import array,hashlib,struct
def print_usage():
print("")
print("Usage:" + sys.argv[0])
print(sys.argv[0] + " main_bin mcu_bin offset magic")
print(" [-h | --help] Display usage")
sys.stdout.flush()
def write_file(file_name, gap_szie, data):
if file_name is None:
print 'file_name cannot be none\n'
sys.exit(0)
fp = open(file_name,'ab')
if fp:
fp.write(data)
if gap_szie > 0:
fp.write('\xFF'*gap_szie)
fp.close()
else:
print '%s write fail\n'%(file_name)
def comp_file_md5(input_file, magic_str):
magic = int(magic_str, 16)
output_file = input_file+".ota"
fin = open(input_file, 'rb')
data = fin.read()
fout = open(output_file, 'wb')
fout.write(data)
size = os.path.getsize(input_file)
fout.write(struct.pack('<I', magic))
fout.write(struct.pack('<I', size))
fout.write(hashlib.md5(data).digest())
print("magic:0x%x size:%d md5:%s" %(magic, size, hashlib.md5(data).hexdigest()))
reserve = bytearray([0xFF,0xFF])
fout.write(reserve)
fout.write(reserve)
fin.close()
fout.close()
os.remove(input_file)
os.rename(output_file, input_file)
def main():
try:
opts, args = getopt.getopt(sys.argv[1:], "h", ["help"])
except getopt.GetoptError as err:
print(str(err))
print_usage()
sys.exit(2)
magic = "0xefcdefcd"
if len(args) < 3:
print_usage()
sys.exit(2)
else:
main_file = args[0]
mcu_file = args[1]
offset = int(args[2], 16)
if len(args) > 3:
magic = args[3]
if not os.path.exists(main_file):
print("Input a main file.")
sys.exit(2)
output_file = main_file+"_ota.bin"
if os.path.exists(output_file):
os.remove(output_file)
gap_szie = offset - os.path.getsize(main_file)
fmain = open(main_file, 'rb')
main_data = fmain.read()
fp = open(output_file,'ab')
if fp:
fp.write(main_data)
fmcu = open(mcu_file, 'rb')
mcu_data = fmcu.read()
print("file main:0x%x mcu:0x%x off:0x%x " %(os.path.getsize(main_file), os.path.getsize(mcu_file), offset))
if gap_szie > 0:
fp.write('\xFF'*gap_szie)
if fp:
fp.write(mcu_data)
fp.close()
fmcu.close()
fmain.close()
comp_file_md5(output_file, magic)
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
pass
| YifuLiu/AliOS-Things | components/ota/tools/ota_image_package.py | Python | apache-2.0 | 2,426 |
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include "upack_data_file.h"
#include "ota_log.h"
#include "ota_import.h"
int data_file_unpack(void *pack_file, unsigned int pack_size, void *upack_path)
{
int ret = -1;
int i = 0;
char tmp_file_name[128];
int tmp_file_name_len = 0;
int read_fd = -1;
unsigned int upack_path_len = 0;
unsigned int read_len = 0;
data_file_pack_head_t pack_head;
data_file_infor_t file_info;
if ((pack_file != NULL) &&
(upack_path != NULL) &&
(strlen(upack_path) <= 64)) {
OTA_LOG_E("upack_path = %d\r\n", strlen(upack_path));
memset(tmp_file_name, 0x00, sizeof(tmp_file_name));
memset(&pack_head, 0x00, sizeof(data_file_pack_head_t));
memset(&file_info, 0x00, sizeof(data_file_infor_t));
upack_path_len = strlen(upack_path);
strncpy(tmp_file_name, upack_path, upack_path_len);
if (tmp_file_name[upack_path_len] != '/') {
tmp_file_name[upack_path_len++] = '/';
}
OTA_LOG_I("upack_path = %s\r\n", (char *)upack_path);
read_fd = ota_fopen(pack_file, O_RDONLY);
if (read_fd >= 0) {
read_len = ota_fread(read_fd, &pack_head, sizeof(data_file_pack_head_t));
OTA_LOG_E("read_len = %d\r\n", read_len);
if (read_len != sizeof(data_file_pack_head_t) ||
pack_head.pack_size != pack_size) {
OTA_LOG_E("file: %s is len erro, pack size = %d\r\n", (char *)pack_file, pack_head.pack_size);
} else {
ret = 0;
for (i = 0; i < pack_head.file_numb; i++) {
read_len = ota_fread(read_fd, (void *)&file_info, sizeof(data_file_infor_t));
if (read_len != sizeof(data_file_infor_t)) {
ret = -1;
OTA_LOG_E("file:%d read file info len err\r\n", i);
break;
} else {
tmp_file_name_len = file_info.head_size - sizeof(data_file_infor_t);
if (tmp_file_name_len > sizeof(tmp_file_name) - upack_path_len) {
ret = -1;
OTA_LOG_E("file%d name too long\r\n", i);
break;
} else {
read_len = ota_fread(read_fd, (void *)&tmp_file_name[upack_path_len], tmp_file_name_len);
if (read_len != tmp_file_name_len) {
ret = -1;
OTA_LOG_E("read file%d name err\r\n", i);
break;
} else {
int write_fd = -1;
int tmp_read_len = 0;
int has_read_len = 0;
int tmp_write_len = 0;
char tmp_buf[128];
OTA_LOG_I("file = %s\r\n", tmp_file_name);
write_fd = ota_fopen(tmp_file_name, O_WRONLY | O_CREAT | O_TRUNC);
while (has_read_len < file_info.file_size) {
file_info.file_size - has_read_len > sizeof(tmp_buf) ? (tmp_read_len = sizeof(tmp_buf)) : (tmp_read_len = file_info.file_size - has_read_len);
read_len = ota_fread(read_fd, (void *)tmp_buf, tmp_read_len);
if (read_len != tmp_read_len) {
ota_fclose(write_fd);
write_fd = -1;
OTA_LOG_E("file%d, read file data err\r\n", i);
ret = -1;
break;
} else {
tmp_write_len = ota_fwrite(write_fd, tmp_buf, tmp_read_len);
if (tmp_write_len != tmp_read_len) {
ota_fclose(write_fd);
write_fd = -1;
OTA_LOG_E("file%d, write file failed\r\n", i);
ret = -1;
break;
} else {
has_read_len += tmp_read_len;
}
}
}
memset(&tmp_file_name[upack_path_len], 0x00, sizeof(tmp_file_name) - upack_path_len);
if (ret == 0) {
ota_fclose(write_fd);
write_fd = -1;
OTA_LOG_E("file%d,write suc!\r\n", i);
} else {
OTA_LOG_E("file%d, write err!\r\n", i);
break;
}
}
}
}
}
}
} else {
OTA_LOG_E("pack faile: %s open failed\n", (char *)pack_file);
}
}
if (read_fd >= 0) {
ota_fclose(read_fd);
read_fd = -1;
}
if (ret < 0) {
OTA_LOG_E("unpack failed\n");
}
return ret;
}
| YifuLiu/AliOS-Things | components/ota/tools/upack_data_file.c | C | apache-2.0 | 5,658 |
/** @defgroup upack_data_file
* @{
*
* This is an include file of upack js app.bin interface.
*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#ifndef UPACK_DATA_FILE_H
#define UPACK_DATA_FILE_H
#ifdef __cplusplus
extern "C" {
#endif
typedef struct DATA_FILE_PACK_HEAD {
unsigned short file_numb;
unsigned short pack_ver;
unsigned int pack_size;
} data_file_pack_head_t;
typedef struct DATA_FILE_INFO{
unsigned int head_size;
unsigned int file_size;
char md5_vale[16];
} data_file_infor_t;
/**
* data_file_unpack data file unpack.
*
* @param[in] void *pack_file pack file name
* @param[in] unsigned int pack_size pack file size
* @param[in] void *upack_path unpack file store path
*
* @return 0 upack success.
* @return -1 unpack failed.
*/
int data_file_unpack(void *pack_file, unsigned int pack_size, void *upack_path);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif | YifuLiu/AliOS-Things | components/ota/tools/upack_data_file.h | C | apache-2.0 | 988 |
/*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#include <stddef.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <utime.h>
#include <string.h>
#include "esp_vfs.h"
#define VFS_PATH_MAX 256
static char g_current_working_directory[VFS_PATH_MAX] = "/";
#if ESP_IDF_VERSION <= ESP_IDF_VERSION_VAL(4, 2, 0)
char *getcwd(char *buf, size_t size)
{
if (buf == NULL) {
return NULL;
}
strncpy(buf, g_current_working_directory, strlen(g_current_working_directory) + 1);
return buf;
}
int chdir(const char *path)
{
if ((path == NULL) || (strlen(path) > VFS_PATH_MAX)) {
return -1;
}
memset(g_current_working_directory, 0, sizeof(g_current_working_directory));
strncpy(g_current_working_directory, path, strlen(path) + 1);
return 0;
}
#endif
int statfs(const char *path, struct statfs *buf)
{
int ret;
ret = esp_vfs_statfs(path, buf);
return ret;
}
| YifuLiu/AliOS-Things | components/posix/esp_idf/fs.c | C | apache-2.0 | 925 |
/*
* Copyright (C) 2021 Alibaba Group Holding Limited
*/
#ifndef _SYS_STATFS_H
#define _SYS_STATFS_H
#ifdef __cplusplus
extern "C" {
#endif
struct statfs {
long f_type; /* fs type */
long f_bsize; /* optimized transport block size */
long f_blocks; /* total blocks */
long f_bfree; /* available blocks */
long f_bavail; /* number of blocks that non-super users can acquire */
long f_files; /* total number of file nodes */
long f_ffree; /* available file nodes */
long f_fsid; /* fs id */
long f_namelen; /* max file name length */
};
int statfs(const char *path, struct statfs *buf);
#ifdef __cplusplus
}
#endif
#endif /*_SYS_STATFS_H*/
| YifuLiu/AliOS-Things | components/posix/esp_idf/include/sys/statfs.h | C | apache-2.0 | 698 |
/*
* Copyright (C) 2021 Alibaba Group Holding Limited
*/
#include <stdio.h>
#include <pthread.h>
#if AOS_COMP_CLI
#include "aos/cli.h"
#endif
static int count = 0;
static pthread_mutex_t count_lock = PTHREAD_MUTEX_INITIALIZER;
static int ret_value = 0;
static void *new_thread_func(void *arg)
{
int increase_count = *((int *)arg);
printf("new thread:0x%x, arg:%d\n", pthread_self(), increase_count);
pthread_mutex_lock(&count_lock);
printf("new thread hold the lock.\n");
count += increase_count;
pthread_mutex_unlock(&count_lock);
ret_value = 100;
pthread_exit(&ret_value);
}
static int pthread_example(int argc, char **argv)
{
int ret = 0;
int increase_count;
pthread_t new_thread;
pthread_attr_t attr;
int *retval;
pthread_attr_init(&attr);
pthread_attr_setstacksize(&attr, 1024);
increase_count = 10;
ret = pthread_create(&new_thread, &attr, new_thread_func, &increase_count);
if (ret != 0) {
printf("pthread_create failed, ret:%d\n", ret);
pthread_attr_destroy(&attr);
return -1;
}
pthread_mutex_lock(&count_lock);
printf("Main thread hold the lock.\n");
count++;
pthread_mutex_unlock(&count_lock);
ret = pthread_join(new_thread, (void **)&retval);
if (ret != 0) {
printf("pthread_join return :%d\n", ret);
}
printf("retval:%p, &ret_value:%p\n", retval, &ret_value);
printf("New thread:0x%x exited with vaule: %d\n", new_thread, *retval);
printf("The count is %d\n", count);
if ((*retval == 100) && (count == 11)) {
printf("pthread_example test success!\n");
} else {
printf("pthread_example test fail!\n");
}
return 0;
}
#if AOS_COMP_CLI
/* reg args: fun, cmd, description*/
ALIOS_CLI_CMD_REGISTER(pthread_example, pthread_example, pthread example)
#endif
| YifuLiu/AliOS-Things | components/posix/example/pthread_example.c | C | apache-2.0 | 1,859 |
#include "dm_export.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
SYMBOL_EXPORT(printf);
SYMBOL_EXPORT(memmove);
SYMBOL_EXPORT(malloc);
SYMBOL_EXPORT(free);
SYMBOL_EXPORT(memset);
SYMBOL_EXPORT(getpid);
SYMBOL_EXPORT(strcpy);
SYMBOL_EXPORT(ioctl);
SYMBOL_EXPORT(memcpy);
SYMBOL_EXPORT(puts);
SYMBOL_EXPORT(close);
SYMBOL_EXPORT(open);
SYMBOL_EXPORT(strlen);
SYMBOL_EXPORT(snprintf);
SYMBOL_EXPORT(lseek);
SYMBOL_EXPORT(write);
SYMBOL_EXPORT(strstr);
SYMBOL_EXPORT(read);
SYMBOL_EXPORT(strncmp);
SYMBOL_EXPORT(strncpy);
SYMBOL_EXPORT(memcmp);
SYMBOL_EXPORT(sscanf);
SYMBOL_EXPORT(strtok);
SYMBOL_EXPORT(perror);
SYMBOL_EXPORT(__errno);
SYMBOL_EXPORT(__getreent);
SYMBOL_EXPORT(gettimeofday);
| YifuLiu/AliOS-Things | components/posix/export.c | C | apache-2.0 | 876 |
/*
* Copyright (C) 2018-2020 Alibaba Group Holding Limited
*/
#ifndef _DIRENT_H
#define _DIRENT_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <sys/stat.h>
#include <aos/vfs.h>
/* file types. */
#define DT_UNKNOWN 0
#define DT_FIFO 1
#define DT_CHR 2
#define DT_DIR 4
#define DT_BLK 6
#define DT_REG 8
#define DT_LNK 10
#define DT_SOCK 12
#define DT_WHT 14
#define DIRSIZ(dp) (offsetof(struct dirent, d_name) + ((strlen((dp)->d_name) + 1 + 3) & ~3))
typedef aos_dir_t DIR;
struct dirent {
int d_ino; /* file number */
uint8_t d_type; /* type of file */
char d_name[]; /* file name */
};
DIR * opendir(const char *dirname);
int closedir(DIR *dirp);
struct dirent *readdir(DIR *dirp);
long telldir(DIR *dirp);
void seekdir(DIR *dirp, long loc);
int mkdir(const char *path, mode_t mode);
int rmdir(const char *path);
void rewinddir(DIR *dirp);
int chdir(const char *path);
#ifdef __cplusplus
}
#endif
#endif /* _DIRENT_H */
| YifuLiu/AliOS-Things | components/posix/include/dirent.h | C | apache-2.0 | 1,103 |
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
#ifndef _ENVIRO_H
#define _ENVIRO_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdio.h>
/* definition for sysconf */
#define _POSIX_JOB_CONTROL 1
#define _POSIX_SAVED_IDS 1
#define _POSIX_VERSION 2016L
#define _POSIX_ASYNCHRONOUS_IO 1
#define _POSIX_FSYNC 1
#define _POSIX_MAPPED_FILES 0
#define _POSIX_MEMLOCK 0
#define _POSIX_MEMLOCK_RANGE 0
#define _POSIX_MEMORY_PROTECTION 0
#define _POSIX_MESSAGE_PASSING 1
#define _POSIX_PRIORITIZED_IO 1
#define _POSIX_PRIORITY_SCHEDULING 1
#define _POSIX_REALTIME_SIGNALS 0
#define _POSIX_SEMAPHORES 1
#define _POSIX_SYNCHRONIZED_IO 0
#define _POSIX_BARRIERS 0
#define _POSIX_READER_WRITER_LOCKS 0
#define _POSIX_SPIN_LOCKS 0
#define _POSIX_THREADS 1
#define _POSIX_THREAD_ATTR_STACKADDR 1
#define _POSIX_THREAD_ATTR_STACKSIZE 1
#define _POSIX_THREAD_PRIORITY_SCHEDULING 1
#define _POSIX_THREAD_PRIO_INHERIT 1
#define _POSIX_THREAD_PRIO_PROTECT 1
#define _POSIX_THREAD_PROCESS_SHARED 1
#define _POSIX_THREAD_SAFE_FUNCTIONS 0
#define _POSIX_SPAWN 0
#define _POSIX_TIMEOUTS 0
#define _POSIX_CPUTIME 1
#define _POSIX_THREAD_CPUTIME 1
#define _POSIX_ADVISORY_INFO 0
/* definition for confstr */
#define _CS_GNU_LIBC_VERSION 1
#define _CS_GNU_LIBPTHREAD_VERSION 2
#define _POSIX_GNU_LIBC_VERSION "newlib 7.3"
#define _POSIX_GNU_LIBPTHREAD_VERSION "IEEE Std 1003.1, 2016 Edition"
/* definition for uname */
#define _UTSNAME_SYSNAME_LENGTH 32
#define _UTSNAME_NODENAME_LENGTH 32
#define _UTSNAME_RELEASE_LENGTH 32
#define _UTSNAME_VERSION_LENGTH 32
#define _UTSNAME_MACHINE_LENGTH 32
struct utsname {
char sysname[_UTSNAME_SYSNAME_LENGTH]; /* name of this implementation of the operating system */
char nodename[_UTSNAME_NODENAME_LENGTH]; /* name of this node within the communications network to
which this node is attached, if any */
char release[_UTSNAME_RELEASE_LENGTH]; /* current release level of this implementation */
char version[_UTSNAME_VERSION_LENGTH]; /* current version level of this release */
char machine[_UTSNAME_MACHINE_LENGTH]; /* name of the hardware type on which the system is running */
};
/* definition for environment variable */
typedef struct pthread_environ {
char *envname;
char *envval;
struct pthread_environ *next;
} pthread_environ_t;
int setenv(const char *envname, const char *envval, int overwrite);
char *getenv(const char *name);
int unsetenv(const char *name);
int putenv(char *string);
int clearenv (void);
int uname(struct utsname *name);
long sysconf(int name);
size_t confstr(int name, char *buf, size_t len);
#ifdef __cplusplus
}
#endif
#endif /* _ENVIRO_H */
| YifuLiu/AliOS-Things | components/posix/include/enviro.h | C | apache-2.0 | 2,938 |
/*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef _MQUEUE_H
#define _MQUEUE_H
#ifdef __cplusplus
extern "C" {
#endif
#include <sys/types.h>
#include <time.h>
#define DEFAULT_MQUEUE_SIZE 10240
#define DEFAULT_MAX_MSG_SIZE 1024
typedef void *mqd_t;
struct mq_attr {
long mq_flags; /* message queue flags */
long mq_maxmsg; /* maximum number of messages */
long mq_msgsize; /* maximum message size */
long mq_curmsgs; /* number of messages currently queued */
};
mqd_t mq_open(const char *name, int oflag, ...);
int mq_close(mqd_t mqdes);
ssize_t mq_receive(mqd_t mqdes, char *msg_ptr, size_t msg_len, unsigned *msg_prio);
int mq_send(mqd_t mqdes, const char *msg_ptr, size_t msg_len, unsigned msg_prio);
int mq_setattr(mqd_t mqdes, const struct mq_attr *mqstat, struct mq_attr *omqstat);
int mq_getattr(mqd_t mqdes, struct mq_attr *mqstat);
ssize_t mq_timedreceive(mqd_t mqdes, char *msg_ptr, size_t msg_len, unsigned *msg_prio, const struct timespec *abs_timeout);
int mq_timedsend(mqd_t mqdes, const char *msg_ptr, size_t msg_len, unsigned msg_prio, const struct timespec *abs_timeout);
int mq_unlink(const char *name);
#ifdef __cplusplus
}
#endif
#endif /* _MQUEUE_H */
| YifuLiu/AliOS-Things | components/posix/include/mqueue.h | C | apache-2.0 | 1,294 |
/*
* Copyright (C) 2021 Alibaba Group Holding Limited
*/
#ifndef _POLL_H
#define _POLL_H
#ifdef __cplusplus
extern "C" {
#endif
#ifndef POLLIN
#define POLLIN 0x001
#endif
#ifndef POLLOUT
#define POLLOUT 0x004
#endif
#ifndef POLLERR
#define POLLERR 0x008
#endif
typedef int nfds_t;
struct pollfd {
int fd; /* file descriptor */
short events; /* requested events */
short revents; /* returned events */
};
int poll(struct pollfd fds[], nfds_t nfds, int timeout);
#ifdef __cplusplus
}
#endif
#endif /*_POLL_H*/
| YifuLiu/AliOS-Things | components/posix/include/poll.h | C | apache-2.0 | 548 |
/*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
/* Deprecated, Keep this file only for back compatible in old alios things.
* You should use the posix standard header files. */
#ifndef _POSIX_TIMER_H
#define _POSIX_TIMER_H
#include <time.h>
#include <signal.h>
#endif
| YifuLiu/AliOS-Things | components/posix/include/posix/timer.h | C | apache-2.0 | 289 |
/*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#ifndef _PTHREAD_H
#define _PTHREAD_H
#include <stdint.h>
#include <stddef.h>
#include <sys/timespec.h>
#include <sched.h>
#ifdef __cplusplus
extern "C" {
#endif
#define PTHREAD_CREATE_JOINABLE 0
#define PTHREAD_CREATE_DETACHED 1
#define PTHREAD_MUTEX_NORMAL 0
#define PTHREAD_MUTEX_DEFAULT 1
#define PTHREAD_MUTEX_RECURSIVE 1
#define PTHREAD_MUTEX_ERRORCHECK 2
#define PTHREAD_PRIO_NONE 0
#define PTHREAD_PRIO_INHERIT 1
#define PTHREAD_PRIO_PROTECT 2
#define PTHREAD_INHERIT_SCHED 0
#define PTHREAD_EXPLICIT_SCHED 1
#define PTHREAD_SCOPE_SYSTEM 0
#define PTHREAD_SCOPE_PROCESS 1
#define PTHREAD_PROCESS_PRIVATE 0
#define PTHREAD_PROCESS_SHARED 1
#define PTHREAD_CANCEL_ENABLE 0
#define PTHREAD_CANCEL_DISABLE 1
#define PTHREAD_CANCEL_MASKED 2
#define PTHREAD_CANCEL_DEFERRED 0
#define PTHREAD_CANCEL_ASYNCHRONOUS 1
#define PTHREAD_CANCELED ((void *)-1)
#define PTHREAD_DYN_INIT 0X01
#define PTHREAD_STATIC_INIT 0X02
#define PTHREAD_MUTEX_INITIALIZER {PTHREAD_STATIC_INIT, NULL, {0}}
#define PTHREAD_COND_INITIALIZER {PTHREAD_STATIC_INIT, 0, 0, NULL, NULL, NULL, {0}}
#define PTHREAD_ONCE_INIT 0
typedef void * pthread_t;
typedef int pthread_once_t;
typedef struct pthread_attr {
uint8_t flag;
void *stackaddr; /* the start addr of the stack of the pthead */
size_t stacksize; /* the size of the stack of the pthead */
size_t guardsize; /* guardsize is set to protect the stack, not supported */
int contentionscope; /* the scope of contention, only PTHREAD_SCOPE_SYSTEM is supported */
int inheritsched; /* when set to PTHREAD_INHERIT_SCHED, specifies that the thread scheduling attributes
shall be inherited from the creating thread, and the scheduling attributes in this
attr argument shall be ignored */
int schedpolicy; /* the sched policy of the thread */
int detachstate; /* when set to PTHREAD_CREATE_JOINABLE, thread will not end untill the creating thread end */
int sched_priority; /* The thread scheduling priority */
uint64_t sched_slice; /* The time slice in SCHED_RR mode (ms) */
} pthread_attr_t;
typedef struct pthread_mutexattr {
uint8_t flag;
int type;
int protocol;
int prioceiling;
int pshared;
} pthread_mutexattr_t;
typedef struct pthread_mutex {
uint8_t flag;
void *mutex;
pthread_mutexattr_t attr;
} pthread_mutex_t;
typedef struct pthread_condattr {
uint8_t flag;
int pshared; /* allow this to be shared amongst processes */
clock_t clock; /* specifiy clock for timeouts */
} pthread_condattr_t;
typedef struct pthread_cond {
uint8_t flag;
int waiting;
int signals;
void *lock;
void *wait_sem;
void *wait_done;
pthread_condattr_t attr;
} pthread_cond_t;
/********* Thread Specific Data *********/
typedef int pthread_key_t;
int pthread_atfork(void (*prepare)(void), void (*parent)(void), void (*child)(void));
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine)(void *), void *arg);
void pthread_exit(void *value_ptr);
int pthread_detach(pthread_t thread);
int pthread_join(pthread_t thread, void **retval);
int pthread_cancel(pthread_t thread);
void pthread_testcancel(void);
int pthread_setcancelstate(int state, int *oldstate);
int pthread_setcanceltype(int type, int *oldtype);
int pthread_kill(pthread_t thread, int sig);
int pthread_equal(pthread_t t1, pthread_t t2);
int pthread_setschedparam(pthread_t thread, int policy, const struct sched_param *pParam);
void pthread_cleanup_pop(int execute);
void pthread_cleanup_push(void (*routine)(void *), void *arg);
int pthread_once(pthread_once_t *once_control, void (*init_routine)(void));
pthread_t pthread_self(void);
int pthread_getcpuclockid(pthread_t thread_id, clockid_t *clock_id);
int pthread_setconcurrency(int new_level);
int pthread_getconcurrency(void);
int pthread_setschedprio(pthread_t thread, int prio);
int pthread_setname_np(pthread_t thread, const char *name);
int pthread_timedjoin_np(pthread_t thread, void **retval, const struct timespec *abstime);
int pthread_attr_init(pthread_attr_t *attr);
int pthread_attr_destroy(pthread_attr_t *attr);
int pthread_attr_setdetachstate(pthread_attr_t *attr, int detachstate);
int pthread_attr_getdetachstate(const pthread_attr_t *attr, int *detachstate);
int pthread_attr_setschedpolicy(pthread_attr_t *attr, int policy);
int pthread_attr_getschedpolicy(pthread_attr_t const *attr, int *policy);
int pthread_attr_setschedparam(pthread_attr_t *attr, const struct sched_param *param);
int pthread_attr_getschedparam(const pthread_attr_t *attr, struct sched_param *param);
int pthread_attr_setstacksize(pthread_attr_t *attr, size_t stacksize);
int pthread_attr_getstacksize(const pthread_attr_t *attr, size_t *stacksize);
int pthread_attr_setstackaddr(pthread_attr_t *attr, void *stackaddr);
int pthread_attr_getstackaddr(const pthread_attr_t *attr, void **stackaddr);
int pthread_attr_setstack(pthread_attr_t *attr, void *stackaddr, size_t stacksize);
int pthread_attr_getstack(const pthread_attr_t *attr, void **stackaddr, size_t *stacksize);
int pthread_attr_setinheritsched(pthread_attr_t *attr, int inheritsched);
int pthread_attr_getinheritsched(const pthread_attr_t *__restrict attr, int *__restrict inheritsched);
int pthread_attr_setguardsize(pthread_attr_t *attr, size_t guardsize);
int pthread_attr_getguardsize(const pthread_attr_t *attr, size_t *guardsize);
int pthread_attr_setscope(pthread_attr_t *attr, int scope);
int pthread_attr_getscope(const pthread_attr_t *attr, int *scope);
int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr);
int pthread_mutex_destroy(pthread_mutex_t *mutex);
int pthread_mutex_lock(pthread_mutex_t *mutex);
int pthread_mutex_unlock(pthread_mutex_t *mutex);
int pthread_mutex_trylock(pthread_mutex_t *mutex);
int pthread_mutex_timedlock(pthread_mutex_t *mutex, const struct timespec *at);
int pthread_mutex_getprioceiling(const pthread_mutex_t *__restrict mutex, int *__restrict prioceiling);
int pthread_mutex_setprioceiling(pthread_mutex_t *__restrict mutex, int prioceiling, int *__restrict old_ceiling);
int pthread_mutexattr_init(pthread_mutexattr_t *attr);
int pthread_mutexattr_destroy(pthread_mutexattr_t *attr);
int pthread_mutexattr_gettype(const pthread_mutexattr_t *attr, int *type);
int pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type);
int pthread_mutexattr_setpshared(pthread_mutexattr_t *attr, int pshared);
int pthread_mutexattr_getpshared(pthread_mutexattr_t *attr, int *pshared);
int pthread_mutexattr_setprotocol(pthread_mutexattr_t *attr, int protocol);
int pthread_mutexattr_getprotocol(const pthread_mutexattr_t *__restrict attr, int *__restrict protocol);
int pthread_mutexattr_getprioceiling(const pthread_mutexattr_t *__restrict attr, int *__restrict prioceiling);
int pthread_mutexattr_setprioceiling(pthread_mutexattr_t *attr, int prioceiling);
int pthread_cond_init(pthread_cond_t *cond, const pthread_condattr_t *attr);
int pthread_cond_destroy(pthread_cond_t *cond);
int pthread_cond_broadcast(pthread_cond_t *cond);
int pthread_cond_signal(pthread_cond_t *cond);
int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex);
int pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *abstime);
int pthread_condattr_init(pthread_condattr_t *attr);
int pthread_condattr_destroy(pthread_condattr_t *attr);
int pthread_condattr_setclock(pthread_condattr_t *attr, clockid_t clock);
int pthread_key_create(pthread_key_t *key, void (*destructor)(void*));
int pthread_setspecific(pthread_key_t key, const void *value);
void* pthread_getspecific(pthread_key_t key);
int pthread_key_delete(pthread_key_t key);
#ifdef __cplusplus
}
#endif
#endif /* _PTHREAD_H */
| YifuLiu/AliOS-Things | components/posix/include/pthread.h | C | apache-2.0 | 8,120 |
/*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#ifndef _SCHED_H
#define _SCHED_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <sys/types.h>
#include <sys/timespec.h>
/* The scheduling policy */
#define SCHED_OTHER 0
#define SCHED_FIFO 1
#define SCHED_RR 2
#define SCHED_CFS 3
struct sched_param {
int sched_priority; /* process execution scheduling priority */
uint64_t slice; /* time slice in SCHED_RR mode (ms) */
};
int sched_yield(void);
int sched_setscheduler(pid_t pid, int policy, const struct sched_param *param);
int sched_get_priority_min(int policy);
int sched_get_priority_max(int policy);
int sched_rr_get_interval(pid_t pid, struct timespec *interval);
#ifdef __cplusplus
}
#endif
#endif /*_SCHED_H*/
| YifuLiu/AliOS-Things | components/posix/include/sched.h | C | apache-2.0 | 792 |
/*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#ifndef _SEMAPHORE_H
#define _SEMAPHORE_H
#include <time.h>
#ifdef __cplusplus
extern "C" {
#endif
#define SEM_FAILED ((sem_t *)0)
#define SEM_VALUE_MAX 32767
typedef struct {
void *aos_sem;
} sem_t;
int sem_init(sem_t *sem, int pshared, unsigned int value);
sem_t *sem_open(const char *name, int oflag, ...);
int sem_post(sem_t *sem);
int sem_timedwait(sem_t *sem, const struct timespec *abs_timeout);
int sem_trywait(sem_t *sem);
int sem_unlink(const char *name);
int sem_wait(sem_t *sem);
int sem_getvalue(sem_t *sem, int *sval);
int sem_close(sem_t *sem);
int sem_destroy(sem_t *sem);
#ifdef __cplusplus
}
#endif
#endif /* _SEMAPHORE_H */
| YifuLiu/AliOS-Things | components/posix/include/semaphore.h | C | apache-2.0 | 746 |
/*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#ifndef _SIGNAL_H
#define _SIGNAL_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <pthread.h>
/* Here is only signal definitions, no signal function is supported. */
#define SIGHUP 1
#define SIGINT 2
#define SIGQUIT 3
#define SIGILL 4
#define SIGTRAP 5
#define SIGABRT 6
#define SIGIOT SIGABRT
#define SIGBUS 7
#define SIGFPE 8
#define SIGKILL 9
#define SIGUSR1 10
#define SIGSEGV 11
#define SIGUSR2 12
#define SIGPIPE 13
#define SIGALRM 14
#define SIGTERM 15
#define SIGSTKFLT 16
#define SIGCHLD 17
#define SIGCONT 18
#define SIGSTOP 19
#define SIGTSTP 20
#define SIGTTIN 21
#define SIGTTOU 22
#define SIGURG 23
#define SIGXCPU 24
#define SIGXFSZ 25
#define SIGVTALRM 26
#define SIGPROF 27
#define SIGWINCH 28
#define SIGIO 29
#define SIGPOLL 29
#define SIGPWR 30
#define SIGSYS 31
#define SIGUNUSED SIGSYS
#define NSIG 32
#define SIG_BLOCK 0
#define SIG_UNBLOCK 1
#define SIG_SETMASK 2
typedef uint32_t sigset_t;
typedef void (*sighandler_t)(int);
typedef sighandler_t _sig_func_ptr;
#define SIG_ERR ((sighandler_t)-1)
#define SIG_DFL ((sighandler_t) 0)
#define SIG_IGN ((sighandler_t) 1)
#define SIGEV_NONE 0
#define SIGEV_SIGNAL 1
#define SIGEV_THREAD 2
union sigval {
int sival_int;
void *sival_ptr;
};
struct sigevent {
int sigev_notify;
int sigev_signo;
union sigval sigev_value;
pthread_attr_t *sigev_notify_attributes;
void (*sigev_notify_function)(union sigval);
};
#ifdef __cplusplus
}
#endif
#endif /* _SIGNAL_H */
| YifuLiu/AliOS-Things | components/posix/include/signal.h | C | apache-2.0 | 1,668 |
/*
* Copyright (C) 2021 Alibaba Group Holding Limited
*/
| YifuLiu/AliOS-Things | components/posix/include/sys/_pthreadtypes.h | C | apache-2.0 | 59 |