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 
LoadTargetBuffer(const Command & cmd,std::vector<uint8_t> & buffer,size_t & blockSize,size_t pos,std::string & srcHash)296 int32_t BlockSet::LoadTargetBuffer(const Command &cmd, std::vector<uint8_t> &buffer, size_t &blockSize,
297     size_t pos, std::string &srcHash)
298 {
299     bool isOverlap = false;
300     auto ret = LoadSourceBuffer(cmd, pos, buffer, isOverlap, blockSize);
301     if (ret != 1) {
302         return ret;
303     }
304     std::string storeBase = cmd.GetTransferParams()->storeBase;
305     std::string storePath = storeBase + "/" + srcHash;
306     struct stat storeStat {};
307     int res = stat(storePath.c_str(), &storeStat);
308     if (VerifySha256(buffer, blockSize, srcHash) == 0) {
309         if (isOverlap && res != 0) {
310             cmd.GetTransferParams()->freeStash = srcHash;
311             ret = Store::WriteDataToStore(storeBase, srcHash, buffer, blockSize * H_BLOCK_SIZE);
312             if (ret != 0) {
313                 LOG(ERROR) << "failed to stash overlapping source blocks";
314                 return -1;
315             }
316         }
317         return 0;
318     }
319     if (Store::LoadDataFromStore(storeBase, srcHash, buffer) == 0) {
320         return 0;
321     }
322     return -1;
323 }
324 
WriteZeroToBlock(int fd,bool isErase)325 int32_t BlockSet::WriteZeroToBlock(int fd, bool isErase)
326 {
327     std::vector<uint8_t> buffer;
328     buffer.resize(H_BLOCK_SIZE);
329     if (memset_s(buffer.data(), H_BLOCK_SIZE, 0, H_BLOCK_SIZE) != EOK) {
330         LOG(ERROR) << "memset_s failed";
331         return -1;
332     }
333 
334     auto iter = blocks_.begin();
335     while (iter != blocks_.end()) {
336         off64_t offset = static_cast<off64_t>(iter->first * H_BLOCK_SIZE);
337         int ret = 0;
338 
339         if (isErase) {
340 #ifndef UPDATER_UT
341             size_t writeSize = (iter->second - iter->first) * H_BLOCK_SIZE;
342             uint64_t arguments[2] = {static_cast<uint64_t>(offset), writeSize};
343             ret = ioctl(fd, BLKDISCARD, &arguments);
344             if (ret == -1 && errno != EOPNOTSUPP) {
345                 LOG(ERROR) << "Error to write block set to memory";
346                 return -1;
347             }
348 #endif
349             iter++;
350             continue;
351         }
352         ret = lseek64(fd, offset, SEEK_SET);
353         if (ret == -1) {
354             LOG(ERROR) << "BlockSet::WriteZeroToBlock Fail to seek";
355             return -1;
356         }
357         for (size_t pos = iter->first; pos < iter->second; pos++) {
358             if (Utils::WriteFully(fd, buffer.data(), H_BLOCK_SIZE)) {
359                 continue;
360             }
361             if (errno == EIO) {
362                 return 1;
363             }
364             LOG(ERROR) << "BlockSet::WriteZeroToBlock Write 0 to block error";
365             return -1;
366         }
367         iter++;
368     }
369     return 0;
370 }
371 
WriteDiffToBlock(const Command & cmd,std::vector<uint8_t> & sourceBuffer,uint8_t * patchBuffer,size_t patchLength,bool isImgDiff)372 int32_t BlockSet::WriteDiffToBlock(const Command &cmd, std::vector<uint8_t> &sourceBuffer, uint8_t *patchBuffer,
373                                    size_t patchLength, bool isImgDiff)
374 {
375     size_t srcBuffSize =  sourceBuffer.size();
376     if (isImgDiff) {
377         std::vector<uint8_t> empty;
378         UpdatePatch::PatchParam patchParam = {sourceBuffer.data(), srcBuffSize, patchBuffer, patchLength};
379         std::unique_ptr<BlockWriter> writer = std::make_unique<BlockWriter>(cmd.GetFileDescriptor(), *this);
380         if (writer.get() == nullptr) {
381             LOG(ERROR) << "Cannot create block writer, pkgdiff patch abort!";
382             return -1;
383         }
384         int32_t ret = UpdatePatch::UpdateApplyPatch::ApplyImagePatch(patchParam, empty,
385             [&](size_t start, const UpdatePatch::BlockBuffer &data, size_t size) -> int {
386                 return (writer->Write(data.buffer, size, nullptr)) ? 0 : -1;
387             }, cmd.GetArgumentByPos(H_DIFF_CMD_ARGS_START + 1));
388         writer.reset();
389         if (ret != 0) {
390             LOG(ERROR) << "Fail to ApplyImagePatch";
391             return -1;
392         }
393     } else {
394         LOG(DEBUG) << "Run bsdiff patch.";
395         UpdatePatch::PatchBuffer patchInfo = {patchBuffer, 0, patchLength};
396         std::unique_ptr<BlockWriter> writer = std::make_unique<BlockWriter>(cmd.GetFileDescriptor(), *this);
397         if (writer.get() == nullptr) {
398             LOG(ERROR) << "Cannot create block writer, pkgdiff patch abort!";
399             return -1;
400         }
401         auto ret = UpdatePatch::UpdateApplyPatch::ApplyBlockPatch(patchInfo, {sourceBuffer.data(), srcBuffSize},
402             [&](size_t start, const UpdatePatch::BlockBuffer &data, size_t size) -> int {
403                 return (writer->Write(data.buffer, size, nullptr)) ? 0 : -1;
404             }, cmd.GetArgumentByPos(H_DIFF_CMD_ARGS_START + 1));
405         writer.reset();
406         if (ret != 0) {
407             LOG(ERROR) << "Fail to ApplyBlockPatch";
408             return -1;
409         }
410     }
411     if (fsync(cmd.GetFileDescriptor()) == -1) {
412         LOG(ERROR) << "Failed to sync restored data";
413         return -1;
414     }
415     return 0;
416 }
417 } // namespace Updater
418