1 /*
2  * Copyright (C) 2019 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "fuse_provider.h"
18 
19 #include <errno.h>
20 #include <fcntl.h>
21 #include <inttypes.h>
22 #include <stdio.h>
23 #include <string.h>
24 #include <sys/stat.h>
25 #include <unistd.h>
26 
27 #include <functional>
28 
29 #include <android-base/file.h>
30 
31 #include "fuse_sideload.h"
32 
FuseFileDataProvider(const std::string & path,uint32_t block_size)33 FuseFileDataProvider::FuseFileDataProvider(const std::string& path, uint32_t block_size) {
34   struct stat sb;
35   if (stat(path.c_str(), &sb) == -1) {
36     fprintf(stderr, "failed to stat %s: %s\n", path.c_str(), strerror(errno));
37     return;
38   }
39 
40   fd_.reset(open(path.c_str(), O_RDONLY));
41   if (fd_ == -1) {
42     fprintf(stderr, "failed to open %s: %s\n", path.c_str(), strerror(errno));
43     return;
44   }
45   file_size_ = sb.st_size;
46   fuse_block_size_ = block_size;
47 }
48 
ReadBlockAlignedData(uint8_t * buffer,uint32_t fetch_size,uint32_t start_block) const49 bool FuseFileDataProvider::ReadBlockAlignedData(uint8_t* buffer, uint32_t fetch_size,
50                                                 uint32_t start_block) const {
51   uint64_t offset = static_cast<uint64_t>(start_block) * fuse_block_size_;
52   if (fetch_size > file_size_ || offset > file_size_ - fetch_size) {
53     fprintf(stderr,
54             "Out of bound read, start block: %" PRIu32 ", fetch size: %" PRIu32
55             ", file size %" PRIu64 "\n",
56             start_block, fetch_size, file_size_);
57     return false;
58   }
59 
60   if (!android::base::ReadFullyAtOffset(fd_, buffer, fetch_size, offset)) {
61     fprintf(stderr, "Failed to read fetch size: %" PRIu32 " bytes data at offset %" PRIu64 ": %s\n",
62             fetch_size, offset, strerror(errno));
63     return false;
64   }
65 
66   return true;
67 }
68 
Close()69 void FuseFileDataProvider::Close() {
70   fd_.reset();
71 }
72