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
16 #include "applypatch/block_set.h"
17 #include <linux/fs.h>
18 #include <sys/ioctl.h>
19 #include <openssl/sha.h>
20 #include <sys/stat.h>
21 #include <sys/types.h>
22 #include <unistd.h>
23 #include "applypatch/command.h"
24 #include "applypatch/store.h"
25 #include "applypatch/transfer_manager.h"
26 #include "log/log.h"
27 #include "patch/update_patch.h"
28 #include "securec.h"
29 #include "utils.h"
30
31 using namespace Updater;
32 using namespace Updater::Utils;
33
34 namespace Updater {
BlockSet(std::vector<BlockPair> &&pairs)35 BlockSet::BlockSet(std::vector<BlockPair> &&pairs)
36 {
37 blockSize_ = 0;
38 if (pairs.empty()) {
39 LOG(ERROR) << "Invalid block.";
40 return;
41 }
42
43 for (const auto &pair : pairs) {
44 if (!CheckReliablePair(pair)) {
45 return;
46 }
47 PushBack(pair);
48 }
49 }
50
CheckReliablePair(BlockPair pair)51 bool BlockSet::CheckReliablePair(BlockPair pair)
52 {
53 if (pair.first >= pair.second) {
54 LOG(ERROR) << "Invalid number of block size";
55 return false;
56 }
57 size_t size = pair.second - pair.first;
58 if (blockSize_ >= (SIZE_MAX - size)) {
59 LOG(ERROR) << "Block size overflow";
60 return false;
61 }
62 return true;
63 }
64
PushBack(BlockPair blockPair)65 void BlockSet::PushBack(BlockPair blockPair)
66 {
67 blocks_.push_back(std::move(blockPair));
68 blockSize_ += (blockPair.second - blockPair.first);
69 }
70
ClearBlocks()71 void BlockSet::ClearBlocks()
72 {
73 blockSize_ = 0;
74 blocks_.clear();
75 }
76
ParserAndInsert(const std::string &blockStr)77 bool BlockSet::ParserAndInsert(const std::string &blockStr)
78 {
79 if (blockStr == "") {
80 LOG(ERROR) << "Invalid argument, this argument is empty";
81 return false;
82 }
83 std::vector<std::string> pairs = SplitString(blockStr, ",");
84 return ParserAndInsert(pairs);
85 }
86
ParserAndInsert(const std::vector<std::string> &blockToken)87 bool BlockSet::ParserAndInsert(const std::vector<std::string> &blockToken)
88 {
89 ClearBlocks();
90 if (blockToken.empty()) {
91 LOG(ERROR) << "Invalid block token argument";
92 return false;
93 }
94 if (blockToken.size() < 3) { // 3:blockToken.size() < 3 means too small blocks_ in argument
95 LOG(ERROR) << "Too small blocks_ in argument";
96 return false;
97 }
98 // Get number of blockToken
99 unsigned long long int blockPairSize;
100 std::vector<std::string> bt = blockToken;
101 std::vector<std::string>::iterator bp = bt.begin();
102 blockPairSize = String2Int<unsigned long long int>(*bp, N_DEC);
103 if (blockPairSize == 0 || blockPairSize % 2 != 0 || // 2:Check whether blockPairSize is valid.
104 blockPairSize != bt.size() - 1) {
105 LOG(ERROR) << "Invalid number in block token";
106 return false;
107 }
108
109 while (++bp != bt.end()) {
110 size_t first = String2Int<size_t>(*bp++, N_DEC);
111 size_t second = String2Int<size_t>(*bp, N_DEC);
112 blocks_.push_back(BlockPair {
113 first, second
114 });
115 blockSize_ += (second - first);
116 }
117 return true;
118 }
119
Begin()120 std::vector<BlockPair>::iterator BlockSet::Begin()
121 {
122 return blocks_.begin();
123 }
124
End()125 std::vector<BlockPair>::iterator BlockSet::End()
126 {
127 return blocks_.end();
128 }
129
CBegin() const130 std::vector<BlockPair>::const_iterator BlockSet::CBegin() const
131 {
132 return blocks_.cbegin();
133 }
134
CEnd() const135 std::vector<BlockPair>::const_iterator BlockSet::CEnd() const
136 {
137 return blocks_.cend();
138 }
139
CrBegin() const140 std::vector<BlockPair>::const_reverse_iterator BlockSet::CrBegin() const
141 {
142 return blocks_.crbegin();
143 }
144
CrEnd() const145 std::vector<BlockPair>::const_reverse_iterator BlockSet::CrEnd() const
146 {
147 return blocks_.crend();
148 }
149
ReadDataFromBlock(int fd, std::vector<uint8_t> &buffer)150 size_t BlockSet::ReadDataFromBlock(int fd, std::vector<uint8_t> &buffer)
151 {
152 size_t pos = 0;
153 std::vector<BlockPair>::iterator it = blocks_.begin();
154 int ret;
155 for (; it != blocks_.end(); ++it) {
156 ret = lseek64(fd, static_cast<off64_t>(it->first * H_BLOCK_SIZE), SEEK_SET);
157 if (ret == -1) {
158 LOG(ERROR) << "Fail to seek";
159 return 0;
160 }
161 size_t size = (it->second - it->first) * H_BLOCK_SIZE;
162 if (!Utils::ReadFully(fd, buffer.data() + pos, size)) {
163 LOG(ERROR) << "Fail to read";
164 return 0;
165 }
166 pos += size;
167 }
168 return pos;
169 }
170
WriteDataToBlock(int fd, std::vector<uint8_t> &buffer)171 size_t BlockSet::WriteDataToBlock(int fd, std::vector<uint8_t> &buffer)
172 {
173 size_t pos = 0;
174 std::vector<BlockPair>::iterator it = blocks_.begin();
175 int ret = 0;
176 for (; it != blocks_.end(); ++it) {
177 off64_t offset = static_cast<off64_t>(it->first * H_BLOCK_SIZE);
178 size_t writeSize = (it->second - it->first) * H_BLOCK_SIZE;
179
180 ret = lseek64(fd, offset, SEEK_SET);
181 if (ret == -1) {
182 LOG(ERROR) << "BlockSet::WriteDataToBlock Fail to seek";
183 return 0;
184 }
185 if (Utils::WriteFully(fd, buffer.data() + pos, writeSize) == false) {
186 LOG(ERROR) << "Write data to block error, errno : " << errno;
187 return 0;
188 }
189 pos += writeSize;
190 }
191 if (fsync(fd) == -1) {
192 LOG(ERROR) << "Failed to fsync" << strerror(errno);
193 return 0;
194 }
195 return pos;
196 }
197
CountOfRanges() const198 size_t BlockSet::CountOfRanges() const
199 {
200 return blocks_.size();
201 }
202
TotalBlockSize() const203 size_t BlockSet::TotalBlockSize() const
204 {
205 return blockSize_;
206 }
207
VerifySha256(const std::vector<uint8_t> &buffer, const size_t size, const std::string &expected)208 int32_t BlockSet::VerifySha256(const std::vector<uint8_t> &buffer, const size_t size, const std::string &expected)
209 {
210 uint8_t digest[SHA256_DIGEST_LENGTH];
211 SHA256(buffer.data(), size * H_BLOCK_SIZE, digest);
212 std::string hexdigest = Utils::ConvertSha256Hex(digest, SHA256_DIGEST_LENGTH);
213 if (hexdigest == expected) {
214 return 0;
215 }
216 return -1;
217 }
218
IsTwoBlocksOverlap(const BlockSet &source, BlockSet &target)219 bool BlockSet::IsTwoBlocksOverlap(const BlockSet &source, BlockSet &target)
220 {
221 auto firstIter = source.CBegin();
222 for (; firstIter != source.CEnd(); ++firstIter) {
223 std::vector<BlockPair>::iterator secondIter = target.Begin();
224 for (; secondIter != target.End(); ++secondIter) {
225 if (!(secondIter->first >= firstIter->second ||
226 firstIter->first >= secondIter->second)) {
227 return true;
228 }
229 }
230 }
231 return false;
232 }
233
MoveBlock(std::vector<uint8_t> &target, const BlockSet& locations, const std::vector<uint8_t>& source)234 void BlockSet::MoveBlock(std::vector<uint8_t> &target, const BlockSet& locations,
235 const std::vector<uint8_t>& source)
236 {
237 const uint8_t *sd = source.data();
238 uint8_t *td = target.data();
239 size_t start = locations.TotalBlockSize();
240 for (auto it = locations.CrBegin(); it != locations.CrEnd(); it++) {
241 size_t blocks = it->second - it->first;
242 start -= blocks;
243 if (memmove_s(td + (it->first * H_BLOCK_SIZE), blocks * H_BLOCK_SIZE, sd + (start *
244 H_BLOCK_SIZE), blocks * H_BLOCK_SIZE) != EOK) {
245 LOG(ERROR) << "MoveBlock memmove_s failed!";
246 return;
247 }
248 }
249 }
250
LoadSourceBuffer(const Command &cmd, size_t &pos, std::vector<uint8_t> &sourceBuffer, bool &isOverlap, size_t &srcBlockSize)251 int32_t BlockSet::LoadSourceBuffer(const Command &cmd, size_t &pos, std::vector<uint8_t> &sourceBuffer,
252 bool &isOverlap, size_t &srcBlockSize)
253 {
254 std::string targetCmd = cmd.GetArgumentByPos(pos++);
255 std::string storeBase = cmd.GetTransferParams()->storeBase;
256 if (targetCmd != "-") {
257 BlockSet srcBlk;
258 srcBlk.ParserAndInsert(targetCmd);
259 isOverlap = IsTwoBlocksOverlap(srcBlk, *this);
260 // read source data
261 if (srcBlk.ReadDataFromBlock(cmd.GetFileDescriptor(), sourceBuffer) == 0) {
262 LOG(ERROR) << "ReadDataFromBlock failed";
263 return -1;
264 }
265 std::string nextArgv = cmd.GetArgumentByPos(pos++);
266 if (nextArgv == "") {
267 return 1;
268 }
269 BlockSet locations;
270 locations.ParserAndInsert(nextArgv);
271 MoveBlock(sourceBuffer, locations, sourceBuffer);
272 }
273
274 std::string lastArg = cmd.GetArgumentByPos(pos++);
275 while (lastArg != "") {
276 std::vector<std::string> tokens = SplitString(lastArg, ":");
277 if (tokens.size() != H_CMD_ARGS_LIMIT) {
278 LOG(ERROR) << "invalid parameter";
279 return -1;
280 }
281 std::vector<uint8_t> stash;
282 auto ret = Store::LoadDataFromStore(storeBase, tokens[H_ZERO_NUMBER], stash);
283 if (ret == -1) {
284 LOG(ERROR) << "Failed to load tokens";
285 return -1;
286 }
287 BlockSet locations;
288 locations.ParserAndInsert(tokens[1]);
289 MoveBlock(sourceBuffer, locations, stash);
290
291 lastArg = cmd.GetArgumentByPos(pos++);
292 }
293 return 1;
294 }
295
BlockVerify(const Command &cmd, std::vector<uint8_t> &buffer, const size_t size, const std::string srcHash, size_t &pos)296 __attribute__((weak)) int32_t BlockVerify(const Command &cmd, std::vector<uint8_t> &buffer,
297 const size_t size, const std::string srcHash, size_t &pos)
298 {
299 return -1;
300 }
301
302
LoadTargetBuffer(const Command &cmd, std::vector<uint8_t> &buffer, size_t &blockSize, size_t pos, std::string &srcHash)303 int32_t BlockSet::LoadTargetBuffer(const Command &cmd, std::vector<uint8_t> &buffer, size_t &blockSize,
304 size_t pos, std::string &srcHash)
305 {
306 bool isOverlap = false;
307 auto ret = LoadSourceBuffer(cmd, pos, buffer, isOverlap, blockSize);
308 if (ret != 1) {
309 return ret;
310 }
311 std::string storeBase = cmd.GetTransferParams()->storeBase;
312 std::string storePath = storeBase + "/" + srcHash;
313 struct stat storeStat {};
314 int res = stat(storePath.c_str(), &storeStat);
315 int32_t verifyRes = VerifySha256(buffer, blockSize, srcHash);
316 if (verifyRes != 0 && !cmd.GetTransferParams()->canWrite) {
317 return BlockVerify(cmd, buffer, blockSize, srcHash, pos);
318 }
319 if (verifyRes == 0) {
320 if (isOverlap && res != 0) {
321 cmd.GetTransferParams()->freeStash = srcHash;
322 ret = Store::WriteDataToStore(storeBase, srcHash, buffer, blockSize * H_BLOCK_SIZE);
323 if (ret != 0) {
324 LOG(ERROR) << "failed to stash overlapping source blocks";
325 return -1;
326 }
327 }
328 return 0;
329 }
330 if (Store::LoadDataFromStore(storeBase, srcHash, buffer) == 0) {
331 return 0;
332 }
333 return -1;
334 }
335
WriteZeroToBlock(int fd, bool isErase)336 int32_t BlockSet::WriteZeroToBlock(int fd, bool isErase)
337 {
338 std::vector<uint8_t> buffer;
339 buffer.resize(H_BLOCK_SIZE);
340 if (memset_s(buffer.data(), H_BLOCK_SIZE, 0, H_BLOCK_SIZE) != EOK) {
341 LOG(ERROR) << "memset_s failed";
342 return -1;
343 }
344
345 auto iter = blocks_.begin();
346 while (iter != blocks_.end()) {
347 off64_t offset = static_cast<off64_t>(iter->first * H_BLOCK_SIZE);
348 int ret = 0;
349
350 if (isErase) {
351 #ifndef UPDATER_UT
352 size_t writeSize = (iter->second - iter->first) * H_BLOCK_SIZE;
353 uint64_t arguments[2] = {static_cast<uint64_t>(offset), writeSize};
354 ret = ioctl(fd, BLKDISCARD, &arguments);
355 if (ret == -1 && errno != EOPNOTSUPP) {
356 LOG(ERROR) << "Error to write block set to memory";
357 return -1;
358 }
359 #endif
360 iter++;
361 continue;
362 }
363 ret = lseek64(fd, offset, SEEK_SET);
364 if (ret == -1) {
365 LOG(ERROR) << "BlockSet::WriteZeroToBlock Fail to seek";
366 return -1;
367 }
368 for (size_t pos = iter->first; pos < iter->second; pos++) {
369 if (Utils::WriteFully(fd, buffer.data(), H_BLOCK_SIZE)) {
370 continue;
371 }
372 if (errno == EIO) {
373 return 1;
374 }
375 LOG(ERROR) << "BlockSet::WriteZeroToBlock Write 0 to block error";
376 return -1;
377 }
378 iter++;
379 }
380 return 0;
381 }
382
WriteDiffToBlock(const Command &cmd, std::vector<uint8_t> &sourceBuffer, uint8_t *patchBuffer, size_t patchLength, bool isImgDiff)383 int32_t BlockSet::WriteDiffToBlock(const Command &cmd, std::vector<uint8_t> &sourceBuffer, uint8_t *patchBuffer,
384 size_t patchLength, bool isImgDiff)
385 {
386 size_t srcBuffSize = sourceBuffer.size();
387 if (isImgDiff) {
388 std::vector<uint8_t> empty;
389 UpdatePatch::PatchParam patchParam = {sourceBuffer.data(), srcBuffSize, patchBuffer, patchLength};
390 std::unique_ptr<BlockWriter> writer = std::make_unique<BlockWriter>(cmd.GetFileDescriptor(), *this);
391 if (writer.get() == nullptr) {
392 LOG(ERROR) << "Cannot create block writer, pkgdiff patch abort!";
393 return -1;
394 }
395 int32_t ret = UpdatePatch::UpdateApplyPatch::ApplyImagePatch(patchParam, empty,
396 [&](size_t start, const UpdatePatch::BlockBuffer &data, size_t size) -> int {
397 return (writer->Write(data.buffer, size, nullptr)) ? 0 : -1;
398 }, cmd.GetArgumentByPos(H_DIFF_CMD_ARGS_START + 1));
399 writer.reset();
400 if (ret != 0) {
401 LOG(ERROR) << "Fail to ApplyImagePatch";
402 return -1;
403 }
404 } else {
405 LOG(DEBUG) << "Run bsdiff patch.";
406 UpdatePatch::PatchBuffer patchInfo = {patchBuffer, 0, patchLength};
407 std::unique_ptr<BlockWriter> writer = std::make_unique<BlockWriter>(cmd.GetFileDescriptor(), *this);
408 if (writer.get() == nullptr) {
409 LOG(ERROR) << "Cannot create block writer, pkgdiff patch abort!";
410 return -1;
411 }
412 auto ret = UpdatePatch::UpdateApplyPatch::ApplyBlockPatch(patchInfo, {sourceBuffer.data(), srcBuffSize},
413 [&](size_t start, const UpdatePatch::BlockBuffer &data, size_t size) -> int {
414 return (writer->Write(data.buffer, size, nullptr)) ? 0 : -1;
415 }, cmd.GetArgumentByPos(H_DIFF_CMD_ARGS_START + 1));
416 writer.reset();
417 if (ret != 0) {
418 LOG(ERROR) << "Fail to ApplyBlockPatch";
419 return -1;
420 }
421 }
422 if (fsync(cmd.GetFileDescriptor()) == -1) {
423 LOG(ERROR) << "Failed to sync restored data";
424 return -1;
425 }
426 return 0;
427 }
428 } // namespace Updater
429