blob: 3799d1fe1530272b0528a64ac5f54c20bcd4d0cc [file] [log] [blame]
Hridya Valsarajudea91b42018-07-17 11:14:01 -07001/*
2 * Copyright (C) 2018 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 "commands.h"
18
Yifan Honga4eb4752021-02-16 19:37:21 -080019#include <inttypes.h>
Hridya Valsarajudea91b42018-07-17 11:14:01 -070020#include <sys/socket.h>
21#include <sys/un.h>
22
David Anderson220ddb12019-10-31 18:02:41 -070023#include <unordered_set>
24
Hridya Valsarajudea91b42018-07-17 11:14:01 -070025#include <android-base/logging.h>
26#include <android-base/parseint.h>
27#include <android-base/properties.h>
28#include <android-base/stringprintf.h>
29#include <android-base/strings.h>
30#include <android-base/unique_fd.h>
David Andersonab8f4662019-10-21 16:45:59 -070031#include <android/hardware/boot/1.1/IBootControl.h>
Hridya Valsarajudea91b42018-07-17 11:14:01 -070032#include <cutils/android_reboot.h>
David Anderson12211d12018-07-24 15:21:20 -070033#include <ext4_utils/wipe.h>
David Anderson5cbd2e42018-09-27 10:53:04 -070034#include <fs_mgr.h>
David Anderson2ffc31b2020-03-23 23:43:45 -070035#include <fs_mgr/roots.h>
David Anderson1d504e32019-01-15 14:38:20 -080036#include <libgsi/libgsi.h>
David Anderson0d4277d2018-07-31 13:27:37 -070037#include <liblp/builder.h>
38#include <liblp/liblp.h>
David Anderson220ddb12019-10-31 18:02:41 -070039#include <libsnapshot/snapshot.h>
Yifan Honga4eb4752021-02-16 19:37:21 -080040#include <storage_literals/storage_literals.h>
David Anderson0d4277d2018-07-31 13:27:37 -070041#include <uuid/uuid.h>
Hridya Valsarajudea91b42018-07-17 11:14:01 -070042
Florian Mayer4c3c5262022-09-14 16:02:11 -070043#include <bootloader_message/bootloader_message.h>
44
Kelvin Zhang6befe782022-06-21 14:20:54 -070045#include "BootControlClient.h"
Hridya Valsaraju31d2c262018-07-20 13:35:50 -070046#include "constants.h"
Hridya Valsarajudea91b42018-07-17 11:14:01 -070047#include "fastboot_device.h"
David Anderson12211d12018-07-24 15:21:20 -070048#include "flashing.h"
Hridya Valsaraju31d2c262018-07-20 13:35:50 -070049#include "utility.h"
50
Yifan Honga4eb4752021-02-16 19:37:21 -080051#ifdef FB_ENABLE_FETCH
52static constexpr bool kEnableFetch = true;
53#else
54static constexpr bool kEnableFetch = false;
55#endif
56
David Anderson27475322019-06-11 14:00:08 -070057using android::fs_mgr::MetadataBuilder;
Kelvin Zhang6befe782022-06-21 14:20:54 -070058using android::hal::CommandResult;
Hridya Valsaraju31d2c262018-07-20 13:35:50 -070059using ::android::hardware::hidl_string;
Hridya Valsarajua15fe312018-09-14 13:58:21 -070060using ::android::hardware::fastboot::V1_0::Result;
61using ::android::hardware::fastboot::V1_0::Status;
David Anderson220ddb12019-10-31 18:02:41 -070062using android::snapshot::SnapshotManager;
Kelvin Zhang6befe782022-06-21 14:20:54 -070063using MergeStatus = android::hal::BootControlClient::MergeStatus;
Hridya Valsarajua15fe312018-09-14 13:58:21 -070064
Yifan Honga4eb4752021-02-16 19:37:21 -080065using namespace android::storage_literals;
66
David Anderson0f626632018-08-31 16:44:25 -070067struct VariableHandlers {
68 // Callback to retrieve the value of a single variable.
69 std::function<bool(FastbootDevice*, const std::vector<std::string>&, std::string*)> get;
70 // Callback to retrieve all possible argument combinations, for getvar all.
71 std::function<std::vector<std::vector<std::string>>(FastbootDevice*)> get_all_args;
72};
73
David Anderson220ddb12019-10-31 18:02:41 -070074static bool IsSnapshotUpdateInProgress(FastbootDevice* device) {
75 auto hal = device->boot1_1();
76 if (!hal) {
77 return false;
78 }
79 auto merge_status = hal->getSnapshotMergeStatus();
80 return merge_status == MergeStatus::SNAPSHOTTED || merge_status == MergeStatus::MERGING;
81}
82
83static bool IsProtectedPartitionDuringMerge(FastbootDevice* device, const std::string& name) {
84 static const std::unordered_set<std::string> ProtectedPartitionsDuringMerge = {
85 "userdata", "metadata", "misc"};
86 if (ProtectedPartitionsDuringMerge.count(name) == 0) {
87 return false;
88 }
89 return IsSnapshotUpdateInProgress(device);
90}
91
David Anderson0f626632018-08-31 16:44:25 -070092static void GetAllVars(FastbootDevice* device, const std::string& name,
93 const VariableHandlers& handlers) {
94 if (!handlers.get_all_args) {
95 std::string message;
96 if (!handlers.get(device, std::vector<std::string>(), &message)) {
97 return;
98 }
99 device->WriteInfo(android::base::StringPrintf("%s:%s", name.c_str(), message.c_str()));
100 return;
101 }
102
103 auto all_args = handlers.get_all_args(device);
104 for (const auto& args : all_args) {
105 std::string message;
106 if (!handlers.get(device, args, &message)) {
107 continue;
108 }
109 std::string arg_string = android::base::Join(args, ":");
110 device->WriteInfo(android::base::StringPrintf("%s:%s:%s", name.c_str(), arg_string.c_str(),
111 message.c_str()));
112 }
113}
114
David Andersonebc8fe12022-06-17 19:17:43 -0700115const std::unordered_map<std::string, VariableHandlers> kVariableMap = {
116 {FB_VAR_VERSION, {GetVersion, nullptr}},
117 {FB_VAR_VERSION_BOOTLOADER, {GetBootloaderVersion, nullptr}},
118 {FB_VAR_VERSION_BASEBAND, {GetBasebandVersion, nullptr}},
119 {FB_VAR_VERSION_OS, {GetOsVersion, nullptr}},
120 {FB_VAR_VERSION_VNDK, {GetVndkVersion, nullptr}},
121 {FB_VAR_PRODUCT, {GetProduct, nullptr}},
122 {FB_VAR_SERIALNO, {GetSerial, nullptr}},
123 {FB_VAR_VARIANT, {GetVariant, nullptr}},
124 {FB_VAR_SECURE, {GetSecure, nullptr}},
125 {FB_VAR_UNLOCKED, {GetUnlocked, nullptr}},
126 {FB_VAR_MAX_DOWNLOAD_SIZE, {GetMaxDownloadSize, nullptr}},
127 {FB_VAR_CURRENT_SLOT, {::GetCurrentSlot, nullptr}},
128 {FB_VAR_SLOT_COUNT, {GetSlotCount, nullptr}},
129 {FB_VAR_HAS_SLOT, {GetHasSlot, GetAllPartitionArgsNoSlot}},
130 {FB_VAR_SLOT_SUCCESSFUL, {GetSlotSuccessful, nullptr}},
131 {FB_VAR_SLOT_UNBOOTABLE, {GetSlotUnbootable, nullptr}},
132 {FB_VAR_PARTITION_SIZE, {GetPartitionSize, GetAllPartitionArgsWithSlot}},
133 {FB_VAR_PARTITION_TYPE, {GetPartitionType, GetAllPartitionArgsWithSlot}},
134 {FB_VAR_IS_LOGICAL, {GetPartitionIsLogical, GetAllPartitionArgsWithSlot}},
135 {FB_VAR_IS_USERSPACE, {GetIsUserspace, nullptr}},
136 {FB_VAR_OFF_MODE_CHARGE_STATE, {GetOffModeChargeState, nullptr}},
137 {FB_VAR_BATTERY_VOLTAGE, {GetBatteryVoltage, nullptr}},
138 {FB_VAR_BATTERY_SOC_OK, {GetBatterySoCOk, nullptr}},
139 {FB_VAR_HW_REVISION, {GetHardwareRevision, nullptr}},
140 {FB_VAR_SUPER_PARTITION_NAME, {GetSuperPartitionName, nullptr}},
141 {FB_VAR_SNAPSHOT_UPDATE_STATUS, {GetSnapshotUpdateStatus, nullptr}},
142 {FB_VAR_CPU_ABI, {GetCpuAbi, nullptr}},
143 {FB_VAR_SYSTEM_FINGERPRINT, {GetSystemFingerprint, nullptr}},
144 {FB_VAR_VENDOR_FINGERPRINT, {GetVendorFingerprint, nullptr}},
145 {FB_VAR_DYNAMIC_PARTITION, {GetDynamicPartition, nullptr}},
146 {FB_VAR_FIRST_API_LEVEL, {GetFirstApiLevel, nullptr}},
147 {FB_VAR_SECURITY_PATCH_LEVEL, {GetSecurityPatchLevel, nullptr}},
148 {FB_VAR_TREBLE_ENABLED, {GetTrebleEnabled, nullptr}},
149 {FB_VAR_MAX_FETCH_SIZE, {GetMaxFetchSize, nullptr}},
150};
David Anderson0f626632018-08-31 16:44:25 -0700151
David Andersonebc8fe12022-06-17 19:17:43 -0700152static bool GetVarAll(FastbootDevice* device) {
153 for (const auto& [name, handlers] : kVariableMap) {
154 GetAllVars(device, name, handlers);
155 }
156 return true;
157}
158
Florian Mayer4c3c5262022-09-14 16:02:11 -0700159static void PostWipeData() {
160 std::string err;
161 // Reset mte state of device.
162 if (!WriteMiscMemtagMessage({}, &err)) {
163 LOG(ERROR) << "Failed to reset MTE state: " << err;
164 }
165}
166
David Andersonebc8fe12022-06-17 19:17:43 -0700167const std::unordered_map<std::string, std::function<bool(FastbootDevice*)>> kSpecialVars = {
168 {"all", GetVarAll},
169 {"dmesg", GetDmesg},
170};
171
172bool GetVarHandler(FastbootDevice* device, const std::vector<std::string>& args) {
David Anderson0f626632018-08-31 16:44:25 -0700173 if (args.size() < 2) {
174 return device->WriteFail("Missing argument");
175 }
176
David Andersonebc8fe12022-06-17 19:17:43 -0700177 // "all" and "dmesg" are multiline and handled specially.
178 auto found_special = kSpecialVars.find(args[1]);
179 if (found_special != kSpecialVars.end()) {
180 if (!found_special->second(device)) {
181 return false;
David Anderson0f626632018-08-31 16:44:25 -0700182 }
183 return device->WriteOkay("");
184 }
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700185
186 // args[0] is command name, args[1] is variable.
187 auto found_variable = kVariableMap.find(args[1]);
188 if (found_variable == kVariableMap.end()) {
David Anderson1fb3fd72018-08-31 14:40:22 -0700189 return device->WriteFail("Unknown variable");
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700190 }
191
David Anderson1fb3fd72018-08-31 14:40:22 -0700192 std::string message;
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700193 std::vector<std::string> getvar_args(args.begin() + 2, args.end());
David Anderson0f626632018-08-31 16:44:25 -0700194 if (!found_variable->second.get(device, getvar_args, &message)) {
David Anderson1fb3fd72018-08-31 14:40:22 -0700195 return device->WriteFail(message);
196 }
197 return device->WriteOkay(message);
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700198}
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700199
josephjang29069752020-09-23 16:28:03 +0800200bool OemPostWipeData(FastbootDevice* device) {
201 auto fastboot_hal = device->fastboot_hal();
202 if (!fastboot_hal) {
203 return false;
204 }
205
206 Result ret;
207 auto ret_val = fastboot_hal->doOemSpecificErase([&](Result result) { ret = result; });
208 if (!ret_val.isOk()) {
209 return false;
210 }
211 if (ret.status == Status::NOT_SUPPORTED) {
212 return false;
213 } else if (ret.status != Status::SUCCESS) {
214 device->WriteStatus(FastbootResult::FAIL, ret.message);
215 } else {
216 device->WriteStatus(FastbootResult::OKAY, "Erasing succeeded");
217 }
218
219 return true;
220}
221
David Anderson12211d12018-07-24 15:21:20 -0700222bool EraseHandler(FastbootDevice* device, const std::vector<std::string>& args) {
223 if (args.size() < 2) {
224 return device->WriteStatus(FastbootResult::FAIL, "Invalid arguments");
225 }
Hridya Valsarajud1e62312018-10-08 09:13:17 -0700226
227 if (GetDeviceLockStatus()) {
228 return device->WriteStatus(FastbootResult::FAIL, "Erase is not allowed on locked devices");
229 }
230
David Anderson220ddb12019-10-31 18:02:41 -0700231 const auto& partition_name = args[1];
232 if (IsProtectedPartitionDuringMerge(device, partition_name)) {
233 auto message = "Cannot erase " + partition_name + " while a snapshot update is in progress";
234 return device->WriteFail(message);
235 }
236
David Anderson12211d12018-07-24 15:21:20 -0700237 PartitionHandle handle;
David Anderson220ddb12019-10-31 18:02:41 -0700238 if (!OpenPartition(device, partition_name, &handle)) {
David Anderson12211d12018-07-24 15:21:20 -0700239 return device->WriteStatus(FastbootResult::FAIL, "Partition doesn't exist");
240 }
241 if (wipe_block_device(handle.fd(), get_block_device_size(handle.fd())) == 0) {
josephjang29069752020-09-23 16:28:03 +0800242 //Perform oem PostWipeData if Android userdata partition has been erased
243 bool support_oem_postwipedata = false;
244 if (partition_name == "userdata") {
Florian Mayer4c3c5262022-09-14 16:02:11 -0700245 PostWipeData();
josephjang29069752020-09-23 16:28:03 +0800246 support_oem_postwipedata = OemPostWipeData(device);
247 }
248
249 if (!support_oem_postwipedata) {
250 return device->WriteStatus(FastbootResult::OKAY, "Erasing succeeded");
251 } else {
252 //Write device status in OemPostWipeData(), so just return true
253 return true;
254 }
David Anderson12211d12018-07-24 15:21:20 -0700255 }
256 return device->WriteStatus(FastbootResult::FAIL, "Erasing failed");
257}
258
Hridya Valsarajua15fe312018-09-14 13:58:21 -0700259bool OemCmdHandler(FastbootDevice* device, const std::vector<std::string>& args) {
260 auto fastboot_hal = device->fastboot_hal();
261 if (!fastboot_hal) {
262 return device->WriteStatus(FastbootResult::FAIL, "Unable to open fastboot HAL");
263 }
264
josephjangad90b452020-09-16 16:27:42 +0800265 //Disable "oem postwipedata userdata" to prevent user wipe oem userdata only.
266 if (args[0] == "oem postwipedata userdata") {
267 return device->WriteStatus(FastbootResult::FAIL, "Unable to do oem postwipedata userdata");
268 }
269
Hridya Valsarajua15fe312018-09-14 13:58:21 -0700270 Result ret;
271 auto ret_val = fastboot_hal->doOemCommand(args[0], [&](Result result) { ret = result; });
272 if (!ret_val.isOk()) {
273 return device->WriteStatus(FastbootResult::FAIL, "Unable to do OEM command");
274 }
275 if (ret.status != Status::SUCCESS) {
276 return device->WriteStatus(FastbootResult::FAIL, ret.message);
277 }
278
Michael Bestasbcf76802022-05-11 22:24:40 +0300279 device->WriteInfo(ret.message);
Hridya Valsarajua15fe312018-09-14 13:58:21 -0700280 return device->WriteStatus(FastbootResult::OKAY, ret.message);
281}
282
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700283bool DownloadHandler(FastbootDevice* device, const std::vector<std::string>& args) {
284 if (args.size() < 2) {
285 return device->WriteStatus(FastbootResult::FAIL, "size argument unspecified");
286 }
Hridya Valsarajud1e62312018-10-08 09:13:17 -0700287
288 if (GetDeviceLockStatus()) {
289 return device->WriteStatus(FastbootResult::FAIL,
290 "Download is not allowed on locked devices");
291 }
292
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700293 // arg[0] is the command name, arg[1] contains size of data to be downloaded
Keith Mok3724bbc2021-12-30 20:08:04 +0000294 // which should always be 8 bytes
295 if (args[1].length() != 8) {
296 return device->WriteStatus(FastbootResult::FAIL,
297 "Invalid size (length of size != 8)");
298 }
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700299 unsigned int size;
Hridya Valsarajuaae84e82018-10-08 13:10:25 -0700300 if (!android::base::ParseUint("0x" + args[1], &size, kMaxDownloadSizeDefault)) {
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700301 return device->WriteStatus(FastbootResult::FAIL, "Invalid size");
302 }
Keith Mok3724bbc2021-12-30 20:08:04 +0000303 if (size == 0) {
304 return device->WriteStatus(FastbootResult::FAIL, "Invalid size (0)");
305 }
David Anderson12211d12018-07-24 15:21:20 -0700306 device->download_data().resize(size);
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700307 if (!device->WriteStatus(FastbootResult::DATA, android::base::StringPrintf("%08x", size))) {
308 return false;
309 }
310
David Anderson12211d12018-07-24 15:21:20 -0700311 if (device->HandleData(true, &device->download_data())) {
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700312 return device->WriteStatus(FastbootResult::OKAY, "");
313 }
314
315 PLOG(ERROR) << "Couldn't download data";
316 return device->WriteStatus(FastbootResult::FAIL, "Couldn't download data");
317}
318
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700319bool SetActiveHandler(FastbootDevice* device, const std::vector<std::string>& args) {
320 if (args.size() < 2) {
321 return device->WriteStatus(FastbootResult::FAIL, "Missing slot argument");
322 }
323
Hridya Valsarajud1e62312018-10-08 09:13:17 -0700324 if (GetDeviceLockStatus()) {
325 return device->WriteStatus(FastbootResult::FAIL,
326 "set_active command is not allowed on locked devices");
327 }
328
Kelvin Zhang6befe782022-06-21 14:20:54 -0700329 int32_t slot = 0;
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700330 if (!GetSlotNumber(args[1], &slot)) {
David Anderson220ddb12019-10-31 18:02:41 -0700331 // Slot suffix needs to be between 'a' and 'z'.
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700332 return device->WriteStatus(FastbootResult::FAIL, "Bad slot suffix");
333 }
334
335 // Non-A/B devices will not have a boot control HAL.
336 auto boot_control_hal = device->boot_control_hal();
337 if (!boot_control_hal) {
338 return device->WriteStatus(FastbootResult::FAIL,
339 "Cannot set slot: boot control HAL absent");
340 }
Kelvin Zhang6befe782022-06-21 14:20:54 -0700341 if (slot >= boot_control_hal->GetNumSlots()) {
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700342 return device->WriteStatus(FastbootResult::FAIL, "Slot out of range");
343 }
David Anderson220ddb12019-10-31 18:02:41 -0700344
345 // If the slot is not changing, do nothing.
Hridya Valsaraju45719a82020-03-02 13:03:47 -0800346 if (args[1] == device->GetCurrentSlot()) {
David Anderson220ddb12019-10-31 18:02:41 -0700347 return device->WriteOkay("");
348 }
349
350 // Check how to handle the current snapshot state.
351 if (auto hal11 = device->boot1_1()) {
352 auto merge_status = hal11->getSnapshotMergeStatus();
353 if (merge_status == MergeStatus::MERGING) {
354 return device->WriteFail("Cannot change slots while a snapshot update is in progress");
355 }
356 // Note: we allow the slot change if the state is SNAPSHOTTED. First-
357 // stage init does not have access to the HAL, and uses the slot number
358 // and /metadata OTA state to determine whether a slot change occurred.
359 // Booting into the old slot would erase the OTA, and switching A->B->A
360 // would simply resume it if no boots occur in between. Re-flashing
361 // partitions implicitly cancels the OTA, so leaving the state as-is is
362 // safe.
363 if (merge_status == MergeStatus::SNAPSHOTTED) {
364 device->WriteInfo(
365 "Changing the active slot with a snapshot applied may cancel the"
366 " update.");
367 }
368 }
369
Kelvin Zhang6befe782022-06-21 14:20:54 -0700370 CommandResult ret = boot_control_hal->SetActiveBootSlot(slot);
371 if (ret.success) {
Hridya Valsaraju20bdf892018-10-10 11:02:19 -0700372 // Save as slot suffix to match the suffix format as returned from
373 // the boot control HAL.
374 auto current_slot = "_" + args[1];
375 device->set_active_slot(current_slot);
376 return device->WriteStatus(FastbootResult::OKAY, "");
377 }
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700378 return device->WriteStatus(FastbootResult::FAIL, "Unable to set slot");
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700379}
380
381bool ShutDownHandler(FastbootDevice* device, const std::vector<std::string>& /* args */) {
382 auto result = device->WriteStatus(FastbootResult::OKAY, "Shutting down");
383 android::base::SetProperty(ANDROID_RB_PROPERTY, "shutdown,fastboot");
384 device->CloseDevice();
385 TEMP_FAILURE_RETRY(pause());
386 return result;
387}
388
389bool RebootHandler(FastbootDevice* device, const std::vector<std::string>& /* args */) {
390 auto result = device->WriteStatus(FastbootResult::OKAY, "Rebooting");
391 android::base::SetProperty(ANDROID_RB_PROPERTY, "reboot,from_fastboot");
392 device->CloseDevice();
393 TEMP_FAILURE_RETRY(pause());
394 return result;
395}
396
397bool RebootBootloaderHandler(FastbootDevice* device, const std::vector<std::string>& /* args */) {
398 auto result = device->WriteStatus(FastbootResult::OKAY, "Rebooting bootloader");
399 android::base::SetProperty(ANDROID_RB_PROPERTY, "reboot,bootloader");
400 device->CloseDevice();
401 TEMP_FAILURE_RETRY(pause());
402 return result;
403}
404
405bool RebootFastbootHandler(FastbootDevice* device, const std::vector<std::string>& /* args */) {
406 auto result = device->WriteStatus(FastbootResult::OKAY, "Rebooting fastboot");
407 android::base::SetProperty(ANDROID_RB_PROPERTY, "reboot,fastboot");
408 device->CloseDevice();
409 TEMP_FAILURE_RETRY(pause());
410 return result;
411}
412
413static bool EnterRecovery() {
414 const char msg_switch_to_recovery = 'r';
415
416 android::base::unique_fd sock(socket(AF_UNIX, SOCK_STREAM, 0));
417 if (sock < 0) {
418 PLOG(ERROR) << "Couldn't create sock";
419 return false;
420 }
421
422 struct sockaddr_un addr = {.sun_family = AF_UNIX};
423 strncpy(addr.sun_path, "/dev/socket/recovery", sizeof(addr.sun_path) - 1);
Yifan Hong07e947f2021-03-22 19:21:34 -0700424 if (connect(sock.get(), (struct sockaddr*)&addr, sizeof(addr)) < 0) {
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700425 PLOG(ERROR) << "Couldn't connect to recovery";
426 return false;
427 }
428 // Switch to recovery will not update the boot reason since it does not
429 // require a reboot.
Yifan Hong07e947f2021-03-22 19:21:34 -0700430 auto ret = write(sock.get(), &msg_switch_to_recovery, sizeof(msg_switch_to_recovery));
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700431 if (ret != sizeof(msg_switch_to_recovery)) {
432 PLOG(ERROR) << "Couldn't write message to switch to recovery";
433 return false;
434 }
435
436 return true;
437}
438
439bool RebootRecoveryHandler(FastbootDevice* device, const std::vector<std::string>& /* args */) {
440 auto status = true;
441 if (EnterRecovery()) {
442 status = device->WriteStatus(FastbootResult::OKAY, "Rebooting to recovery");
443 } else {
444 status = device->WriteStatus(FastbootResult::FAIL, "Unable to reboot to recovery");
445 }
446 device->CloseDevice();
447 TEMP_FAILURE_RETRY(pause());
448 return status;
449}
David Anderson0d4277d2018-07-31 13:27:37 -0700450
451// Helper class for opening a handle to a MetadataBuilder and writing the new
452// partition table to the same place it was read.
453class PartitionBuilder {
454 public:
David Andersond25f1c32018-11-09 20:41:33 -0800455 explicit PartitionBuilder(FastbootDevice* device, const std::string& partition_name);
David Anderson0d4277d2018-07-31 13:27:37 -0700456
457 bool Write();
458 bool Valid() const { return !!builder_; }
459 MetadataBuilder* operator->() const { return builder_.get(); }
460
461 private:
David Anderson4d307b02018-12-17 17:07:34 -0800462 FastbootDevice* device_;
David Anderson0d4277d2018-07-31 13:27:37 -0700463 std::string super_device_;
David Andersond25f1c32018-11-09 20:41:33 -0800464 uint32_t slot_number_;
David Anderson0d4277d2018-07-31 13:27:37 -0700465 std::unique_ptr<MetadataBuilder> builder_;
466};
467
David Anderson4d307b02018-12-17 17:07:34 -0800468PartitionBuilder::PartitionBuilder(FastbootDevice* device, const std::string& partition_name)
469 : device_(device) {
David Andersond25f1c32018-11-09 20:41:33 -0800470 std::string slot_suffix = GetSuperSlotSuffix(device, partition_name);
David Anderson27475322019-06-11 14:00:08 -0700471 slot_number_ = android::fs_mgr::SlotNumberForSlotSuffix(slot_suffix);
David Andersond25f1c32018-11-09 20:41:33 -0800472 auto super_device = FindPhysicalPartition(fs_mgr_get_super_partition_name(slot_number_));
David Anderson0d4277d2018-07-31 13:27:37 -0700473 if (!super_device) {
474 return;
475 }
476 super_device_ = *super_device;
David Andersond25f1c32018-11-09 20:41:33 -0800477 builder_ = MetadataBuilder::New(super_device_, slot_number_);
David Anderson0d4277d2018-07-31 13:27:37 -0700478}
479
480bool PartitionBuilder::Write() {
David Anderson27475322019-06-11 14:00:08 -0700481 auto metadata = builder_->Export();
David Anderson0d4277d2018-07-31 13:27:37 -0700482 if (!metadata) {
483 return false;
484 }
David Anderson4d307b02018-12-17 17:07:34 -0800485 return UpdateAllPartitionMetadata(device_, super_device_, *metadata.get());
David Anderson0d4277d2018-07-31 13:27:37 -0700486}
487
488bool CreatePartitionHandler(FastbootDevice* device, const std::vector<std::string>& args) {
489 if (args.size() < 3) {
490 return device->WriteFail("Invalid partition name and size");
491 }
492
Hridya Valsarajudca328d2018-09-24 16:01:35 -0700493 if (GetDeviceLockStatus()) {
494 return device->WriteStatus(FastbootResult::FAIL, "Command not available on locked devices");
495 }
496
David Anderson0d4277d2018-07-31 13:27:37 -0700497 uint64_t partition_size;
498 std::string partition_name = args[1];
499 if (!android::base::ParseUint(args[2].c_str(), &partition_size)) {
500 return device->WriteFail("Invalid partition size");
501 }
502
David Andersond25f1c32018-11-09 20:41:33 -0800503 PartitionBuilder builder(device, partition_name);
David Anderson0d4277d2018-07-31 13:27:37 -0700504 if (!builder.Valid()) {
505 return device->WriteFail("Could not open super partition");
506 }
507 // TODO(112433293) Disallow if the name is in the physical table as well.
508 if (builder->FindPartition(partition_name)) {
509 return device->WriteFail("Partition already exists");
510 }
511
David Anderson27475322019-06-11 14:00:08 -0700512 auto partition = builder->AddPartition(partition_name, 0);
David Anderson0d4277d2018-07-31 13:27:37 -0700513 if (!partition) {
514 return device->WriteFail("Failed to add partition");
515 }
516 if (!builder->ResizePartition(partition, partition_size)) {
517 builder->RemovePartition(partition_name);
518 return device->WriteFail("Not enough space for partition");
519 }
520 if (!builder.Write()) {
521 return device->WriteFail("Failed to write partition table");
522 }
523 return device->WriteOkay("Partition created");
524}
525
526bool DeletePartitionHandler(FastbootDevice* device, const std::vector<std::string>& args) {
527 if (args.size() < 2) {
528 return device->WriteFail("Invalid partition name and size");
529 }
530
Hridya Valsarajudca328d2018-09-24 16:01:35 -0700531 if (GetDeviceLockStatus()) {
532 return device->WriteStatus(FastbootResult::FAIL, "Command not available on locked devices");
533 }
534
David Andersond25f1c32018-11-09 20:41:33 -0800535 std::string partition_name = args[1];
536
537 PartitionBuilder builder(device, partition_name);
David Anderson0d4277d2018-07-31 13:27:37 -0700538 if (!builder.Valid()) {
539 return device->WriteFail("Could not open super partition");
540 }
David Andersond25f1c32018-11-09 20:41:33 -0800541 builder->RemovePartition(partition_name);
David Anderson0d4277d2018-07-31 13:27:37 -0700542 if (!builder.Write()) {
543 return device->WriteFail("Failed to write partition table");
544 }
545 return device->WriteOkay("Partition deleted");
546}
547
548bool ResizePartitionHandler(FastbootDevice* device, const std::vector<std::string>& args) {
549 if (args.size() < 3) {
550 return device->WriteFail("Invalid partition name and size");
551 }
552
Hridya Valsarajudca328d2018-09-24 16:01:35 -0700553 if (GetDeviceLockStatus()) {
554 return device->WriteStatus(FastbootResult::FAIL, "Command not available on locked devices");
555 }
556
David Anderson0d4277d2018-07-31 13:27:37 -0700557 uint64_t partition_size;
558 std::string partition_name = args[1];
559 if (!android::base::ParseUint(args[2].c_str(), &partition_size)) {
560 return device->WriteFail("Invalid partition size");
561 }
562
David Andersond25f1c32018-11-09 20:41:33 -0800563 PartitionBuilder builder(device, partition_name);
David Anderson0d4277d2018-07-31 13:27:37 -0700564 if (!builder.Valid()) {
565 return device->WriteFail("Could not open super partition");
566 }
567
David Anderson27475322019-06-11 14:00:08 -0700568 auto partition = builder->FindPartition(partition_name);
David Anderson0d4277d2018-07-31 13:27:37 -0700569 if (!partition) {
570 return device->WriteFail("Partition does not exist");
571 }
David Andersonad970fc2019-08-27 14:01:16 -0700572
573 // Remove the updated flag to cancel any snapshots.
574 uint32_t attrs = partition->attributes();
575 partition->set_attributes(attrs & ~LP_PARTITION_ATTR_UPDATED);
576
David Anderson0d4277d2018-07-31 13:27:37 -0700577 if (!builder->ResizePartition(partition, partition_size)) {
578 return device->WriteFail("Not enough space to resize partition");
579 }
580 if (!builder.Write()) {
581 return device->WriteFail("Failed to write partition table");
582 }
583 return device->WriteOkay("Partition resized");
584}
David Anderson38b3c7a2018-08-15 16:27:42 -0700585
David Andersonad970fc2019-08-27 14:01:16 -0700586void CancelPartitionSnapshot(FastbootDevice* device, const std::string& partition_name) {
587 PartitionBuilder builder(device, partition_name);
588 if (!builder.Valid()) return;
589
590 auto partition = builder->FindPartition(partition_name);
591 if (!partition) return;
592
593 // Remove the updated flag to cancel any snapshots.
594 uint32_t attrs = partition->attributes();
595 partition->set_attributes(attrs & ~LP_PARTITION_ATTR_UPDATED);
596
597 builder.Write();
598}
599
600bool FlashHandler(FastbootDevice* device, const std::vector<std::string>& args) {
601 if (args.size() < 2) {
602 return device->WriteStatus(FastbootResult::FAIL, "Invalid arguments");
603 }
604
605 if (GetDeviceLockStatus()) {
606 return device->WriteStatus(FastbootResult::FAIL,
607 "Flashing is not allowed on locked devices");
608 }
609
610 const auto& partition_name = args[1];
David Anderson220ddb12019-10-31 18:02:41 -0700611 if (IsProtectedPartitionDuringMerge(device, partition_name)) {
612 auto message = "Cannot flash " + partition_name + " while a snapshot update is in progress";
613 return device->WriteFail(message);
614 }
615
David Andersonad970fc2019-08-27 14:01:16 -0700616 if (LogicalPartitionExists(device, partition_name)) {
617 CancelPartitionSnapshot(device, partition_name);
618 }
619
620 int ret = Flash(device, partition_name);
621 if (ret < 0) {
622 return device->WriteStatus(FastbootResult::FAIL, strerror(-ret));
623 }
Florian Mayer4c3c5262022-09-14 16:02:11 -0700624 if (partition_name == "userdata") {
625 PostWipeData();
626 }
627
David Andersonad970fc2019-08-27 14:01:16 -0700628 return device->WriteStatus(FastbootResult::OKAY, "Flashing succeeded");
629}
630
David Anderson38b3c7a2018-08-15 16:27:42 -0700631bool UpdateSuperHandler(FastbootDevice* device, const std::vector<std::string>& args) {
632 if (args.size() < 2) {
633 return device->WriteFail("Invalid arguments");
634 }
Hridya Valsarajudca328d2018-09-24 16:01:35 -0700635
636 if (GetDeviceLockStatus()) {
637 return device->WriteStatus(FastbootResult::FAIL, "Command not available on locked devices");
638 }
639
David Anderson38b3c7a2018-08-15 16:27:42 -0700640 bool wipe = (args.size() >= 3 && args[2] == "wipe");
641 return UpdateSuper(device, args[1], wipe);
642}
David Anderson1d504e32019-01-15 14:38:20 -0800643
David Anderson3d782d52019-01-29 13:09:49 -0800644bool GsiHandler(FastbootDevice* device, const std::vector<std::string>& args) {
David Anderson1d504e32019-01-15 14:38:20 -0800645 if (args.size() != 2) {
646 return device->WriteFail("Invalid arguments");
647 }
David Anderson3d782d52019-01-29 13:09:49 -0800648
649 AutoMountMetadata mount_metadata;
650 if (!mount_metadata) {
651 return device->WriteFail("Could not find GSI install");
652 }
653
654 if (!android::gsi::IsGsiInstalled()) {
655 return device->WriteStatus(FastbootResult::FAIL, "No GSI is installed");
656 }
657
David Anderson1d504e32019-01-15 14:38:20 -0800658 if (args[1] == "wipe") {
659 if (!android::gsi::UninstallGsi()) {
660 return device->WriteStatus(FastbootResult::FAIL, strerror(errno));
661 }
662 } else if (args[1] == "disable") {
663 if (!android::gsi::DisableGsi()) {
664 return device->WriteStatus(FastbootResult::FAIL, strerror(errno));
665 }
666 }
667 return device->WriteStatus(FastbootResult::OKAY, "Success");
668}
David Andersonab8f4662019-10-21 16:45:59 -0700669
670bool SnapshotUpdateHandler(FastbootDevice* device, const std::vector<std::string>& args) {
671 // Note that we use the HAL rather than mounting /metadata, since we want
672 // our results to match the bootloader.
David Anderson220ddb12019-10-31 18:02:41 -0700673 auto hal = device->boot1_1();
David Andersonab8f4662019-10-21 16:45:59 -0700674 if (!hal) return device->WriteFail("Not supported");
675
David Andersonab8f4662019-10-21 16:45:59 -0700676 // If no arguments, return the same thing as a getvar. Note that we get the
677 // HAL first so we can return "not supported" before we return the less
678 // specific error message below.
679 if (args.size() < 2 || args[1].empty()) {
680 std::string message;
681 if (!GetSnapshotUpdateStatus(device, {}, &message)) {
682 return device->WriteFail("Could not determine update status");
683 }
684 device->WriteInfo(message);
685 return device->WriteOkay("");
686 }
687
David Anderson220ddb12019-10-31 18:02:41 -0700688 MergeStatus status = hal->getSnapshotMergeStatus();
689
690 if (args.size() != 2) {
David Andersonab8f4662019-10-21 16:45:59 -0700691 return device->WriteFail("Invalid arguments");
692 }
David Anderson220ddb12019-10-31 18:02:41 -0700693 if (args[1] == "cancel") {
694 switch (status) {
695 case MergeStatus::SNAPSHOTTED:
Kelvin Zhang6befe782022-06-21 14:20:54 -0700696 case MergeStatus::MERGING: {
697 const auto ret = hal->SetSnapshotMergeStatus(MergeStatus::CANCELLED);
698 if (!ret.success) {
699 device->WriteFail("Failed to SetSnapshotMergeStatus(MergeStatus::CANCELLED) " +
700 ret.errMsg);
701 }
David Anderson220ddb12019-10-31 18:02:41 -0700702 break;
Kelvin Zhang6befe782022-06-21 14:20:54 -0700703 }
David Anderson220ddb12019-10-31 18:02:41 -0700704 default:
705 break;
706 }
707 } else if (args[1] == "merge") {
708 if (status != MergeStatus::MERGING) {
709 return device->WriteFail("No snapshot merge is in progress");
710 }
David Andersonab8f4662019-10-21 16:45:59 -0700711
David Anderson565577f2021-02-04 20:14:18 -0800712 auto sm = SnapshotManager::New();
David Anderson220ddb12019-10-31 18:02:41 -0700713 if (!sm) {
714 return device->WriteFail("Unable to create SnapshotManager");
715 }
David Anderson5a0177d2020-04-30 18:53:23 -0700716 if (!sm->FinishMergeInRecovery()) {
David Anderson220ddb12019-10-31 18:02:41 -0700717 return device->WriteFail("Unable to finish snapshot merge");
718 }
719 } else {
720 return device->WriteFail("Invalid parameter to snapshot-update");
David Andersonab8f4662019-10-21 16:45:59 -0700721 }
722 return device->WriteStatus(FastbootResult::OKAY, "Success");
723}
Yifan Honga4eb4752021-02-16 19:37:21 -0800724
725namespace {
726// Helper of FetchHandler.
727class PartitionFetcher {
728 public:
729 static bool Fetch(FastbootDevice* device, const std::vector<std::string>& args) {
730 if constexpr (!kEnableFetch) {
731 return device->WriteFail("Fetch is not allowed on user build");
732 }
733
734 if (GetDeviceLockStatus()) {
735 return device->WriteFail("Fetch is not allowed on locked devices");
736 }
737
738 PartitionFetcher fetcher(device, args);
739 if (fetcher.Open()) {
740 fetcher.Fetch();
741 }
742 CHECK(fetcher.ret_.has_value());
743 return *fetcher.ret_;
744 }
745
746 private:
747 PartitionFetcher(FastbootDevice* device, const std::vector<std::string>& args)
748 : device_(device), args_(&args) {}
749 // Return whether the partition is successfully opened.
750 // If successfully opened, ret_ is left untouched. Otherwise, ret_ is set to the value
751 // that FetchHandler should return.
752 bool Open() {
Yifan Hongbcd27702021-02-16 19:37:32 -0800753 if (args_->size() < 2) {
754 ret_ = device_->WriteFail("Missing partition arg");
Yifan Honga4eb4752021-02-16 19:37:21 -0800755 return false;
756 }
757
Yifan Hongbcd27702021-02-16 19:37:32 -0800758 partition_name_ = args_->at(1);
759 if (std::find(kAllowedPartitions.begin(), kAllowedPartitions.end(), partition_name_) ==
760 kAllowedPartitions.end()) {
761 ret_ = device_->WriteFail("Fetch is only allowed on [" +
762 android::base::Join(kAllowedPartitions, ", ") + "]");
763 return false;
764 }
765
Konstantin Vyshetsky81cc1192021-11-04 10:27:06 -0700766 if (!OpenPartition(device_, partition_name_, &handle_, O_RDONLY)) {
Yifan Honga4eb4752021-02-16 19:37:21 -0800767 ret_ = device_->WriteFail(
768 android::base::StringPrintf("Cannot open %s", partition_name_.c_str()));
769 return false;
770 }
771
772 partition_size_ = get_block_device_size(handle_.fd());
773 if (partition_size_ == 0) {
774 ret_ = device_->WriteOkay(android::base::StringPrintf("Partition %s has size 0",
775 partition_name_.c_str()));
776 return false;
777 }
778
779 start_offset_ = 0;
780 if (args_->size() >= 3) {
781 if (!android::base::ParseUint(args_->at(2), &start_offset_)) {
782 ret_ = device_->WriteFail("Invalid offset, must be integer");
783 return false;
784 }
785 if (start_offset_ > std::numeric_limits<off64_t>::max()) {
786 ret_ = device_->WriteFail(
787 android::base::StringPrintf("Offset overflows: %" PRIx64, start_offset_));
788 return false;
789 }
790 }
791 if (start_offset_ > partition_size_) {
792 ret_ = device_->WriteFail(android::base::StringPrintf(
793 "Invalid offset 0x%" PRIx64 ", partition %s has size 0x%" PRIx64, start_offset_,
794 partition_name_.c_str(), partition_size_));
795 return false;
796 }
797 uint64_t maximum_total_size_to_read = partition_size_ - start_offset_;
798 total_size_to_read_ = maximum_total_size_to_read;
799 if (args_->size() >= 4) {
800 if (!android::base::ParseUint(args_->at(3), &total_size_to_read_)) {
801 ret_ = device_->WriteStatus(FastbootResult::FAIL, "Invalid size, must be integer");
802 return false;
803 }
804 }
805 if (total_size_to_read_ == 0) {
806 ret_ = device_->WriteOkay("Read 0 bytes");
807 return false;
808 }
809 if (total_size_to_read_ > maximum_total_size_to_read) {
810 ret_ = device_->WriteFail(android::base::StringPrintf(
811 "Invalid size to read 0x%" PRIx64 ", partition %s has size 0x%" PRIx64
812 " and fetching from offset 0x%" PRIx64,
813 total_size_to_read_, partition_name_.c_str(), partition_size_, start_offset_));
814 return false;
815 }
816
817 if (total_size_to_read_ > kMaxFetchSizeDefault) {
818 ret_ = device_->WriteFail(android::base::StringPrintf(
819 "Cannot fetch 0x%" PRIx64
820 " bytes because it exceeds maximum transport size 0x%x",
821 partition_size_, kMaxDownloadSizeDefault));
822 return false;
823 }
824
825 return true;
826 }
827
828 // Assume Open() returns true.
829 // After execution, ret_ is set to the value that FetchHandler should return.
830 void Fetch() {
831 CHECK(start_offset_ <= std::numeric_limits<off64_t>::max());
832 if (lseek64(handle_.fd(), start_offset_, SEEK_SET) != static_cast<off64_t>(start_offset_)) {
833 ret_ = device_->WriteFail(android::base::StringPrintf(
834 "On partition %s, unable to lseek(0x%" PRIx64 ": %s", partition_name_.c_str(),
835 start_offset_, strerror(errno)));
836 return;
837 }
838
839 if (!device_->WriteStatus(FastbootResult::DATA,
840 android::base::StringPrintf(
841 "%08x", static_cast<uint32_t>(total_size_to_read_)))) {
842 ret_ = false;
843 return;
844 }
845 uint64_t end_offset = start_offset_ + total_size_to_read_;
846 std::vector<char> buf(1_MiB);
847 uint64_t current_offset = start_offset_;
848 while (current_offset < end_offset) {
849 // On any error, exit. We can't return a status message to the driver because
850 // we are in the middle of writing data, so just let the driver guess what's wrong
851 // by ending the data stream prematurely.
852 uint64_t remaining = end_offset - current_offset;
853 uint64_t chunk_size = std::min<uint64_t>(buf.size(), remaining);
854 if (!android::base::ReadFully(handle_.fd(), buf.data(), chunk_size)) {
855 PLOG(ERROR) << std::hex << "Unable to read 0x" << chunk_size << " bytes from "
856 << partition_name_ << " @ offset 0x" << current_offset;
857 ret_ = false;
858 return;
859 }
860 if (!device_->HandleData(false /* is read */, buf.data(), chunk_size)) {
861 PLOG(ERROR) << std::hex << "Unable to send 0x" << chunk_size << " bytes of "
862 << partition_name_ << " @ offset 0x" << current_offset;
863 ret_ = false;
864 return;
865 }
866 current_offset += chunk_size;
867 }
868
869 ret_ = device_->WriteOkay(android::base::StringPrintf(
870 "Fetched %s (offset=0x%" PRIx64 ", size=0x%" PRIx64, partition_name_.c_str(),
871 start_offset_, total_size_to_read_));
872 }
873
Yifan Hongbcd27702021-02-16 19:37:32 -0800874 static constexpr std::array<const char*, 3> kAllowedPartitions{
875 "vendor_boot",
876 "vendor_boot_a",
877 "vendor_boot_b",
878 };
879
Yifan Honga4eb4752021-02-16 19:37:21 -0800880 FastbootDevice* device_;
881 const std::vector<std::string>* args_ = nullptr;
882 std::string partition_name_;
883 PartitionHandle handle_;
884 uint64_t partition_size_ = 0;
885 uint64_t start_offset_ = 0;
886 uint64_t total_size_to_read_ = 0;
887
888 // What FetchHandler should return.
889 std::optional<bool> ret_ = std::nullopt;
890};
891} // namespace
892
893bool FetchHandler(FastbootDevice* device, const std::vector<std::string>& args) {
894 return PartitionFetcher::Fetch(device, args);
895}