1 /*
2  * Copyright (C) 2016 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 <bootloader_message/bootloader_message.h>
18 
19 #include <errno.h>
20 #include <fcntl.h>
21 #include <string.h>
22 
23 #include <optional>
24 #include <string>
25 #include <string_view>
26 #include <vector>
27 
28 #include <android-base/file.h>
29 #include <android-base/hex.h>
30 #include <android-base/logging.h>
31 #include <android-base/properties.h>
32 #include <android-base/stringprintf.h>
33 #include <android-base/unique_fd.h>
34 #include <fstab/fstab.h>
35 
36 #ifndef __ANDROID__
37 #include <cutils/memory.h>  // for strlcpy
38 #endif
39 
40 using android::fs_mgr::Fstab;
41 using android::fs_mgr::ReadDefaultFstab;
42 
43 static std::optional<std::string> g_misc_device_for_test;
44 
45 // Exposed for test purpose.
SetMiscBlockDeviceForTest(std::string_view misc_device)46 void SetMiscBlockDeviceForTest(std::string_view misc_device) {
47   g_misc_device_for_test = misc_device;
48 }
49 
get_misc_blk_device(std::string * err)50 std::string get_misc_blk_device(std::string* err) {
51   if (g_misc_device_for_test.has_value() && !g_misc_device_for_test->empty()) {
52     return *g_misc_device_for_test;
53   }
54   Fstab fstab;
55   if (!ReadDefaultFstab(&fstab)) {
56     *err = "failed to read default fstab";
57     return "";
58   }
59   for (const auto& entry : fstab) {
60     if (entry.mount_point == "/misc") {
61       return entry.blk_device;
62     }
63   }
64 
65   *err = "failed to find /misc partition";
66   return "";
67 }
68 
69 // In recovery mode, recovery can get started and try to access the misc
70 // device before the kernel has actually created it.
wait_for_device(const std::string & blk_device,std::string * err)71 static bool wait_for_device(const std::string& blk_device, std::string* err) {
72   int tries = 0;
73   int ret;
74   err->clear();
75   do {
76     ++tries;
77     struct stat buf;
78     ret = stat(blk_device.c_str(), &buf);
79     if (ret == -1) {
80       *err += android::base::StringPrintf("failed to stat %s try %d: %s\n",
81                                           blk_device.c_str(), tries, strerror(errno));
82       sleep(1);
83     }
84   } while (ret && tries < 10);
85 
86   if (ret) {
87     *err += android::base::StringPrintf("failed to stat %s\n", blk_device.c_str());
88   }
89   return ret == 0;
90 }
91 
read_misc_partition(void * p,size_t size,const std::string & misc_blk_device,size_t offset,std::string * err)92 static bool read_misc_partition(void* p, size_t size, const std::string& misc_blk_device,
93                                 size_t offset, std::string* err) {
94   if (!wait_for_device(misc_blk_device, err)) {
95     return false;
96   }
97   android::base::unique_fd fd(open(misc_blk_device.c_str(), O_RDONLY));
98   if (fd == -1) {
99     *err = android::base::StringPrintf("failed to open %s: %s", misc_blk_device.c_str(),
100                                        strerror(errno));
101     return false;
102   }
103   if (lseek(fd, static_cast<off_t>(offset), SEEK_SET) != static_cast<off_t>(offset)) {
104     *err = android::base::StringPrintf("failed to lseek %s: %s", misc_blk_device.c_str(),
105                                        strerror(errno));
106     return false;
107   }
108   if (!android::base::ReadFully(fd, p, size)) {
109     *err = android::base::StringPrintf("failed to read %s: %s", misc_blk_device.c_str(),
110                                        strerror(errno));
111     return false;
112   }
113   return true;
114 }
115 
write_misc_partition(const void * p,size_t size,const std::string & misc_blk_device,size_t offset,std::string * err)116 bool write_misc_partition(const void* p, size_t size, const std::string& misc_blk_device,
117                           size_t offset, std::string* err) {
118   android::base::unique_fd fd(open(misc_blk_device.c_str(), O_WRONLY));
119   if (fd == -1) {
120     *err = android::base::StringPrintf("failed to open %s: %s", misc_blk_device.c_str(),
121                                        strerror(errno));
122     return false;
123   }
124   if (lseek(fd, static_cast<off_t>(offset), SEEK_SET) != static_cast<off_t>(offset)) {
125     *err = android::base::StringPrintf("failed to lseek %s: %s", misc_blk_device.c_str(),
126                                        strerror(errno));
127     return false;
128   }
129   if (!android::base::WriteFully(fd, p, size)) {
130     *err = android::base::StringPrintf("failed to write %s: %s", misc_blk_device.c_str(),
131                                        strerror(errno));
132     return false;
133   }
134   if (fsync(fd) == -1) {
135     *err = android::base::StringPrintf("failed to fsync %s: %s", misc_blk_device.c_str(),
136                                        strerror(errno));
137     return false;
138   }
139   return true;
140 }
141 
get_bootloader_message_blk_device(std::string * err)142 std::string get_bootloader_message_blk_device(std::string* err) {
143   std::string misc_blk_device = get_misc_blk_device(err);
144   if (misc_blk_device.empty()) return "";
145   if (!wait_for_device(misc_blk_device, err)) return "";
146   return misc_blk_device;
147 }
148 
read_bootloader_message_from(bootloader_message * boot,const std::string & misc_blk_device,std::string * err)149 bool read_bootloader_message_from(bootloader_message* boot, const std::string& misc_blk_device,
150                                   std::string* err) {
151   return read_misc_partition(boot, sizeof(*boot), misc_blk_device,
152                              BOOTLOADER_MESSAGE_OFFSET_IN_MISC, err);
153 }
154 
read_bootloader_message(bootloader_message * boot,std::string * err)155 bool read_bootloader_message(bootloader_message* boot, std::string* err) {
156   std::string misc_blk_device = get_misc_blk_device(err);
157   if (misc_blk_device.empty()) {
158     return false;
159   }
160   return read_bootloader_message_from(boot, misc_blk_device, err);
161 }
162 
write_bootloader_message_to(const bootloader_message & boot,const std::string & misc_blk_device,std::string * err)163 bool write_bootloader_message_to(const bootloader_message& boot, const std::string& misc_blk_device,
164                                  std::string* err) {
165   return write_misc_partition(&boot, sizeof(boot), misc_blk_device,
166                               BOOTLOADER_MESSAGE_OFFSET_IN_MISC, err);
167 }
168 
write_bootloader_message(const bootloader_message & boot,std::string * err)169 bool write_bootloader_message(const bootloader_message& boot, std::string* err) {
170   std::string misc_blk_device = get_misc_blk_device(err);
171   if (misc_blk_device.empty()) {
172     return false;
173   }
174   return write_bootloader_message_to(boot, misc_blk_device, err);
175 }
176 
clear_bootloader_message(std::string * err)177 bool clear_bootloader_message(std::string* err) {
178   bootloader_message boot = {};
179   LOG(INFO) << "Clearing BCB";
180   return write_bootloader_message(boot, err);
181 }
182 
write_bootloader_message(const std::vector<std::string> & options,std::string * err)183 bool write_bootloader_message(const std::vector<std::string>& options, std::string* err) {
184   bootloader_message boot = {};
185   update_bootloader_message_in_struct(&boot, options);
186 
187   return write_bootloader_message(boot, err);
188 }
189 
write_bootloader_message_to(const std::vector<std::string> & options,const std::string & misc_blk_device,std::string * err)190 bool write_bootloader_message_to(const std::vector<std::string>& options,
191                                  const std::string& misc_blk_device, std::string* err) {
192   bootloader_message boot = {};
193   update_bootloader_message_in_struct(&boot, options);
194 
195   return write_bootloader_message_to(boot, misc_blk_device, err);
196 }
197 
update_bootloader_message(const std::vector<std::string> & options,std::string * err)198 bool update_bootloader_message(const std::vector<std::string>& options, std::string* err) {
199   bootloader_message boot{};
200   if (!read_bootloader_message(&boot, err)) {
201     return false;
202   }
203   update_bootloader_message_in_struct(&boot, options);
204   LOG(INFO) << "Writing BCB " << boot.command << " " << boot.recovery;
205 
206   return write_bootloader_message(boot, err);
207 }
208 
update_bootloader_message_in_struct(bootloader_message * boot,const std::vector<std::string> & options)209 bool update_bootloader_message_in_struct(bootloader_message* boot,
210                                          const std::vector<std::string>& options) {
211   if (!boot) return false;
212   // Replace the command & recovery fields.
213   memset(boot->command, 0, sizeof(boot->command));
214   memset(boot->recovery, 0, sizeof(boot->recovery));
215 
216   strlcpy(boot->command, "boot-recovery", sizeof(boot->command));
217 
218   std::string recovery = "recovery\n";
219   for (const auto& s : options) {
220     recovery += s;
221     if (s.back() != '\n') {
222       recovery += '\n';
223     }
224   }
225   strlcpy(boot->recovery, recovery.c_str(), sizeof(boot->recovery));
226   return true;
227 }
228 
write_reboot_bootloader(std::string * err)229 bool write_reboot_bootloader(std::string* err) {
230   bootloader_message boot{};
231   if (!read_bootloader_message(&boot, err)) {
232     return false;
233   }
234   if (boot.command[0] != '\0') {
235     *err = "Bootloader command pending.";
236     return false;
237   }
238   strlcpy(boot.command, "bootonce-bootloader", sizeof(boot.command));
239   LOG(INFO) << "Writing BCB cmd: " << boot.command << " args: " << boot.recovery;
240   return write_bootloader_message(boot, err);
241 }
242 
read_wipe_package(std::string * package_data,size_t size,std::string * err)243 bool read_wipe_package(std::string* package_data, size_t size, std::string* err) {
244   std::string misc_blk_device = get_misc_blk_device(err);
245   if (misc_blk_device.empty()) {
246     return false;
247   }
248   package_data->resize(size);
249   return read_misc_partition(&(*package_data)[0], size, misc_blk_device,
250                              WIPE_PACKAGE_OFFSET_IN_MISC, err);
251 }
252 
write_wipe_package(const std::string & package_data,std::string * err)253 bool write_wipe_package(const std::string& package_data, std::string* err) {
254   std::string misc_blk_device = get_misc_blk_device(err);
255   if (misc_blk_device.empty()) {
256     return false;
257   }
258   static constexpr size_t kMaximumWipePackageSize =
259       SYSTEM_SPACE_OFFSET_IN_MISC - WIPE_PACKAGE_OFFSET_IN_MISC;
260   if (package_data.size() > kMaximumWipePackageSize) {
261     *err = "Wipe package size " + std::to_string(package_data.size()) + " exceeds " +
262            std::to_string(kMaximumWipePackageSize) + " bytes";
263     return false;
264   }
265   return write_misc_partition(package_data.data(), package_data.size(), misc_blk_device,
266                               WIPE_PACKAGE_OFFSET_IN_MISC, err);
267 }
268 
ValidateSystemSpaceRegion(size_t offset,size_t size,std::string * err)269 static bool ValidateSystemSpaceRegion(size_t offset, size_t size, std::string* err) {
270   if (size <= SYSTEM_SPACE_SIZE_IN_MISC && offset <= (SYSTEM_SPACE_SIZE_IN_MISC - size)) {
271     return true;
272   }
273   *err = android::base::StringPrintf("Out of bound access (offset %zu size %zu)", offset, size);
274   return false;
275 }
276 
ReadMiscPartitionSystemSpace(void * data,size_t size,size_t offset,std::string * err)277 static bool ReadMiscPartitionSystemSpace(void* data, size_t size, size_t offset, std::string* err) {
278   if (!ValidateSystemSpaceRegion(offset, size, err)) {
279     return false;
280   }
281   auto misc_blk_device = get_misc_blk_device(err);
282   if (misc_blk_device.empty()) {
283     return false;
284   }
285   return read_misc_partition(data, size, misc_blk_device, SYSTEM_SPACE_OFFSET_IN_MISC + offset,
286                              err);
287 }
288 
WriteMiscPartitionSystemSpace(const void * data,size_t size,size_t offset,std::string * err)289 static bool WriteMiscPartitionSystemSpace(const void* data, size_t size, size_t offset,
290                                           std::string* err) {
291   if (!ValidateSystemSpaceRegion(offset, size, err)) {
292     return false;
293   }
294   auto misc_blk_device = get_misc_blk_device(err);
295   if (misc_blk_device.empty()) {
296     return false;
297   }
298   return write_misc_partition(data, size, misc_blk_device, SYSTEM_SPACE_OFFSET_IN_MISC + offset,
299                               err);
300 }
301 
ReadMiscVirtualAbMessage(misc_virtual_ab_message * message,std::string * err)302 bool ReadMiscVirtualAbMessage(misc_virtual_ab_message* message, std::string* err) {
303   return ReadMiscPartitionSystemSpace(message, sizeof(*message),
304                                       offsetof(misc_system_space_layout, virtual_ab_message), err);
305 }
306 
WriteMiscVirtualAbMessage(const misc_virtual_ab_message & message,std::string * err)307 bool WriteMiscVirtualAbMessage(const misc_virtual_ab_message& message, std::string* err) {
308   return WriteMiscPartitionSystemSpace(&message, sizeof(message),
309                                        offsetof(misc_system_space_layout, virtual_ab_message), err);
310 }
311 
ReadMiscMemtagMessage(misc_memtag_message * message,std::string * err)312 bool ReadMiscMemtagMessage(misc_memtag_message* message, std::string* err) {
313   return ReadMiscPartitionSystemSpace(message, sizeof(*message),
314                                       offsetof(misc_system_space_layout, memtag_message), err);
315 }
316 
WriteMiscMemtagMessage(const misc_memtag_message & message,std::string * err)317 bool WriteMiscMemtagMessage(const misc_memtag_message& message, std::string* err) {
318   return WriteMiscPartitionSystemSpace(&message, sizeof(message),
319                                        offsetof(misc_system_space_layout, memtag_message), err);
320 }
321 
ReadMiscKcmdlineMessage(misc_kcmdline_message * message,std::string * err)322 bool ReadMiscKcmdlineMessage(misc_kcmdline_message* message, std::string* err) {
323   return ReadMiscPartitionSystemSpace(message, sizeof(*message),
324                                       offsetof(misc_system_space_layout, kcmdline_message), err);
325 }
326 
WriteMiscKcmdlineMessage(const misc_kcmdline_message & message,std::string * err)327 bool WriteMiscKcmdlineMessage(const misc_kcmdline_message& message, std::string* err) {
328   return WriteMiscPartitionSystemSpace(&message, sizeof(message),
329                                        offsetof(misc_system_space_layout, kcmdline_message), err);
330 }
331 
ReadMiscControlMessage(misc_control_message * message,std::string * err)332 bool ReadMiscControlMessage(misc_control_message* message, std::string* err) {
333   return ReadMiscPartitionSystemSpace(message, sizeof(*message),
334                                       offsetof(misc_system_space_layout, control_message), err);
335 }
336 
WriteMiscControlMessage(const misc_control_message & message,std::string * err)337 bool WriteMiscControlMessage(const misc_control_message& message, std::string* err) {
338   return WriteMiscPartitionSystemSpace(&message, sizeof(message),
339                                        offsetof(misc_system_space_layout, control_message), err);
340 }
341 
CheckReservedSystemSpaceEmpty(bool * empty,std::string * err)342 bool CheckReservedSystemSpaceEmpty(bool* empty, std::string* err) {
343   constexpr size_t kReservedSize = SYSTEM_SPACE_SIZE_IN_MISC - sizeof(misc_system_space_layout);
344 
345   uint8_t space[kReservedSize];
346   if (!ReadMiscPartitionSystemSpace(&space, kReservedSize, sizeof(misc_system_space_layout), err)) {
347     return false;
348   }
349 
350   *empty = space[0] == 0 && 0 == memcmp(space, space + 1, kReservedSize - 1);
351 
352   if (!*empty) {
353     *err = android::base::HexString(space, kReservedSize);
354   }
355 
356   return true;
357 }
358 
write_reboot_bootloader(void)359 extern "C" bool write_reboot_bootloader(void) {
360   std::string err;
361   return write_reboot_bootloader(&err);
362 }
363 
write_bootloader_message(const char * options)364 extern "C" bool write_bootloader_message(const char* options) {
365   std::string err;
366   return write_bootloader_message({options}, &err);
367 }
368