1 // Copyright (C) 2019 The Android Open Source Project
2 //
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 "utility.h"
16 
17 #include <errno.h>
18 #include <time.h>
19 
20 #include <iomanip>
21 #include <sstream>
22 
23 #include <android-base/file.h>
24 #include <android-base/logging.h>
25 #include <android-base/strings.h>
26 #include <fs_mgr/roots.h>
27 
28 using android::dm::kSectorSize;
29 using android::fiemap::FiemapStatus;
30 using android::fs_mgr::EnsurePathMounted;
31 using android::fs_mgr::EnsurePathUnmounted;
32 using android::fs_mgr::Fstab;
33 using android::fs_mgr::GetEntryForPath;
34 using android::fs_mgr::MetadataBuilder;
35 using android::fs_mgr::Partition;
36 using android::fs_mgr::ReadDefaultFstab;
37 using google::protobuf::RepeatedPtrField;
38 
39 namespace android {
40 namespace snapshot {
41 
Release()42 void AutoDevice::Release() {
43     name_.clear();
44 }
45 
~AutoDeviceList()46 AutoDeviceList::~AutoDeviceList() {
47     // Destroy devices in the reverse order because newer devices may have dependencies
48     // on older devices.
49     for (auto it = devices_.rbegin(); it != devices_.rend(); ++it) {
50         it->reset();
51     }
52 }
53 
Release()54 void AutoDeviceList::Release() {
55     for (auto&& p : devices_) {
56         p->Release();
57     }
58 }
59 
~AutoUnmapDevice()60 AutoUnmapDevice::~AutoUnmapDevice() {
61     if (name_.empty()) return;
62     if (!dm_->DeleteDeviceIfExists(name_)) {
63         LOG(ERROR) << "Failed to auto unmap device " << name_;
64     }
65 }
66 
~AutoUnmapImage()67 AutoUnmapImage::~AutoUnmapImage() {
68     if (name_.empty()) return;
69     if (!images_->UnmapImageIfExists(name_)) {
70         LOG(ERROR) << "Failed to auto unmap cow image " << name_;
71     }
72 }
73 
ListPartitionsWithSuffix(MetadataBuilder * builder,const std::string & suffix)74 std::vector<Partition*> ListPartitionsWithSuffix(MetadataBuilder* builder,
75                                                  const std::string& suffix) {
76     std::vector<Partition*> ret;
77     for (const auto& group : builder->ListGroups()) {
78         for (auto* partition : builder->ListPartitionsInGroup(group)) {
79             if (!base::EndsWith(partition->name(), suffix)) {
80                 continue;
81             }
82             ret.push_back(partition);
83         }
84     }
85     return ret;
86 }
87 
~AutoDeleteSnapshot()88 AutoDeleteSnapshot::~AutoDeleteSnapshot() {
89     if (!name_.empty() && !manager_->DeleteSnapshot(lock_, name_)) {
90         LOG(ERROR) << "Failed to auto delete snapshot " << name_;
91     }
92 }
93 
InitializeCow(const std::string & device)94 Return InitializeCow(const std::string& device) {
95     // When the kernel creates a persistent dm-snapshot, it requires a CoW file
96     // to store the modifications. The kernel interface does not specify how
97     // the CoW is used, and there is no standard associated.
98     // By looking at the current implementation, the CoW file is treated as:
99     // - a _NEW_ snapshot if its first 32 bits are zero, so the newly created
100     // dm-snapshot device will look like a perfect copy of the origin device;
101     // - an _EXISTING_ snapshot if the first 32 bits are equal to a
102     // kernel-specified magic number and the CoW file metadata is set as valid,
103     // so it can be used to resume the last state of a snapshot device;
104     // - an _INVALID_ snapshot otherwise.
105     // To avoid zero-filling the whole CoW file when a new dm-snapshot is
106     // created, here we zero-fill only the first chunk to be compliant with
107     // lvm.
108     constexpr ssize_t kDmSnapZeroFillSize = kSectorSize * kSnapshotChunkSize;
109 
110     std::vector<uint8_t> zeros(kDmSnapZeroFillSize, 0);
111     android::base::unique_fd fd(open(device.c_str(), O_WRONLY | O_BINARY));
112     if (fd < 0) {
113         PLOG(ERROR) << "Can't open COW device: " << device;
114         return Return(FiemapStatus::FromErrno(errno));
115     }
116 
117     LOG(INFO) << "Zero-filling COW device: " << device;
118     if (!android::base::WriteFully(fd, zeros.data(), kDmSnapZeroFillSize)) {
119         PLOG(ERROR) << "Can't zero-fill COW device for " << device;
120         return Return(FiemapStatus::FromErrno(errno));
121     }
122     return Return::Ok();
123 }
124 
New(const std::string & path)125 std::unique_ptr<AutoUnmountDevice> AutoUnmountDevice::New(const std::string& path) {
126     Fstab fstab;
127     if (!ReadDefaultFstab(&fstab)) {
128         LOG(ERROR) << "Cannot read default fstab";
129         return nullptr;
130     }
131 
132     if (GetEntryForPath(&fstab, path) == nullptr) {
133         LOG(INFO) << "EnsureMetadataMounted can't find entry for " << path << ", skipping";
134         return std::unique_ptr<AutoUnmountDevice>(new AutoUnmountDevice("", {}));
135     }
136 
137     if (!EnsurePathMounted(&fstab, path)) {
138         LOG(ERROR) << "Cannot mount " << path;
139         return nullptr;
140     }
141     return std::unique_ptr<AutoUnmountDevice>(new AutoUnmountDevice(path, std::move(fstab)));
142 }
143 
~AutoUnmountDevice()144 AutoUnmountDevice::~AutoUnmountDevice() {
145     if (name_.empty()) return;
146     if (!EnsurePathUnmounted(&fstab_, name_)) {
147         LOG(ERROR) << "Cannot unmount " << name_;
148     }
149 }
150 
WriteStringToFileAtomic(const std::string & content,const std::string & path)151 bool WriteStringToFileAtomic(const std::string& content, const std::string& path) {
152     std::string tmp_path = path + ".tmp";
153     if (!android::base::WriteStringToFile(content, tmp_path)) {
154         return false;
155     }
156     if (rename(tmp_path.c_str(), path.c_str()) == -1) {
157         PLOG(ERROR) << "rename failed from " << tmp_path << " to " << path;
158         return false;
159     }
160     return true;
161 }
162 
operator <<(std::ostream & os,const Now &)163 std::ostream& operator<<(std::ostream& os, const Now&) {
164     struct tm now;
165     time_t t = time(nullptr);
166     localtime_r(&t, &now);
167     return os << std::put_time(&now, "%Y%m%d-%H%M%S");
168 }
169 
AppendExtent(RepeatedPtrField<chromeos_update_engine::Extent> * extents,uint64_t start_block,uint64_t num_blocks)170 void AppendExtent(RepeatedPtrField<chromeos_update_engine::Extent>* extents, uint64_t start_block,
171                   uint64_t num_blocks) {
172     if (extents->size() > 0) {
173         auto last_extent = extents->rbegin();
174         auto next_block = last_extent->start_block() + last_extent->num_blocks();
175         if (start_block == next_block) {
176             last_extent->set_num_blocks(last_extent->num_blocks() + num_blocks);
177             return;
178         }
179     }
180     auto* new_extent = extents->Add();
181     new_extent->set_start_block(start_block);
182     new_extent->set_num_blocks(num_blocks);
183 }
184 
185 }  // namespace snapshot
186 }  // namespace android
187