1 /*
2 * Copyright (C) 2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "host_updater.h"
17
18 #include <algorithm>
19 #include <unordered_map>
20
21 #include "common.h"
22 #include "define.h"
23 #include "serial_struct.h"
24
25 namespace Hdc {
26 namespace {
27 constexpr uint8_t PERCENT_FINISH = 100;
28 constexpr uint8_t PERCENT_CLEAR = UINT8_MAX;
29 constexpr int MAX_RETRY_COUNT = 3;
30 constexpr size_t FLASH_PARAM_MIN_COUNT = 2;
31 constexpr size_t FLASH_FILE_INDEX = 1;
32 constexpr size_t UPDATE_PARAM_MIN_COUNT = 1;
33 constexpr size_t UPDATE_FILE_INDEX = 0;
34 constexpr size_t FORMAT_PARAM_MIN_COUNT = 2;
35 constexpr size_t ERASE_PARAM_MIN_COUNT = 2;
36
37 const std::string CMD_STR_UPDATE = "update ";
38 const std::string CMD_STR_FLASH = "flash ";
39 const std::string CMD_STR_ERASE = "erase ";
40 const std::string CMD_STR_FORMAT = "format ";
41
42 const std::unordered_map<std::string, uint16_t> FLASHD_CMD = {
43 {CMD_STR_UPDATE, CMD_FLASHD_UPDATE_INIT},
44 {CMD_STR_FLASH, CMD_FLASHD_FLASH_INIT},
45 {CMD_STR_ERASE, CMD_FLASHD_ERASE},
46 {CMD_STR_FORMAT, CMD_FLASHD_FORMAT},
47 };
48
Split(const std::string & src,const std::vector<std::string> & filter)49 std::vector<std::string> Split(const std::string &src, const std::vector<std::string> &filter)
50 {
51 std::vector<std::string> result;
52 if (src.empty()) {
53 return result;
54 }
55 const auto len = src.size() + 1;
56 auto buffer = std::vector<char>(len, 0);
57 buffer.assign(src.begin(), src.end());
58 const char delimit[] = "\t\r\n ";
59 char *nextToken = nullptr;
60 char *token = strtok_s(buffer.data(), delimit, &nextToken);
61 while (token != nullptr) {
62 if (std::find(filter.cbegin(), filter.cend(), token) == filter.cend()) {
63 result.push_back(token);
64 }
65 token = strtok_s(nullptr, delimit, &nextToken);
66 }
67 return result;
68 }
69 }
70
HostUpdater(HTaskInfo hTaskInfo)71 HostUpdater::HostUpdater(HTaskInfo hTaskInfo) : HdcTransferBase(hTaskInfo)
72 {
73 commandBegin = CMD_FLASHD_BEGIN;
74 commandData = CMD_FLASHD_DATA;
75 }
76
~HostUpdater()77 HostUpdater::~HostUpdater() {}
78
RunQueue(CtxFile & context)79 void HostUpdater::RunQueue(CtxFile &context)
80 {
81 refCount++;
82 context.localPath = context.taskQueue.back();
83 uv_fs_open(loopTask, &context.fsOpenReq, context.localPath.c_str(), O_RDONLY, 0, OnFileOpen);
84 context.master = true;
85 }
86
BeginTransfer(const std::string & function,const uint8_t * payload,int payloadSize,size_t minParam,size_t fileIndex)87 bool HostUpdater::BeginTransfer(const std::string &function, const uint8_t *payload, int payloadSize, size_t minParam,
88 size_t fileIndex)
89 {
90 if (payload[payloadSize - 1] != '\0') {
91 WRITE_LOG(LOG_FATAL, "payload is invalid");
92 return false;
93 }
94 std::string cmdParam(reinterpret_cast<const char *>(payload));
95 auto params = Split(cmdParam, {});
96 auto count = minParam;
97 auto index = fileIndex;
98 if (std::find(params.cbegin(), params.cend(), "-f") != params.cend()) {
99 count++;
100 index++;
101 }
102 if (params.size() != count || params.size() <= index) {
103 WRITE_LOG(LOG_FATAL, "param count is invalid");
104 return false;
105 }
106
107 std::string localPath = params[index];
108 if (!Base::CheckDirectoryOrPath(localPath.c_str(), true, true)) {
109 WRITE_LOG(LOG_FATAL, "localPath is invalid");
110 return false;
111 }
112
113 if (MatchPackageExtendName(localPath, ".img") || MatchPackageExtendName(localPath, ".bin")) {
114 ctxNow.transferConfig.compressType = COMPRESS_NONE;
115 } else if (MatchPackageExtendName(localPath, ".zip")) {
116 WRITE_LOG(LOG_INFO, "file type is zip");
117 } else {
118 WRITE_LOG(LOG_FATAL, "file type is invalid");
119 return false;
120 }
121 ctxNow.transferConfig.functionName = function;
122 ctxNow.transferConfig.options = cmdParam;
123 ctxNow.localPath = localPath;
124 ctxNow.taskQueue.push_back(localPath);
125 RunQueue(ctxNow);
126 return true;
127 }
128
CheckMaster(CtxFile * context)129 void HostUpdater::CheckMaster(CtxFile *context)
130 {
131 uv_fs_t fs;
132 Base::ZeroStruct(fs.statbuf);
133 uv_fs_fstat(nullptr, &fs, context->fsOpenReq.result, nullptr);
134 context->transferConfig.fileSize = fs.statbuf.st_size;
135 uv_fs_req_cleanup(&fs);
136 context->transferConfig.optionalName = Base::GetFileNameAny(context->localPath);
137 std::string bufString = SerialStruct::SerializeToString(context->transferConfig);
138
139 WRITE_LOG(LOG_DEBUG, "functionName = %s, fileSize = %llu", context->transferConfig.functionName.c_str(),
140 context->transferConfig.fileSize);
141
142 std::vector<uint8_t> buffer(sizeof(uint64_t) / sizeof(uint8_t), 0);
143 buffer.insert(buffer.end(), bufString.begin(), bufString.end());
144 SendToAnother(CMD_FLASHD_CHECK, (uint8_t *)buffer.data(), buffer.size());
145 }
146
CheckCmd(HdcCommand command,uint8_t * payload,int payloadSize,size_t paramCount)147 bool HostUpdater::CheckCmd(HdcCommand command, uint8_t *payload, int payloadSize, size_t paramCount)
148 {
149 if (payloadSize < 1 || payload[payloadSize - 1] != '\0') {
150 WRITE_LOG(LOG_FATAL, "payload is invalid");
151 return false;
152 }
153 std::string cmdParam(reinterpret_cast<char *>(payload));
154 WRITE_LOG(LOG_INFO, "cmdParam = %s, paramCount = %u", cmdParam.c_str(), paramCount);
155
156 auto result = Split(cmdParam, {});
157 auto iter = std::find(result.cbegin(), result.cend(), "-f");
158 bool ret = (iter != result.cend()) ? (result.size() == (paramCount + 1)) : (result.size() == paramCount);
159 if (!ret) {
160 WRITE_LOG(LOG_FATAL, "CheckCmd failed");
161 return false;
162 }
163
164 SendToAnother(command, payload, payloadSize);
165 ctxNow.taskQueue.push_back(cmdParam);
166 return true;
167 }
168
CommandDispatch(const uint16_t command,uint8_t * payload,const int payloadSize)169 bool HostUpdater::CommandDispatch(const uint16_t command, uint8_t *payload, const int payloadSize)
170 {
171 if (command == CMD_FLASHD_BEGIN) {
172 if (!HdcTransferBase::CommandDispatch(command, payload, payloadSize)) {
173 return false;
174 }
175 std::string tip("Processing: 0%");
176 sendProgress_ = true;
177 SendRawData(tip);
178 return true;
179 }
180
181 if (payload == nullptr || payloadSize <= 0) {
182 WRITE_LOG(LOG_FATAL, "payload or payloadSize is invalid");
183 return false;
184 }
185 if (!HdcTransferBase::CommandDispatch(command, payload, payloadSize)) {
186 return false;
187 }
188 bool ret = true;
189 switch (command) {
190 case CMD_FLASHD_UPDATE_INIT:
191 ret = BeginTransfer(CMDSTR_FLASHD_UPDATE, payload, payloadSize, UPDATE_PARAM_MIN_COUNT, UPDATE_FILE_INDEX);
192 break;
193 case CMD_FLASHD_FLASH_INIT:
194 ret = BeginTransfer(CMDSTR_FLASHD_FLASH, payload, payloadSize, FLASH_PARAM_MIN_COUNT, FLASH_FILE_INDEX);
195 break;
196 case CMD_FLASHD_FINISH:
197 ret = CheckUpdateContinue(command, payload, payloadSize);
198 break;
199 case CMD_FLASHD_ERASE:
200 ret = CheckCmd(CMD_FLASHD_ERASE, payload, payloadSize, ERASE_PARAM_MIN_COUNT);
201 break;
202 case CMD_FLASHD_FORMAT:
203 ret = CheckCmd(CMD_FLASHD_FORMAT, payload, payloadSize, FORMAT_PARAM_MIN_COUNT);
204 break;
205 case CMD_FLASHD_PROGRESS:
206 ProcessProgress(*payload);
207 break;
208 default:
209 break;
210 }
211 return ret;
212 }
213
ProcessProgress(uint8_t percentage)214 void HostUpdater::ProcessProgress(uint8_t percentage)
215 {
216 if (!sendProgress_) {
217 return;
218 }
219 if (percentage == PERCENT_CLEAR) {
220 SendRawData("\n");
221 sendProgress_ = false;
222 return;
223 }
224 std::string plrogress = "\rProcessing: " + std::to_string(percentage) + "%";
225 SendRawData(plrogress);
226 if (percentage == PERCENT_FINISH) {
227 SendRawData("\n");
228 sendProgress_ = false;
229 }
230 }
231
CheckUpdateContinue(const uint16_t command,const uint8_t * payload,int payloadSize)232 bool HostUpdater::CheckUpdateContinue(const uint16_t command, const uint8_t *payload, int payloadSize)
233 {
234 if (static_cast<size_t>(payloadSize) < sizeof(uint16_t)) {
235 return false;
236 }
237
238 MessageLevel level = static_cast<MessageLevel>(payload[1]);
239 if ((level == MSG_OK) && sendProgress_) {
240 ProcessProgress(PERCENT_FINISH);
241 }
242 std::string info(reinterpret_cast<char *>(const_cast<uint8_t *>(payload + sizeof(uint16_t))),
243 payloadSize - sizeof(uint16_t));
244 if (!info.empty()) {
245 LogMsg(level, "%s", info.c_str());
246 }
247 WRITE_LOG(LOG_DEBUG, "CheckUpdateContinue payloadSize %d %d %s", payloadSize, level, info.c_str());
248 if (ctxNow.taskQueue.size() != 0) {
249 ctxNow.taskQueue.pop_back();
250 }
251 if (singalStop || !ctxNow.taskQueue.size()) {
252 return false;
253 }
254 RunQueue(ctxNow);
255 return true;
256 }
257
CheckMatchUpdate(const std::string & input,TranslateCommand::FormatCommand & outCmd)258 bool HostUpdater::CheckMatchUpdate(const std::string &input, TranslateCommand::FormatCommand &outCmd)
259 {
260 WRITE_LOG(LOG_DEBUG, "CheckMatchUpdate command:%s", input.c_str());
261 for (const auto &iter : FLASHD_CMD) {
262 if ((input.find(iter.first) == 0) && (input.size() > iter.first.size())) {
263 outCmd.cmdFlag = iter.second;
264 return true;
265 }
266 }
267 return false;
268 }
269
ConfirmCommand(const string & commandIn,bool & closeInput)270 bool HostUpdater::ConfirmCommand(const string &commandIn, bool &closeInput)
271 {
272 std::string tip = "";
273 if (!strncmp(commandIn.c_str(), CMD_STR_UPDATE.c_str(), CMD_STR_UPDATE.size())) {
274 closeInput = true;
275 } else if (!strncmp(commandIn.c_str(), CMD_STR_FLASH.c_str(), CMD_STR_FLASH.size())) {
276 tip = "Confirm flash partition";
277 closeInput = true;
278 } else if (!strncmp(commandIn.c_str(), CMD_STR_ERASE.c_str(), CMD_STR_ERASE.size())) {
279 tip = "Confirm erase partition";
280 } else if (!strncmp(commandIn.c_str(), CMD_STR_FORMAT.c_str(), CMD_STR_FORMAT.size())) {
281 tip = "Confirm format partition";
282 }
283 if (tip.empty() || strstr(commandIn.c_str(), " -f") != nullptr) {
284 return true;
285 }
286 const size_t minLen = strlen("yes");
287 int retryCount = 0;
288 do {
289 printf("%s ? (Yes/No) ", tip.c_str());
290 fflush(stdin);
291 std::string info = {};
292 size_t i = 0;
293 while (1) {
294 char c = getchar();
295 if (c == '\r' || c == '\n') {
296 break;
297 }
298 if (c == ' ') {
299 continue;
300 }
301 if (i < minLen && isprint(c)) {
302 info.append(1, std::tolower(c));
303 i++;
304 }
305 }
306 if (info == "n" || info == "no") {
307 return false;
308 }
309 if (info == "y" || info == "yes") {
310 return true;
311 }
312 retryCount++;
313 } while (retryCount < MAX_RETRY_COUNT);
314 return (retryCount >= MAX_RETRY_COUNT) ? false : true;
315 }
316
SendRawData(std::string rawData) const317 void HostUpdater::SendRawData(std::string rawData) const
318 {
319 HdcSessionBase *sessionBase = (HdcSessionBase *)clsSession;
320 if (sessionBase == nullptr) {
321 WRITE_LOG(LOG_FATAL, "sessionBase is null");
322 return;
323 }
324 sessionBase->ServerCommand(taskInfo->sessionId, taskInfo->channelId, CMD_KERNEL_ECHO_RAW,
325 reinterpret_cast<uint8_t *>(rawData.data()), rawData.size());
326 }
327 } // namespace Hdc