1 /*
2 * Copyright (c) 2021 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 #include "update_image_block.h"
16 #include <cerrno>
17 #include <fcntl.h>
18 #include <pthread.h>
19 #include <sstream>
20 #include <sys/stat.h>
21 #include <sys/types.h>
22 #include <unistd.h>
23 #include "applypatch/block_set.h"
24 #include "applypatch/store.h"
25 #include "applypatch/transfer_manager.h"
26 #include "applypatch/partition_record.h"
27 #include "fs_manager/mount.h"
28 #include "log/dump.h"
29 #include "log/log.h"
30 #include "updater/updater_const.h"
31 #include "updater/hwfault_retry.h"
32 #include "utils.h"
33
34 using namespace Uscript;
35 using namespace Hpackage;
36 using namespace Updater;
37
38 namespace Updater {
39 constexpr int32_t SHA_CHECK_SECOND = 2;
40 constexpr int32_t SHA_CHECK_PARAMS = 3;
41 constexpr int32_t SHA_CHECK_TARGETPAIRS_INDEX = 3;
42 constexpr int32_t SHA_CHECK_TARGETSHA_INDEX = 4;
43 constexpr int32_t SHA_CHECK_TARGET_PARAMS = 5;
ExtractNewData(const PkgBuffer & buffer,size_t size,size_t start,bool isFinish,const void * context)44 static int ExtractNewData(const PkgBuffer &buffer, size_t size, size_t start, bool isFinish, const void* context)
45 {
46 void *p = const_cast<void *>(context);
47 WriterThreadInfo *info = static_cast<WriterThreadInfo *>(p);
48 uint8_t *addr = buffer.buffer;
49 while (size > 0) {
50 pthread_mutex_lock(&info->mutex);
51 while (info->writer == nullptr) {
52 if (!info->readyToWrite) {
53 LOG(WARNING) << "writer is not ready to write.";
54 pthread_mutex_unlock(&info->mutex);
55 return Hpackage::PKG_INVALID_STREAM;
56 }
57 pthread_cond_wait(&info->cond, &info->mutex);
58 }
59 pthread_mutex_unlock(&info->mutex);
60 size_t toWrite = std::min(size, info->writer->GetBlocksSize() - info->writer->GetTotalWritten());
61 // No more data to write.
62 if (toWrite == 0) {
63 break;
64 }
65 bool ret = info->writer->Write(addr, toWrite, nullptr);
66 std::ostringstream logMessage;
67 logMessage << "Write " << toWrite << " byte(s) failed";
68 if (!ret) {
69 LOG(ERROR) << logMessage.str();
70 return Hpackage::PKG_INVALID_STREAM;
71 }
72 size -= toWrite;
73 addr += toWrite;
74
75 if (info->writer->IsWriteDone()) {
76 pthread_mutex_lock(&info->mutex);
77 info->writer.reset();
78 pthread_cond_broadcast(&info->cond);
79 pthread_mutex_unlock(&info->mutex);
80 }
81 }
82 return Hpackage::PKG_SUCCESS;
83 }
84
CondBroadcast(WriterThreadInfo * info)85 static inline void CondBroadcast(WriterThreadInfo *info)
86 {
87 pthread_mutex_lock(&info->mutex);
88 info->readyToWrite = false;
89 if (info->writer != nullptr) {
90 pthread_cond_broadcast(&info->cond);
91 }
92 pthread_mutex_unlock(&info->mutex);
93 }
94
UnpackNewData(void * arg)95 void* UnpackNewData(void *arg)
96 {
97 TransferManagerPtr tm = static_cast<TransferManagerPtr>(arg);
98 WriterThreadInfo *info = tm->GetTransferParams()->writerThreadInfo.get();
99 Hpackage::PkgManager::StreamPtr stream = nullptr;
100 if (info->newPatch.empty()) {
101 LOG(ERROR) << "new patch file name is empty. thread quit.";
102 CondBroadcast(info);
103 return nullptr;
104 }
105 LOG(DEBUG) << "new patch file name: " << info->newPatch;
106 auto env = tm->GetTransferParams()->env;
107 const FileInfo *file = env->GetPkgManager()->GetFileInfo(info->newPatch);
108 if (file == nullptr) {
109 LOG(ERROR) << "Cannot get file info of :" << info->newPatch;
110 CondBroadcast(info);
111 return nullptr;
112 }
113 LOG(DEBUG) << info->newPatch << " info: size " << file->packedSize << " unpacked size " <<
114 file->unpackedSize << " name " << file->identity;
115 int32_t ret = env->GetPkgManager()->CreatePkgStream(stream, info->newPatch, ExtractNewData, info);
116 if (ret != Hpackage::PKG_SUCCESS || stream == nullptr) {
117 LOG(ERROR) << "Cannot extract " << info->newPatch << " from package.";
118 CondBroadcast(info);
119 return nullptr;
120 }
121 ret = env->GetPkgManager()->ExtractFile(info->newPatch, stream);
122 env->GetPkgManager()->ClosePkgStream(stream);
123 LOG(DEBUG) << "new data writer ending...";
124 // extract new data done.
125 // tell command.
126 CondBroadcast(info);
127 return nullptr;
128 }
129
ReturnAndPushParam(int32_t returnValue,Uscript::UScriptContext & context)130 static int32_t ReturnAndPushParam(int32_t returnValue, Uscript::UScriptContext &context)
131 {
132 context.PushParam(returnValue);
133 return returnValue;
134 }
135
136 struct UpdateBlockInfo {
137 std::string partitionName;
138 std::string transferName;
139 std::string newDataName;
140 std::string patchDataName;
141 std::string devPath;
142 };
143
GetUpdateBlockInfo(struct UpdateBlockInfo & infos,Uscript::UScriptEnv & env,Uscript::UScriptContext & context)144 static int32_t GetUpdateBlockInfo(struct UpdateBlockInfo &infos, Uscript::UScriptEnv &env,
145 Uscript::UScriptContext &context)
146 {
147 if (context.GetParamCount() != 4) { // 4:Determine the number of parameters
148 LOG(ERROR) << "Invalid param";
149 return ReturnAndPushParam(USCRIPT_INVALID_PARAM, context);
150 }
151
152 // Get partition Name first.
153 // Use partition name as zip file name. ${partition name}.zip
154 // load ${partition name}.zip from updater package.
155 // Try to unzip ${partition name}.zip, extract transfer.list, net.dat, patch.dat
156 size_t pos = 0;
157 int32_t ret = context.GetParam(pos++, infos.partitionName);
158 if (ret != USCRIPT_SUCCESS) {
159 LOG(ERROR) << "Error to get param 1";
160 return ret;
161 }
162 ret = context.GetParam(pos++, infos.transferName);
163 if (ret != USCRIPT_SUCCESS) {
164 LOG(ERROR) << "Error to get param 2";
165 return ret;
166 }
167 ret = context.GetParam(pos++, infos.newDataName);
168 if (ret != USCRIPT_SUCCESS) {
169 LOG(ERROR) << "Error to get param 3";
170 return ret;
171 }
172 ret = context.GetParam(pos++, infos.patchDataName);
173 if (ret != USCRIPT_SUCCESS) {
174 LOG(ERROR) << "Error to get param 4";
175 return ret;
176 }
177
178 LOG(INFO) << "ExecuteUpdateBlock::updating " << infos.partitionName << " ...";
179 infos.devPath = GetBlockDeviceByMountPoint(infos.partitionName);
180 LOG(INFO) << "ExecuteUpdateBlock::updating dev path : " << infos.devPath;
181 if (infos.devPath.empty()) {
182 LOG(ERROR) << "cannot get block device of partition";
183 return ReturnAndPushParam(USCRIPT_ERROR_EXECUTE, context);
184 }
185 return USCRIPT_SUCCESS;
186 }
187
ExecuteTransferCommand(int fd,const std::vector<std::string> & lines,TransferManagerPtr tm,Uscript::UScriptContext & context,const UpdateBlockInfo & infos)188 static int32_t ExecuteTransferCommand(int fd, const std::vector<std::string> &lines, TransferManagerPtr tm,
189 Uscript::UScriptContext &context, const UpdateBlockInfo &infos)
190 {
191 auto transferParams = tm->GetTransferParams();
192 auto writerThreadInfo = transferParams->writerThreadInfo.get();
193
194 transferParams->storeBase = std::string("/data/updater") + infos.partitionName + "_tmp";
195 transferParams->retryFile = std::string("/data/updater") + infos.partitionName + "_retry";
196 transferParams->devPath = infos.devPath;
197 LOG(INFO) << "Store base path is " << transferParams->storeBase;
198 int32_t ret = Store::CreateNewSpace(transferParams->storeBase, !transferParams->env->IsRetry());
199 if (ret == -1) {
200 LOG(ERROR) << "Error to create new store space";
201 return ReturnAndPushParam(USCRIPT_ERROR_EXECUTE, context);
202 }
203 transferParams->storeCreated = ret;
204
205 if (!tm->CommandsParser(fd, lines)) {
206 return USCRIPT_ERROR_EXECUTE;
207 }
208 pthread_mutex_lock(&writerThreadInfo->mutex);
209 if (writerThreadInfo->readyToWrite) {
210 LOG(WARNING) << "New data writer thread is still available...";
211 }
212
213 writerThreadInfo->readyToWrite = false;
214 pthread_cond_broadcast(&writerThreadInfo->cond);
215 pthread_mutex_unlock(&writerThreadInfo->mutex);
216 ret = pthread_join(transferParams->thread, nullptr);
217 std::ostringstream logMessage;
218 logMessage << "pthread join returned with " << ret;
219 if (ret != 0) {
220 LOG(WARNING) << logMessage.str();
221 }
222 if (transferParams->storeCreated != -1) {
223 Store::DoFreeSpace(transferParams->storeBase);
224 }
225 return USCRIPT_SUCCESS;
226 }
227
InitThread(const struct UpdateBlockInfo & infos,TransferManagerPtr tm)228 static int InitThread(const struct UpdateBlockInfo &infos, TransferManagerPtr tm)
229 {
230 auto transferParams = tm->GetTransferParams();
231 auto writerThreadInfo = transferParams->writerThreadInfo.get();
232 writerThreadInfo->readyToWrite = true;
233 pthread_mutex_init(&writerThreadInfo->mutex, nullptr);
234 pthread_cond_init(&writerThreadInfo->cond, nullptr);
235 pthread_attr_t attr;
236 pthread_attr_init(&attr);
237 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
238 writerThreadInfo->newPatch = infos.newDataName;
239 int error = pthread_create(&transferParams->thread, &attr, UnpackNewData, tm);
240 return error;
241 }
242
ExtractDiffPackageAndLoad(const UpdateBlockInfo & infos,Uscript::UScriptEnv & env,Uscript::UScriptContext & context)243 static int32_t ExtractDiffPackageAndLoad(const UpdateBlockInfo &infos, Uscript::UScriptEnv &env,
244 Uscript::UScriptContext &context)
245 {
246 Hpackage::PkgManager::StreamPtr outStream = nullptr;
247 LOG(DEBUG) << "partitionName is " << infos.partitionName;
248 const FileInfo *info = env.GetPkgManager()->GetFileInfo(infos.partitionName);
249 if (info == nullptr) {
250 LOG(WARNING) << "Error to get file info";
251 return USCRIPT_SUCCESS;
252 }
253 std::string diffPackage = std::string("/data/updater") + infos.partitionName;
254 int32_t ret = env.GetPkgManager()->CreatePkgStream(outStream,
255 diffPackage, info->unpackedSize, PkgStream::PkgStreamType_Write);
256 if (outStream == nullptr) {
257 LOG(ERROR) << "Error to create output stream";
258 return USCRIPT_ERROR_EXECUTE;
259 }
260
261 ret = env.GetPkgManager()->ExtractFile(infos.partitionName, outStream);
262 if (ret != USCRIPT_SUCCESS) {
263 LOG(ERROR) << "Error to extract file";
264 env.GetPkgManager()->ClosePkgStream(outStream);
265 return USCRIPT_ERROR_EXECUTE;
266 }
267 env.GetPkgManager()->ClosePkgStream(outStream);
268 std::string diffPackageZip = diffPackage + ".zip";
269 if (rename(diffPackage.c_str(), diffPackageZip.c_str()) != 0) {
270 LOG(ERROR) << "rename failed";
271 return USCRIPT_ERROR_EXECUTE;
272 }
273 LOG(DEBUG) << "Rename " << diffPackage << " to zip\nExtract " << diffPackage << " done\nReload " << diffPackageZip;
274 std::vector<std::string> diffPackageComponents;
275 ret = env.GetPkgManager()->LoadPackage(diffPackageZip, Updater::Utils::GetCertName(), diffPackageComponents);
276 if (diffPackageComponents.size() < 1) {
277 LOG(ERROR) << "Diff package is empty";
278 return ReturnAndPushParam(USCRIPT_ERROR_EXECUTE, context);
279 }
280 return USCRIPT_SUCCESS;
281 }
282
DoExecuteUpdateBlock(const UpdateBlockInfo & infos,TransferManagerPtr tm,Hpackage::PkgManager::StreamPtr & outStream,const std::vector<std::string> & lines,Uscript::UScriptContext & context)283 static int32_t DoExecuteUpdateBlock(const UpdateBlockInfo &infos, TransferManagerPtr tm,
284 Hpackage::PkgManager::StreamPtr &outStream, const std::vector<std::string> &lines, Uscript::UScriptContext &context)
285 {
286 int fd = open(infos.devPath.c_str(), O_RDWR | O_LARGEFILE);
287 auto env = tm->GetTransferParams()->env;
288 if (fd == -1) {
289 LOG(ERROR) << "Failed to open block";
290 env->GetPkgManager()->ClosePkgStream(outStream);
291 return USCRIPT_ERROR_EXECUTE;
292 }
293 int32_t ret = ExecuteTransferCommand(fd, lines, tm, context, infos);
294 fsync(fd);
295 close(fd);
296 fd = -1;
297 env->GetPkgManager()->ClosePkgStream(outStream);
298 if (ret == USCRIPT_SUCCESS) {
299 PartitionRecord::GetInstance().RecordPartitionUpdateStatus(infos.partitionName, true);
300 }
301 return ret;
302 }
303
ExtractFileByName(Uscript::UScriptEnv & env,const std::string & fileName,Hpackage::PkgManager::StreamPtr & outStream,uint8_t * & outBuf,size_t & buffSize)304 static int32_t ExtractFileByName(Uscript::UScriptEnv &env, const std::string &fileName,
305 Hpackage::PkgManager::StreamPtr &outStream, uint8_t *&outBuf, size_t &buffSize)
306 {
307 if (env.GetPkgManager() == nullptr) {
308 LOG(ERROR) << "Error to get pkg manager";
309 return USCRIPT_ERROR_EXECUTE;
310 }
311
312 const FileInfo *info = env.GetPkgManager()->GetFileInfo(fileName);
313 if (info == nullptr) {
314 LOG(ERROR) << "GetFileInfo fail";
315 return USCRIPT_ERROR_EXECUTE;
316 }
317 auto ret = env.GetPkgManager()->CreatePkgStream(outStream,
318 fileName, info->unpackedSize, PkgStream::PkgStreamType_MemoryMap);
319 if (ret != USCRIPT_SUCCESS || outStream == nullptr) {
320 LOG(ERROR) << "Error to create output stream";
321 return USCRIPT_ERROR_EXECUTE;
322 }
323 ret = env.GetPkgManager()->ExtractFile(fileName, outStream);
324 if (ret != USCRIPT_SUCCESS) {
325 LOG(ERROR) << "Error to extract file";
326 env.GetPkgManager()->ClosePkgStream(outStream);
327 return USCRIPT_ERROR_EXECUTE;
328 }
329 ret = outStream->GetBuffer(outBuf, buffSize);
330 LOG(DEBUG) << "outBuf data size is: " << buffSize;
331
332 return USCRIPT_SUCCESS;
333 }
334
ExecuteUpdateBlock(Uscript::UScriptEnv & env,Uscript::UScriptContext & context)335 static int32_t ExecuteUpdateBlock(Uscript::UScriptEnv &env, Uscript::UScriptContext &context)
336 {
337 UpdateBlockInfo infos {};
338 if (GetUpdateBlockInfo(infos, env, context) != USCRIPT_SUCCESS) {
339 return USCRIPT_ERROR_EXECUTE;
340 }
341
342 if (env.IsRetry()) {
343 LOG(DEBUG) << "Retry updater, check if current partition updatered already during last time";
344 if (PartitionRecord::GetInstance().IsPartitionUpdated(infos.partitionName)) {
345 LOG(INFO) << infos.partitionName << " already updated, skip";
346 return USCRIPT_SUCCESS;
347 }
348 }
349
350 if (ExtractDiffPackageAndLoad(infos, env, context) != USCRIPT_SUCCESS) {
351 return USCRIPT_ERROR_EXECUTE;
352 }
353
354 uint8_t *transferListBuffer = nullptr;
355 size_t transferListSize = 0;
356 Hpackage::PkgManager::StreamPtr outStream = nullptr;
357 if (ExtractFileByName(env, infos.transferName, outStream,
358 transferListBuffer, transferListSize) != USCRIPT_SUCCESS) {
359 return USCRIPT_ERROR_EXECUTE;
360 }
361
362 std::unique_ptr<TransferManager> tm = std::make_unique<TransferManager>();
363
364 auto transferParams = tm->GetTransferParams();
365 /* Save Script Env to transfer manager */
366 transferParams->env = &env;
367
368 std::vector<std::string> lines =
369 Updater::Utils::SplitString(std::string(reinterpret_cast<const char*>(transferListBuffer)), "\n");
370 // Close stream opened before.
371 env.GetPkgManager()->ClosePkgStream(outStream);
372
373 LOG(INFO) << "Start unpack new data thread done. Get patch data: " << infos.patchDataName;
374 if (ExtractFileByName(env, infos.patchDataName, outStream,
375 transferParams->patchDataBuffer, transferParams->patchDataSize) != USCRIPT_SUCCESS) {
376 return USCRIPT_ERROR_EXECUTE;
377 }
378
379 LOG(INFO) << "Ready to start a thread to handle new data processing";
380 if (InitThread(infos, tm.get()) != 0) {
381 LOG(ERROR) << "Failed to create pthread";
382 env.GetPkgManager()->ClosePkgStream(outStream);
383 return USCRIPT_ERROR_EXECUTE;
384 }
385
386 return DoExecuteUpdateBlock(infos, tm.get(), outStream, lines, context);
387 }
388
Execute(Uscript::UScriptEnv & env,Uscript::UScriptContext & context)389 int32_t UScriptInstructionBlockUpdate::Execute(Uscript::UScriptEnv &env, Uscript::UScriptContext &context)
390 {
391 int32_t result = ExecuteUpdateBlock(env, context);
392 context.PushParam(result);
393 return result;
394 }
395
ExecReadBlockInfo(const std::string & devPath,Uscript::UScriptContext & context,time_t & mountTime,uint16_t & mountCount)396 bool UScriptInstructionBlockCheck::ExecReadBlockInfo(const std::string &devPath, Uscript::UScriptContext &context,
397 time_t &mountTime, uint16_t &mountCount)
398 {
399 UPDATER_INIT_RECORD;
400 int fd = open(devPath.c_str(), O_RDWR | O_LARGEFILE);
401 if (fd == -1) {
402 LOG(ERROR) << "Failed to open file";
403 UPDATER_LAST_WORD(false);
404 return false;
405 }
406 std::vector<uint8_t> block_buff(H_BLOCK_SIZE);
407 BlockSet blk0(std::vector<BlockPair> {BlockPair{0, 1}});
408
409 size_t pos = 0;
410 std::vector<BlockPair>::iterator it = blk0.Begin();
411 for (; it != blk0.End(); ++it) {
412 LOG(INFO) << "BlockSet::ReadDataFromBlock lseek64";
413 if (lseek64(fd, static_cast<off64_t>(it->first * H_BLOCK_SIZE), SEEK_SET) == -1) {
414 LOG(ERROR) << "Failed to seek";
415 close(fd);
416 UPDATER_LAST_WORD(false);
417 return false;
418 }
419 size_t size = (it->second - it->first) * H_BLOCK_SIZE;
420 LOG(INFO) << "BlockSet::ReadDataFromBlock Read " << size << " from block";
421 if (!Utils::ReadFully(fd, block_buff.data() + pos, size)) {
422 LOG(ERROR) << "Failed to read";
423 close(fd);
424 UPDATER_LAST_WORD(false);
425 return false;
426 }
427 pos += size;
428 }
429 close(fd);
430 mountTime = *reinterpret_cast<uint32_t *>(&block_buff[0x400 + 0x2C]);
431 mountCount = *reinterpret_cast<uint16_t *>(&block_buff[0x400 + 0x34]);
432 return true;
433 }
434
Execute(Uscript::UScriptEnv & env,Uscript::UScriptContext & context)435 int32_t UScriptInstructionBlockCheck::Execute(Uscript::UScriptEnv &env, Uscript::UScriptContext &context)
436 {
437 if (context.GetParamCount() != 1) {
438 LOG(ERROR) << "Invalid param";
439 UPDATER_LAST_WORD(USCRIPT_INVALID_PARAM);
440 return ReturnAndPushParam(USCRIPT_INVALID_PARAM, context);
441 }
442 if (env.IsRetry()) {
443 return ReturnAndPushParam(USCRIPT_SUCCESS, context);
444 }
445 std::string partitionName;
446 int32_t ret = context.GetParam(0, partitionName);
447 if (ret != USCRIPT_SUCCESS) {
448 LOG(ERROR) << "Failed to get param";
449 UPDATER_LAST_WORD(USCRIPT_ERROR_EXECUTE);
450 return ReturnAndPushParam(USCRIPT_ERROR_EXECUTE, context);
451 }
452 auto devPath = GetBlockDeviceByMountPoint(partitionName);
453 LOG(INFO) << "UScriptInstructionBlockCheck::dev path : " << devPath;
454 time_t mountTime = 0;
455 uint16_t mountCount = 0;
456 if (devPath.empty() || (!ExecReadBlockInfo(devPath, context, mountTime, mountCount))) {
457 LOG(ERROR) << "cannot get block device of partition";
458 UPDATER_LAST_WORD(USCRIPT_ERROR_EXECUTE);
459 return ReturnAndPushParam(USCRIPT_ERROR_EXECUTE, context);
460 }
461
462 if (mountCount > 0) {
463 std::ostringstream ostr;
464 ostr << "Device was remounted R/W " << mountCount << "times\nLast remount happened on " <<
465 ctime(&mountTime) << std::endl;
466 std::string message = ostr.str();
467 env.PostMessage("ui_log", message);
468 LOG(ERROR) << message;
469 }
470 LOG(INFO) << "UScriptInstructionBlockCheck::Execute Success";
471 context.PushParam(USCRIPT_SUCCESS);
472 return USCRIPT_SUCCESS;
473 }
474
IsTargetShaDiff(const std::string & devPath,const ShaInfo & shaInfo)475 bool UScriptInstructionShaCheck::IsTargetShaDiff(const std::string &devPath, const ShaInfo &shaInfo)
476 {
477 std::string tgtResultSha = CalculateBlockSha(devPath, shaInfo.targetPairs);
478 if (tgtResultSha.empty()) {
479 LOG(WARNING) << "target sha is empty";
480 return true;
481 }
482 LOG(INFO) << "tgtResultSha: " << tgtResultSha << ", shaInfo.targetSha: " << shaInfo.targetSha;
483 return (tgtResultSha != shaInfo.targetSha);
484 }
485
ExecReadShaInfo(Uscript::UScriptEnv & env,const std::string & devPath,const ShaInfo & shaInfo)486 int UScriptInstructionShaCheck::ExecReadShaInfo(Uscript::UScriptEnv &env, const std::string &devPath,
487 const ShaInfo &shaInfo)
488 {
489 UPDATER_INIT_RECORD;
490 std::string resultSha = CalculateBlockSha(devPath, shaInfo.blockPairs);
491 if (resultSha != shaInfo.contrastSha && IsTargetShaDiff(devPath, shaInfo)) {
492 LOG(ERROR) << "Different sha256, cannot continue";
493 LOG(ERROR) << "blockPairs:" << shaInfo.blockPairs;
494 LOG(ERROR) << "resultSha: " << resultSha << ", shaInfo.contrastSha: " << shaInfo.contrastSha;
495 PrintAbnormalBlockHash(devPath, shaInfo.blockPairs);
496 UPDATER_LAST_WORD(devPath.substr(devPath.find_last_of("/") + 1), USCRIPT_ERROR_EXECUTE);
497 env.PostMessage(UPDATER_RETRY_TAG, VERIFY_FAILED_REBOOT);
498 return USCRIPT_ERROR_EXECUTE;
499 }
500 LOG(INFO) << "UScriptInstructionShaCheck::Execute Success";
501 return USCRIPT_SUCCESS;
502 }
503
PrintAbnormalBlockHash(const std::string & devPath,const std::string & blockPairs)504 void UScriptInstructionShaCheck::PrintAbnormalBlockHash(const std::string &devPath, const std::string &blockPairs)
505 {
506 int fd = open(devPath.c_str(), O_RDWR | O_LARGEFILE);
507 if (fd == -1) {
508 LOG(ERROR) << "Failed to open file " << devPath;
509 return;
510 }
511
512 BlockSet blk;
513 blk.ParserAndInsert(blockPairs);
514 std::vector<uint8_t> block_buff(H_BLOCK_SIZE);
515 std::vector<BlockPair>::iterator it = blk.Begin();
516 for (; it != blk.End(); ++it) {
517 if (lseek64(fd, static_cast<off64_t>(it->first * H_BLOCK_SIZE), SEEK_SET) == -1) {
518 LOG(ERROR) << "Failed to seek";
519 close(fd);
520 return;
521 }
522 SHA256_CTX ctx;
523 SHA256_Init(&ctx);
524 for (size_t i = it->first; i < it->second; ++i) {
525 if (!Utils::ReadFully(fd, block_buff.data(), H_BLOCK_SIZE)) {
526 LOG(ERROR) << "Failed to read";
527 close(fd);
528 return;
529 }
530 SHA256_Update(&ctx, block_buff.data(), H_BLOCK_SIZE);
531 }
532 uint8_t digest[SHA256_DIGEST_LENGTH] = {0};
533 SHA256_Final(digest, &ctx);
534 LOG(ERROR) << "block id:" << it->first << "-" << it->second <<
535 " hex:" << Utils::ConvertSha256Hex(digest, SHA256_DIGEST_LENGTH);
536 }
537 close(fd);
538 }
539
CalculateBlockSha(const std::string & devPath,const std::string & blockPairs)540 std::string UScriptInstructionShaCheck::CalculateBlockSha(const std::string &devPath, const std::string &blockPairs)
541 {
542 if (blockPairs.empty()) {
543 LOG(ERROR) << "Failed to get blockPairs";
544 return "";
545 }
546
547 int fd = open(devPath.c_str(), O_RDWR | O_LARGEFILE);
548 if (fd == -1) {
549 LOG(ERROR) << "Failed to open file";
550 UPDATER_LAST_WORD(USCRIPT_ERROR_EXECUTE);
551 return "";
552 }
553
554 BlockSet blk;
555 blk.ParserAndInsert(blockPairs);
556 std::vector<uint8_t> block_buff(H_BLOCK_SIZE);
557 SHA256_CTX ctx;
558 SHA256_Init(&ctx);
559 std::vector<BlockPair>::iterator it = blk.Begin();
560 for (; it != blk.End(); ++it) {
561 if (lseek64(fd, static_cast<off64_t>(it->first * H_BLOCK_SIZE), SEEK_SET) == -1) {
562 LOG(ERROR) << "Failed to seek";
563 close(fd);
564 UPDATER_LAST_WORD(USCRIPT_ERROR_EXECUTE);
565 return "";
566 }
567 for (size_t i = it->first; i < it->second; ++i) {
568 if (!Utils::ReadFully(fd, block_buff.data(), H_BLOCK_SIZE)) {
569 LOG(ERROR) << "Failed to read";
570 close(fd);
571 UPDATER_LAST_WORD(USCRIPT_ERROR_EXECUTE);
572 return "";
573 }
574 SHA256_Update(&ctx, block_buff.data(), H_BLOCK_SIZE);
575 }
576 }
577 close(fd);
578
579 uint8_t digest[SHA256_DIGEST_LENGTH] = {0};
580 SHA256_Final(digest, &ctx);
581 return Utils::ConvertSha256Hex(digest, SHA256_DIGEST_LENGTH);
582 }
583
SetShaInfo(Uscript::UScriptContext & context,ShaInfo & shaInfo)584 int32_t UScriptInstructionShaCheck::SetShaInfo(Uscript::UScriptContext &context, ShaInfo &shaInfo)
585 {
586 int32_t ret = context.GetParam(1, shaInfo.blockPairs);
587 if (ret != USCRIPT_SUCCESS) {
588 LOG(ERROR) << "Failed to get param blockPairs";
589 UPDATER_LAST_WORD(USCRIPT_ERROR_EXECUTE);
590 return USCRIPT_ERROR_EXECUTE;
591 }
592
593 ret = context.GetParam(SHA_CHECK_SECOND, shaInfo.contrastSha);
594 if (ret != USCRIPT_SUCCESS) {
595 LOG(ERROR) << "Failed to get param contrastSha";
596 UPDATER_LAST_WORD(USCRIPT_ERROR_EXECUTE);
597 return USCRIPT_ERROR_EXECUTE;
598 }
599
600 // Only three parameters can be obtained for the upgrade package of an earlier version.
601 ret = context.GetParam(SHA_CHECK_TARGETPAIRS_INDEX, shaInfo.targetPairs);
602 if (ret != USCRIPT_SUCCESS) {
603 LOG(WARNING) << "Failed to get param targetPairs";
604 }
605
606 ret = context.GetParam(SHA_CHECK_TARGETSHA_INDEX, shaInfo.targetSha);
607 if (ret != USCRIPT_SUCCESS) {
608 LOG(WARNING) << "Failed to get param targetSha";
609 }
610
611 return USCRIPT_SUCCESS;
612 }
613
Execute(Uscript::UScriptEnv & env,Uscript::UScriptContext & context)614 int32_t UScriptInstructionShaCheck::Execute(Uscript::UScriptEnv &env, Uscript::UScriptContext &context)
615 {
616 int32_t paramCount = context.GetParamCount();
617 if (paramCount != SHA_CHECK_PARAMS && paramCount != SHA_CHECK_TARGET_PARAMS) {
618 LOG(ERROR) << "Invalid param";
619 UPDATER_LAST_WORD(USCRIPT_INVALID_PARAM);
620 return ReturnAndPushParam(USCRIPT_INVALID_PARAM, context);
621 }
622 if (env.IsRetry() && !Utils::CheckFaultInfo(VERIFY_FAILED_REBOOT)) {
623 return ReturnAndPushParam(USCRIPT_SUCCESS, context);
624 }
625
626 std::string partitionName;
627 int32_t ret = context.GetParam(0, partitionName);
628 if (ret != USCRIPT_SUCCESS) {
629 LOG(ERROR) << "Failed to get param";
630 UPDATER_LAST_WORD(USCRIPT_ERROR_EXECUTE);
631 return ReturnAndPushParam(USCRIPT_ERROR_EXECUTE, context);
632 }
633
634 ShaInfo shaInfo {};
635 ret = SetShaInfo(context, shaInfo);
636 if (ret != USCRIPT_SUCCESS) {
637 LOG(ERROR) << "Failed to set sha info";
638 return ReturnAndPushParam(ret, context);
639 }
640
641 auto devPath = GetBlockDeviceByMountPoint(partitionName);
642 LOG(INFO) << "UScriptInstructionShaCheck::dev path : " << devPath;
643 if (devPath.empty()) {
644 LOG(ERROR) << "cannot get block device of partition";
645 UPDATER_LAST_WORD(USCRIPT_ERROR_EXECUTE);
646 return ReturnAndPushParam(USCRIPT_ERROR_EXECUTE, context);
647 }
648 ret = ExecReadShaInfo(env, devPath, shaInfo);
649 return ReturnAndPushParam(ret, context);
650 }
651 }
652