blob: bd936ae771dc0c7270574331e0f360baef7c24ae [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;
David Anderson220ddb12019-10-31 18:02:41 -070060using android::snapshot::SnapshotManager;
Kelvin Zhang6befe782022-06-21 14:20:54 -070061using MergeStatus = android::hal::BootControlClient::MergeStatus;
Hridya Valsarajua15fe312018-09-14 13:58:21 -070062
Yifan Honga4eb4752021-02-16 19:37:21 -080063using namespace android::storage_literals;
64
David Anderson0f626632018-08-31 16:44:25 -070065struct VariableHandlers {
66 // Callback to retrieve the value of a single variable.
67 std::function<bool(FastbootDevice*, const std::vector<std::string>&, std::string*)> get;
68 // Callback to retrieve all possible argument combinations, for getvar all.
69 std::function<std::vector<std::vector<std::string>>(FastbootDevice*)> get_all_args;
70};
71
David Anderson220ddb12019-10-31 18:02:41 -070072static bool IsSnapshotUpdateInProgress(FastbootDevice* device) {
73 auto hal = device->boot1_1();
74 if (!hal) {
75 return false;
76 }
77 auto merge_status = hal->getSnapshotMergeStatus();
78 return merge_status == MergeStatus::SNAPSHOTTED || merge_status == MergeStatus::MERGING;
79}
80
81static bool IsProtectedPartitionDuringMerge(FastbootDevice* device, const std::string& name) {
82 static const std::unordered_set<std::string> ProtectedPartitionsDuringMerge = {
83 "userdata", "metadata", "misc"};
84 if (ProtectedPartitionsDuringMerge.count(name) == 0) {
85 return false;
86 }
87 return IsSnapshotUpdateInProgress(device);
88}
89
David Anderson0f626632018-08-31 16:44:25 -070090static void GetAllVars(FastbootDevice* device, const std::string& name,
91 const VariableHandlers& handlers) {
92 if (!handlers.get_all_args) {
93 std::string message;
94 if (!handlers.get(device, std::vector<std::string>(), &message)) {
95 return;
96 }
97 device->WriteInfo(android::base::StringPrintf("%s:%s", name.c_str(), message.c_str()));
98 return;
99 }
100
101 auto all_args = handlers.get_all_args(device);
102 for (const auto& args : all_args) {
103 std::string message;
104 if (!handlers.get(device, args, &message)) {
105 continue;
106 }
107 std::string arg_string = android::base::Join(args, ":");
108 device->WriteInfo(android::base::StringPrintf("%s:%s:%s", name.c_str(), arg_string.c_str(),
109 message.c_str()));
110 }
111}
112
David Andersonebc8fe12022-06-17 19:17:43 -0700113const std::unordered_map<std::string, VariableHandlers> kVariableMap = {
114 {FB_VAR_VERSION, {GetVersion, nullptr}},
115 {FB_VAR_VERSION_BOOTLOADER, {GetBootloaderVersion, nullptr}},
116 {FB_VAR_VERSION_BASEBAND, {GetBasebandVersion, nullptr}},
117 {FB_VAR_VERSION_OS, {GetOsVersion, nullptr}},
118 {FB_VAR_VERSION_VNDK, {GetVndkVersion, nullptr}},
119 {FB_VAR_PRODUCT, {GetProduct, nullptr}},
120 {FB_VAR_SERIALNO, {GetSerial, nullptr}},
121 {FB_VAR_VARIANT, {GetVariant, nullptr}},
122 {FB_VAR_SECURE, {GetSecure, nullptr}},
123 {FB_VAR_UNLOCKED, {GetUnlocked, nullptr}},
124 {FB_VAR_MAX_DOWNLOAD_SIZE, {GetMaxDownloadSize, nullptr}},
125 {FB_VAR_CURRENT_SLOT, {::GetCurrentSlot, nullptr}},
126 {FB_VAR_SLOT_COUNT, {GetSlotCount, nullptr}},
127 {FB_VAR_HAS_SLOT, {GetHasSlot, GetAllPartitionArgsNoSlot}},
128 {FB_VAR_SLOT_SUCCESSFUL, {GetSlotSuccessful, nullptr}},
129 {FB_VAR_SLOT_UNBOOTABLE, {GetSlotUnbootable, nullptr}},
130 {FB_VAR_PARTITION_SIZE, {GetPartitionSize, GetAllPartitionArgsWithSlot}},
131 {FB_VAR_PARTITION_TYPE, {GetPartitionType, GetAllPartitionArgsWithSlot}},
132 {FB_VAR_IS_LOGICAL, {GetPartitionIsLogical, GetAllPartitionArgsWithSlot}},
133 {FB_VAR_IS_USERSPACE, {GetIsUserspace, nullptr}},
Yi-Yo Chiang38b68c62022-11-22 17:32:21 +0800134 {FB_VAR_IS_FORCE_DEBUGGABLE, {GetIsForceDebuggable, nullptr}},
David Andersonebc8fe12022-06-17 19:17:43 -0700135 {FB_VAR_OFF_MODE_CHARGE_STATE, {GetOffModeChargeState, nullptr}},
136 {FB_VAR_BATTERY_VOLTAGE, {GetBatteryVoltage, nullptr}},
Harry Pan7fa8dd62023-10-03 17:48:26 +0000137 {FB_VAR_BATTERY_SOC, {GetBatterySoC, nullptr}},
David Andersonebc8fe12022-06-17 19:17:43 -0700138 {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
Sandeep Dhavale2534d482022-11-08 22:30:05 +0000206 auto status = fastboot_hal->doOemSpecificErase();
207 if (status.isOk()) {
josephjang29069752020-09-23 16:28:03 +0800208 device->WriteStatus(FastbootResult::OKAY, "Erasing succeeded");
Sandeep Dhavale2534d482022-11-08 22:30:05 +0000209 return true;
josephjang29069752020-09-23 16:28:03 +0800210 }
Sandeep Dhavale2534d482022-11-08 22:30:05 +0000211 switch (status.getExceptionCode()) {
212 case EX_UNSUPPORTED_OPERATION:
213 return false;
214 case EX_SERVICE_SPECIFIC:
215 device->WriteStatus(FastbootResult::FAIL, status.getDescription());
216 return false;
217 default:
218 LOG(ERROR) << "Erase operation failed" << status.getDescription();
219 return false;
220 }
josephjang29069752020-09-23 16:28:03 +0800221}
222
David Anderson12211d12018-07-24 15:21:20 -0700223bool EraseHandler(FastbootDevice* device, const std::vector<std::string>& args) {
224 if (args.size() < 2) {
225 return device->WriteStatus(FastbootResult::FAIL, "Invalid arguments");
226 }
Hridya Valsarajud1e62312018-10-08 09:13:17 -0700227
228 if (GetDeviceLockStatus()) {
229 return device->WriteStatus(FastbootResult::FAIL, "Erase is not allowed on locked devices");
230 }
231
David Anderson220ddb12019-10-31 18:02:41 -0700232 const auto& partition_name = args[1];
233 if (IsProtectedPartitionDuringMerge(device, partition_name)) {
234 auto message = "Cannot erase " + partition_name + " while a snapshot update is in progress";
235 return device->WriteFail(message);
236 }
237
David Anderson12211d12018-07-24 15:21:20 -0700238 PartitionHandle handle;
David Anderson220ddb12019-10-31 18:02:41 -0700239 if (!OpenPartition(device, partition_name, &handle)) {
David Anderson12211d12018-07-24 15:21:20 -0700240 return device->WriteStatus(FastbootResult::FAIL, "Partition doesn't exist");
241 }
242 if (wipe_block_device(handle.fd(), get_block_device_size(handle.fd())) == 0) {
josephjang29069752020-09-23 16:28:03 +0800243 //Perform oem PostWipeData if Android userdata partition has been erased
244 bool support_oem_postwipedata = false;
245 if (partition_name == "userdata") {
Florian Mayer4c3c5262022-09-14 16:02:11 -0700246 PostWipeData();
josephjang29069752020-09-23 16:28:03 +0800247 support_oem_postwipedata = OemPostWipeData(device);
248 }
249
250 if (!support_oem_postwipedata) {
251 return device->WriteStatus(FastbootResult::OKAY, "Erasing succeeded");
252 } else {
253 //Write device status in OemPostWipeData(), so just return true
254 return true;
255 }
David Anderson12211d12018-07-24 15:21:20 -0700256 }
257 return device->WriteStatus(FastbootResult::FAIL, "Erasing failed");
258}
259
Hridya Valsarajua15fe312018-09-14 13:58:21 -0700260bool OemCmdHandler(FastbootDevice* device, const std::vector<std::string>& args) {
261 auto fastboot_hal = device->fastboot_hal();
262 if (!fastboot_hal) {
263 return device->WriteStatus(FastbootResult::FAIL, "Unable to open fastboot HAL");
264 }
265
josephjangad90b452020-09-16 16:27:42 +0800266 //Disable "oem postwipedata userdata" to prevent user wipe oem userdata only.
267 if (args[0] == "oem postwipedata userdata") {
268 return device->WriteStatus(FastbootResult::FAIL, "Unable to do oem postwipedata userdata");
269 }
Sandeep Dhavale2534d482022-11-08 22:30:05 +0000270 std::string message;
271 auto status = fastboot_hal->doOemCommand(args[0], &message);
272 if (!status.isOk()) {
273 LOG(ERROR) << "Unable to do OEM command " << args[0].c_str() << status.getDescription();
274 return device->WriteStatus(FastbootResult::FAIL,
275 "Unable to do OEM command " + status.getDescription());
Hridya Valsarajua15fe312018-09-14 13:58:21 -0700276 }
277
Sandeep Dhavale2534d482022-11-08 22:30:05 +0000278 device->WriteInfo(message);
279 return device->WriteStatus(FastbootResult::OKAY, message);
Hridya Valsarajua15fe312018-09-14 13:58:21 -0700280}
281
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700282bool DownloadHandler(FastbootDevice* device, const std::vector<std::string>& args) {
283 if (args.size() < 2) {
284 return device->WriteStatus(FastbootResult::FAIL, "size argument unspecified");
285 }
Hridya Valsarajud1e62312018-10-08 09:13:17 -0700286
287 if (GetDeviceLockStatus()) {
288 return device->WriteStatus(FastbootResult::FAIL,
289 "Download is not allowed on locked devices");
290 }
291
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700292 // arg[0] is the command name, arg[1] contains size of data to be downloaded
Keith Mok3724bbc2021-12-30 20:08:04 +0000293 // which should always be 8 bytes
294 if (args[1].length() != 8) {
295 return device->WriteStatus(FastbootResult::FAIL,
296 "Invalid size (length of size != 8)");
297 }
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700298 unsigned int size;
Hridya Valsarajuaae84e82018-10-08 13:10:25 -0700299 if (!android::base::ParseUint("0x" + args[1], &size, kMaxDownloadSizeDefault)) {
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700300 return device->WriteStatus(FastbootResult::FAIL, "Invalid size");
301 }
Keith Mok3724bbc2021-12-30 20:08:04 +0000302 if (size == 0) {
303 return device->WriteStatus(FastbootResult::FAIL, "Invalid size (0)");
304 }
David Anderson12211d12018-07-24 15:21:20 -0700305 device->download_data().resize(size);
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700306 if (!device->WriteStatus(FastbootResult::DATA, android::base::StringPrintf("%08x", size))) {
307 return false;
308 }
309
David Anderson12211d12018-07-24 15:21:20 -0700310 if (device->HandleData(true, &device->download_data())) {
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700311 return device->WriteStatus(FastbootResult::OKAY, "");
312 }
313
314 PLOG(ERROR) << "Couldn't download data";
315 return device->WriteStatus(FastbootResult::FAIL, "Couldn't download data");
316}
317
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700318bool SetActiveHandler(FastbootDevice* device, const std::vector<std::string>& args) {
319 if (args.size() < 2) {
320 return device->WriteStatus(FastbootResult::FAIL, "Missing slot argument");
321 }
322
Hridya Valsarajud1e62312018-10-08 09:13:17 -0700323 if (GetDeviceLockStatus()) {
324 return device->WriteStatus(FastbootResult::FAIL,
325 "set_active command is not allowed on locked devices");
326 }
327
Kelvin Zhang6befe782022-06-21 14:20:54 -0700328 int32_t slot = 0;
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700329 if (!GetSlotNumber(args[1], &slot)) {
David Anderson220ddb12019-10-31 18:02:41 -0700330 // Slot suffix needs to be between 'a' and 'z'.
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700331 return device->WriteStatus(FastbootResult::FAIL, "Bad slot suffix");
332 }
333
334 // Non-A/B devices will not have a boot control HAL.
335 auto boot_control_hal = device->boot_control_hal();
336 if (!boot_control_hal) {
337 return device->WriteStatus(FastbootResult::FAIL,
338 "Cannot set slot: boot control HAL absent");
339 }
Kelvin Zhang6befe782022-06-21 14:20:54 -0700340 if (slot >= boot_control_hal->GetNumSlots()) {
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700341 return device->WriteStatus(FastbootResult::FAIL, "Slot out of range");
342 }
David Anderson220ddb12019-10-31 18:02:41 -0700343
344 // If the slot is not changing, do nothing.
Hridya Valsaraju45719a82020-03-02 13:03:47 -0800345 if (args[1] == device->GetCurrentSlot()) {
David Anderson220ddb12019-10-31 18:02:41 -0700346 return device->WriteOkay("");
347 }
348
349 // Check how to handle the current snapshot state.
350 if (auto hal11 = device->boot1_1()) {
351 auto merge_status = hal11->getSnapshotMergeStatus();
352 if (merge_status == MergeStatus::MERGING) {
353 return device->WriteFail("Cannot change slots while a snapshot update is in progress");
354 }
355 // Note: we allow the slot change if the state is SNAPSHOTTED. First-
356 // stage init does not have access to the HAL, and uses the slot number
357 // and /metadata OTA state to determine whether a slot change occurred.
358 // Booting into the old slot would erase the OTA, and switching A->B->A
359 // would simply resume it if no boots occur in between. Re-flashing
360 // partitions implicitly cancels the OTA, so leaving the state as-is is
361 // safe.
362 if (merge_status == MergeStatus::SNAPSHOTTED) {
363 device->WriteInfo(
364 "Changing the active slot with a snapshot applied may cancel the"
365 " update.");
366 }
367 }
368
Kelvin Zhang6befe782022-06-21 14:20:54 -0700369 CommandResult ret = boot_control_hal->SetActiveBootSlot(slot);
370 if (ret.success) {
Hridya Valsaraju20bdf892018-10-10 11:02:19 -0700371 // Save as slot suffix to match the suffix format as returned from
372 // the boot control HAL.
373 auto current_slot = "_" + args[1];
374 device->set_active_slot(current_slot);
375 return device->WriteStatus(FastbootResult::OKAY, "");
376 }
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700377 return device->WriteStatus(FastbootResult::FAIL, "Unable to set slot");
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700378}
379
380bool ShutDownHandler(FastbootDevice* device, const std::vector<std::string>& /* args */) {
381 auto result = device->WriteStatus(FastbootResult::OKAY, "Shutting down");
382 android::base::SetProperty(ANDROID_RB_PROPERTY, "shutdown,fastboot");
383 device->CloseDevice();
384 TEMP_FAILURE_RETRY(pause());
385 return result;
386}
387
388bool RebootHandler(FastbootDevice* device, const std::vector<std::string>& /* args */) {
389 auto result = device->WriteStatus(FastbootResult::OKAY, "Rebooting");
390 android::base::SetProperty(ANDROID_RB_PROPERTY, "reboot,from_fastboot");
391 device->CloseDevice();
392 TEMP_FAILURE_RETRY(pause());
393 return result;
394}
395
396bool RebootBootloaderHandler(FastbootDevice* device, const std::vector<std::string>& /* args */) {
397 auto result = device->WriteStatus(FastbootResult::OKAY, "Rebooting bootloader");
398 android::base::SetProperty(ANDROID_RB_PROPERTY, "reboot,bootloader");
399 device->CloseDevice();
400 TEMP_FAILURE_RETRY(pause());
401 return result;
402}
403
404bool RebootFastbootHandler(FastbootDevice* device, const std::vector<std::string>& /* args */) {
405 auto result = device->WriteStatus(FastbootResult::OKAY, "Rebooting fastboot");
406 android::base::SetProperty(ANDROID_RB_PROPERTY, "reboot,fastboot");
407 device->CloseDevice();
408 TEMP_FAILURE_RETRY(pause());
409 return result;
410}
411
412static bool EnterRecovery() {
413 const char msg_switch_to_recovery = 'r';
414
415 android::base::unique_fd sock(socket(AF_UNIX, SOCK_STREAM, 0));
416 if (sock < 0) {
417 PLOG(ERROR) << "Couldn't create sock";
418 return false;
419 }
420
421 struct sockaddr_un addr = {.sun_family = AF_UNIX};
422 strncpy(addr.sun_path, "/dev/socket/recovery", sizeof(addr.sun_path) - 1);
Yifan Hong07e947f2021-03-22 19:21:34 -0700423 if (connect(sock.get(), (struct sockaddr*)&addr, sizeof(addr)) < 0) {
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700424 PLOG(ERROR) << "Couldn't connect to recovery";
425 return false;
426 }
427 // Switch to recovery will not update the boot reason since it does not
428 // require a reboot.
Yifan Hong07e947f2021-03-22 19:21:34 -0700429 auto ret = write(sock.get(), &msg_switch_to_recovery, sizeof(msg_switch_to_recovery));
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700430 if (ret != sizeof(msg_switch_to_recovery)) {
431 PLOG(ERROR) << "Couldn't write message to switch to recovery";
432 return false;
433 }
434
435 return true;
436}
437
438bool RebootRecoveryHandler(FastbootDevice* device, const std::vector<std::string>& /* args */) {
439 auto status = true;
440 if (EnterRecovery()) {
441 status = device->WriteStatus(FastbootResult::OKAY, "Rebooting to recovery");
442 } else {
443 status = device->WriteStatus(FastbootResult::FAIL, "Unable to reboot to recovery");
444 }
445 device->CloseDevice();
446 TEMP_FAILURE_RETRY(pause());
447 return status;
448}
David Anderson0d4277d2018-07-31 13:27:37 -0700449
450// Helper class for opening a handle to a MetadataBuilder and writing the new
451// partition table to the same place it was read.
452class PartitionBuilder {
453 public:
David Andersond25f1c32018-11-09 20:41:33 -0800454 explicit PartitionBuilder(FastbootDevice* device, const std::string& partition_name);
David Anderson0d4277d2018-07-31 13:27:37 -0700455
456 bool Write();
457 bool Valid() const { return !!builder_; }
458 MetadataBuilder* operator->() const { return builder_.get(); }
459
460 private:
David Anderson4d307b02018-12-17 17:07:34 -0800461 FastbootDevice* device_;
David Anderson0d4277d2018-07-31 13:27:37 -0700462 std::string super_device_;
David Andersond25f1c32018-11-09 20:41:33 -0800463 uint32_t slot_number_;
David Anderson0d4277d2018-07-31 13:27:37 -0700464 std::unique_ptr<MetadataBuilder> builder_;
465};
466
David Anderson4d307b02018-12-17 17:07:34 -0800467PartitionBuilder::PartitionBuilder(FastbootDevice* device, const std::string& partition_name)
468 : device_(device) {
David Andersond25f1c32018-11-09 20:41:33 -0800469 std::string slot_suffix = GetSuperSlotSuffix(device, partition_name);
David Anderson27475322019-06-11 14:00:08 -0700470 slot_number_ = android::fs_mgr::SlotNumberForSlotSuffix(slot_suffix);
David Andersond25f1c32018-11-09 20:41:33 -0800471 auto super_device = FindPhysicalPartition(fs_mgr_get_super_partition_name(slot_number_));
David Anderson0d4277d2018-07-31 13:27:37 -0700472 if (!super_device) {
473 return;
474 }
475 super_device_ = *super_device;
David Andersond25f1c32018-11-09 20:41:33 -0800476 builder_ = MetadataBuilder::New(super_device_, slot_number_);
David Anderson0d4277d2018-07-31 13:27:37 -0700477}
478
479bool PartitionBuilder::Write() {
David Anderson27475322019-06-11 14:00:08 -0700480 auto metadata = builder_->Export();
David Anderson0d4277d2018-07-31 13:27:37 -0700481 if (!metadata) {
482 return false;
483 }
David Anderson4d307b02018-12-17 17:07:34 -0800484 return UpdateAllPartitionMetadata(device_, super_device_, *metadata.get());
David Anderson0d4277d2018-07-31 13:27:37 -0700485}
486
487bool CreatePartitionHandler(FastbootDevice* device, const std::vector<std::string>& args) {
488 if (args.size() < 3) {
489 return device->WriteFail("Invalid partition name and size");
490 }
491
Hridya Valsarajudca328d2018-09-24 16:01:35 -0700492 if (GetDeviceLockStatus()) {
493 return device->WriteStatus(FastbootResult::FAIL, "Command not available on locked devices");
494 }
495
David Anderson0d4277d2018-07-31 13:27:37 -0700496 uint64_t partition_size;
497 std::string partition_name = args[1];
498 if (!android::base::ParseUint(args[2].c_str(), &partition_size)) {
499 return device->WriteFail("Invalid partition size");
500 }
501
David Andersond25f1c32018-11-09 20:41:33 -0800502 PartitionBuilder builder(device, partition_name);
David Anderson0d4277d2018-07-31 13:27:37 -0700503 if (!builder.Valid()) {
504 return device->WriteFail("Could not open super partition");
505 }
506 // TODO(112433293) Disallow if the name is in the physical table as well.
507 if (builder->FindPartition(partition_name)) {
508 return device->WriteFail("Partition already exists");
509 }
510
David Anderson27475322019-06-11 14:00:08 -0700511 auto partition = builder->AddPartition(partition_name, 0);
David Anderson0d4277d2018-07-31 13:27:37 -0700512 if (!partition) {
513 return device->WriteFail("Failed to add partition");
514 }
515 if (!builder->ResizePartition(partition, partition_size)) {
516 builder->RemovePartition(partition_name);
517 return device->WriteFail("Not enough space for partition");
518 }
519 if (!builder.Write()) {
520 return device->WriteFail("Failed to write partition table");
521 }
522 return device->WriteOkay("Partition created");
523}
524
525bool DeletePartitionHandler(FastbootDevice* device, const std::vector<std::string>& args) {
526 if (args.size() < 2) {
527 return device->WriteFail("Invalid partition name and size");
528 }
529
Hridya Valsarajudca328d2018-09-24 16:01:35 -0700530 if (GetDeviceLockStatus()) {
531 return device->WriteStatus(FastbootResult::FAIL, "Command not available on locked devices");
532 }
533
David Andersond25f1c32018-11-09 20:41:33 -0800534 std::string partition_name = args[1];
535
536 PartitionBuilder builder(device, partition_name);
David Anderson0d4277d2018-07-31 13:27:37 -0700537 if (!builder.Valid()) {
538 return device->WriteFail("Could not open super partition");
539 }
David Andersond25f1c32018-11-09 20:41:33 -0800540 builder->RemovePartition(partition_name);
David Anderson0d4277d2018-07-31 13:27:37 -0700541 if (!builder.Write()) {
542 return device->WriteFail("Failed to write partition table");
543 }
544 return device->WriteOkay("Partition deleted");
545}
546
547bool ResizePartitionHandler(FastbootDevice* device, const std::vector<std::string>& args) {
548 if (args.size() < 3) {
549 return device->WriteFail("Invalid partition name and size");
550 }
551
Hridya Valsarajudca328d2018-09-24 16:01:35 -0700552 if (GetDeviceLockStatus()) {
553 return device->WriteStatus(FastbootResult::FAIL, "Command not available on locked devices");
554 }
555
David Anderson0d4277d2018-07-31 13:27:37 -0700556 uint64_t partition_size;
557 std::string partition_name = args[1];
558 if (!android::base::ParseUint(args[2].c_str(), &partition_size)) {
559 return device->WriteFail("Invalid partition size");
560 }
561
David Andersond25f1c32018-11-09 20:41:33 -0800562 PartitionBuilder builder(device, partition_name);
David Anderson0d4277d2018-07-31 13:27:37 -0700563 if (!builder.Valid()) {
564 return device->WriteFail("Could not open super partition");
565 }
566
David Anderson27475322019-06-11 14:00:08 -0700567 auto partition = builder->FindPartition(partition_name);
David Anderson0d4277d2018-07-31 13:27:37 -0700568 if (!partition) {
569 return device->WriteFail("Partition does not exist");
570 }
David Andersonad970fc2019-08-27 14:01:16 -0700571
572 // Remove the updated flag to cancel any snapshots.
573 uint32_t attrs = partition->attributes();
574 partition->set_attributes(attrs & ~LP_PARTITION_ATTR_UPDATED);
575
David Anderson0d4277d2018-07-31 13:27:37 -0700576 if (!builder->ResizePartition(partition, partition_size)) {
577 return device->WriteFail("Not enough space to resize partition");
578 }
579 if (!builder.Write()) {
580 return device->WriteFail("Failed to write partition table");
581 }
582 return device->WriteOkay("Partition resized");
583}
David Anderson38b3c7a2018-08-15 16:27:42 -0700584
David Andersonad970fc2019-08-27 14:01:16 -0700585void CancelPartitionSnapshot(FastbootDevice* device, const std::string& partition_name) {
586 PartitionBuilder builder(device, partition_name);
587 if (!builder.Valid()) return;
588
589 auto partition = builder->FindPartition(partition_name);
590 if (!partition) return;
591
592 // Remove the updated flag to cancel any snapshots.
593 uint32_t attrs = partition->attributes();
594 partition->set_attributes(attrs & ~LP_PARTITION_ATTR_UPDATED);
595
596 builder.Write();
597}
598
599bool FlashHandler(FastbootDevice* device, const std::vector<std::string>& args) {
600 if (args.size() < 2) {
601 return device->WriteStatus(FastbootResult::FAIL, "Invalid arguments");
602 }
603
604 if (GetDeviceLockStatus()) {
605 return device->WriteStatus(FastbootResult::FAIL,
606 "Flashing is not allowed on locked devices");
607 }
608
609 const auto& partition_name = args[1];
David Anderson220ddb12019-10-31 18:02:41 -0700610 if (IsProtectedPartitionDuringMerge(device, partition_name)) {
611 auto message = "Cannot flash " + partition_name + " while a snapshot update is in progress";
612 return device->WriteFail(message);
613 }
614
David Andersonad970fc2019-08-27 14:01:16 -0700615 if (LogicalPartitionExists(device, partition_name)) {
616 CancelPartitionSnapshot(device, partition_name);
617 }
618
619 int ret = Flash(device, partition_name);
620 if (ret < 0) {
621 return device->WriteStatus(FastbootResult::FAIL, strerror(-ret));
622 }
Florian Mayer4c3c5262022-09-14 16:02:11 -0700623 if (partition_name == "userdata") {
624 PostWipeData();
625 }
626
David Andersonad970fc2019-08-27 14:01:16 -0700627 return device->WriteStatus(FastbootResult::OKAY, "Flashing succeeded");
628}
629
David Anderson38b3c7a2018-08-15 16:27:42 -0700630bool UpdateSuperHandler(FastbootDevice* device, const std::vector<std::string>& args) {
631 if (args.size() < 2) {
632 return device->WriteFail("Invalid arguments");
633 }
Hridya Valsarajudca328d2018-09-24 16:01:35 -0700634
635 if (GetDeviceLockStatus()) {
636 return device->WriteStatus(FastbootResult::FAIL, "Command not available on locked devices");
637 }
638
David Anderson38b3c7a2018-08-15 16:27:42 -0700639 bool wipe = (args.size() >= 3 && args[2] == "wipe");
640 return UpdateSuper(device, args[1], wipe);
641}
David Anderson1d504e32019-01-15 14:38:20 -0800642
Chun-Wei Wange72b3ad2023-09-07 09:53:11 +0800643static bool IsLockedDsu() {
644 std::string active_dsu;
645 android::gsi::GetActiveDsu(&active_dsu);
646 return android::base::EndsWith(active_dsu, ".lock");
647}
648
David Anderson3d782d52019-01-29 13:09:49 -0800649bool GsiHandler(FastbootDevice* device, const std::vector<std::string>& args) {
David Anderson1d504e32019-01-15 14:38:20 -0800650 if (args.size() != 2) {
651 return device->WriteFail("Invalid arguments");
652 }
David Anderson3d782d52019-01-29 13:09:49 -0800653
654 AutoMountMetadata mount_metadata;
655 if (!mount_metadata) {
656 return device->WriteFail("Could not find GSI install");
657 }
658
659 if (!android::gsi::IsGsiInstalled()) {
660 return device->WriteStatus(FastbootResult::FAIL, "No GSI is installed");
661 }
662
Chun-Wei Wange72b3ad2023-09-07 09:53:11 +0800663 if ((args[1] == "wipe" || args[1] == "disable") && GetDeviceLockStatus() && IsLockedDsu()) {
664 // Block commands that modify the states of locked DSU
665 return device->WriteFail("Command not available on locked DSU/devices");
666 }
667
David Anderson1d504e32019-01-15 14:38:20 -0800668 if (args[1] == "wipe") {
669 if (!android::gsi::UninstallGsi()) {
670 return device->WriteStatus(FastbootResult::FAIL, strerror(errno));
671 }
672 } else if (args[1] == "disable") {
673 if (!android::gsi::DisableGsi()) {
674 return device->WriteStatus(FastbootResult::FAIL, strerror(errno));
675 }
Chun-Wei Wang671a2a52023-08-30 07:55:43 +0000676 } else if (args[1] == "status") {
677 std::string active_dsu;
678 if (!android::gsi::IsGsiRunning()) {
679 device->WriteInfo("Not running");
680 } else if (!android::gsi::GetActiveDsu(&active_dsu)) {
681 return device->WriteFail(strerror(errno));
682 } else {
683 device->WriteInfo("Running active DSU: " + active_dsu);
684 }
685 } else {
686 return device->WriteFail("Invalid arguments");
David Anderson1d504e32019-01-15 14:38:20 -0800687 }
688 return device->WriteStatus(FastbootResult::OKAY, "Success");
689}
David Andersonab8f4662019-10-21 16:45:59 -0700690
691bool SnapshotUpdateHandler(FastbootDevice* device, const std::vector<std::string>& args) {
692 // Note that we use the HAL rather than mounting /metadata, since we want
693 // our results to match the bootloader.
David Anderson220ddb12019-10-31 18:02:41 -0700694 auto hal = device->boot1_1();
David Andersonab8f4662019-10-21 16:45:59 -0700695 if (!hal) return device->WriteFail("Not supported");
696
David Andersonab8f4662019-10-21 16:45:59 -0700697 // If no arguments, return the same thing as a getvar. Note that we get the
698 // HAL first so we can return "not supported" before we return the less
699 // specific error message below.
700 if (args.size() < 2 || args[1].empty()) {
701 std::string message;
702 if (!GetSnapshotUpdateStatus(device, {}, &message)) {
703 return device->WriteFail("Could not determine update status");
704 }
705 device->WriteInfo(message);
706 return device->WriteOkay("");
707 }
708
David Anderson220ddb12019-10-31 18:02:41 -0700709 MergeStatus status = hal->getSnapshotMergeStatus();
710
711 if (args.size() != 2) {
David Andersonab8f4662019-10-21 16:45:59 -0700712 return device->WriteFail("Invalid arguments");
713 }
David Anderson220ddb12019-10-31 18:02:41 -0700714 if (args[1] == "cancel") {
715 switch (status) {
716 case MergeStatus::SNAPSHOTTED:
Kelvin Zhang6befe782022-06-21 14:20:54 -0700717 case MergeStatus::MERGING: {
718 const auto ret = hal->SetSnapshotMergeStatus(MergeStatus::CANCELLED);
719 if (!ret.success) {
720 device->WriteFail("Failed to SetSnapshotMergeStatus(MergeStatus::CANCELLED) " +
721 ret.errMsg);
722 }
David Anderson220ddb12019-10-31 18:02:41 -0700723 break;
Kelvin Zhang6befe782022-06-21 14:20:54 -0700724 }
David Anderson220ddb12019-10-31 18:02:41 -0700725 default:
726 break;
727 }
728 } else if (args[1] == "merge") {
729 if (status != MergeStatus::MERGING) {
730 return device->WriteFail("No snapshot merge is in progress");
731 }
David Andersonab8f4662019-10-21 16:45:59 -0700732
David Anderson565577f2021-02-04 20:14:18 -0800733 auto sm = SnapshotManager::New();
David Anderson220ddb12019-10-31 18:02:41 -0700734 if (!sm) {
735 return device->WriteFail("Unable to create SnapshotManager");
736 }
David Anderson5a0177d2020-04-30 18:53:23 -0700737 if (!sm->FinishMergeInRecovery()) {
David Anderson220ddb12019-10-31 18:02:41 -0700738 return device->WriteFail("Unable to finish snapshot merge");
739 }
740 } else {
741 return device->WriteFail("Invalid parameter to snapshot-update");
David Andersonab8f4662019-10-21 16:45:59 -0700742 }
743 return device->WriteStatus(FastbootResult::OKAY, "Success");
744}
Yifan Honga4eb4752021-02-16 19:37:21 -0800745
746namespace {
747// Helper of FetchHandler.
748class PartitionFetcher {
749 public:
750 static bool Fetch(FastbootDevice* device, const std::vector<std::string>& args) {
751 if constexpr (!kEnableFetch) {
752 return device->WriteFail("Fetch is not allowed on user build");
753 }
754
755 if (GetDeviceLockStatus()) {
756 return device->WriteFail("Fetch is not allowed on locked devices");
757 }
758
759 PartitionFetcher fetcher(device, args);
760 if (fetcher.Open()) {
761 fetcher.Fetch();
762 }
763 CHECK(fetcher.ret_.has_value());
764 return *fetcher.ret_;
765 }
766
767 private:
768 PartitionFetcher(FastbootDevice* device, const std::vector<std::string>& args)
769 : device_(device), args_(&args) {}
770 // Return whether the partition is successfully opened.
771 // If successfully opened, ret_ is left untouched. Otherwise, ret_ is set to the value
772 // that FetchHandler should return.
773 bool Open() {
Yifan Hongbcd27702021-02-16 19:37:32 -0800774 if (args_->size() < 2) {
775 ret_ = device_->WriteFail("Missing partition arg");
Yifan Honga4eb4752021-02-16 19:37:21 -0800776 return false;
777 }
778
Yifan Hongbcd27702021-02-16 19:37:32 -0800779 partition_name_ = args_->at(1);
780 if (std::find(kAllowedPartitions.begin(), kAllowedPartitions.end(), partition_name_) ==
781 kAllowedPartitions.end()) {
782 ret_ = device_->WriteFail("Fetch is only allowed on [" +
783 android::base::Join(kAllowedPartitions, ", ") + "]");
784 return false;
785 }
786
Konstantin Vyshetsky81cc1192021-11-04 10:27:06 -0700787 if (!OpenPartition(device_, partition_name_, &handle_, O_RDONLY)) {
Yifan Honga4eb4752021-02-16 19:37:21 -0800788 ret_ = device_->WriteFail(
789 android::base::StringPrintf("Cannot open %s", partition_name_.c_str()));
790 return false;
791 }
792
793 partition_size_ = get_block_device_size(handle_.fd());
794 if (partition_size_ == 0) {
795 ret_ = device_->WriteOkay(android::base::StringPrintf("Partition %s has size 0",
796 partition_name_.c_str()));
797 return false;
798 }
799
800 start_offset_ = 0;
801 if (args_->size() >= 3) {
802 if (!android::base::ParseUint(args_->at(2), &start_offset_)) {
803 ret_ = device_->WriteFail("Invalid offset, must be integer");
804 return false;
805 }
806 if (start_offset_ > std::numeric_limits<off64_t>::max()) {
807 ret_ = device_->WriteFail(
808 android::base::StringPrintf("Offset overflows: %" PRIx64, start_offset_));
809 return false;
810 }
811 }
812 if (start_offset_ > partition_size_) {
813 ret_ = device_->WriteFail(android::base::StringPrintf(
814 "Invalid offset 0x%" PRIx64 ", partition %s has size 0x%" PRIx64, start_offset_,
815 partition_name_.c_str(), partition_size_));
816 return false;
817 }
818 uint64_t maximum_total_size_to_read = partition_size_ - start_offset_;
819 total_size_to_read_ = maximum_total_size_to_read;
820 if (args_->size() >= 4) {
821 if (!android::base::ParseUint(args_->at(3), &total_size_to_read_)) {
822 ret_ = device_->WriteStatus(FastbootResult::FAIL, "Invalid size, must be integer");
823 return false;
824 }
825 }
826 if (total_size_to_read_ == 0) {
827 ret_ = device_->WriteOkay("Read 0 bytes");
828 return false;
829 }
830 if (total_size_to_read_ > maximum_total_size_to_read) {
831 ret_ = device_->WriteFail(android::base::StringPrintf(
832 "Invalid size to read 0x%" PRIx64 ", partition %s has size 0x%" PRIx64
833 " and fetching from offset 0x%" PRIx64,
834 total_size_to_read_, partition_name_.c_str(), partition_size_, start_offset_));
835 return false;
836 }
837
838 if (total_size_to_read_ > kMaxFetchSizeDefault) {
839 ret_ = device_->WriteFail(android::base::StringPrintf(
840 "Cannot fetch 0x%" PRIx64
841 " bytes because it exceeds maximum transport size 0x%x",
842 partition_size_, kMaxDownloadSizeDefault));
843 return false;
844 }
845
846 return true;
847 }
848
849 // Assume Open() returns true.
850 // After execution, ret_ is set to the value that FetchHandler should return.
851 void Fetch() {
852 CHECK(start_offset_ <= std::numeric_limits<off64_t>::max());
853 if (lseek64(handle_.fd(), start_offset_, SEEK_SET) != static_cast<off64_t>(start_offset_)) {
854 ret_ = device_->WriteFail(android::base::StringPrintf(
855 "On partition %s, unable to lseek(0x%" PRIx64 ": %s", partition_name_.c_str(),
856 start_offset_, strerror(errno)));
857 return;
858 }
859
860 if (!device_->WriteStatus(FastbootResult::DATA,
861 android::base::StringPrintf(
862 "%08x", static_cast<uint32_t>(total_size_to_read_)))) {
863 ret_ = false;
864 return;
865 }
866 uint64_t end_offset = start_offset_ + total_size_to_read_;
867 std::vector<char> buf(1_MiB);
868 uint64_t current_offset = start_offset_;
869 while (current_offset < end_offset) {
870 // On any error, exit. We can't return a status message to the driver because
871 // we are in the middle of writing data, so just let the driver guess what's wrong
872 // by ending the data stream prematurely.
873 uint64_t remaining = end_offset - current_offset;
874 uint64_t chunk_size = std::min<uint64_t>(buf.size(), remaining);
875 if (!android::base::ReadFully(handle_.fd(), buf.data(), chunk_size)) {
876 PLOG(ERROR) << std::hex << "Unable to read 0x" << chunk_size << " bytes from "
877 << partition_name_ << " @ offset 0x" << current_offset;
878 ret_ = false;
879 return;
880 }
881 if (!device_->HandleData(false /* is read */, buf.data(), chunk_size)) {
882 PLOG(ERROR) << std::hex << "Unable to send 0x" << chunk_size << " bytes of "
883 << partition_name_ << " @ offset 0x" << current_offset;
884 ret_ = false;
885 return;
886 }
887 current_offset += chunk_size;
888 }
889
890 ret_ = device_->WriteOkay(android::base::StringPrintf(
891 "Fetched %s (offset=0x%" PRIx64 ", size=0x%" PRIx64, partition_name_.c_str(),
892 start_offset_, total_size_to_read_));
893 }
894
Yifan Hongbcd27702021-02-16 19:37:32 -0800895 static constexpr std::array<const char*, 3> kAllowedPartitions{
896 "vendor_boot",
897 "vendor_boot_a",
898 "vendor_boot_b",
899 };
900
Yifan Honga4eb4752021-02-16 19:37:21 -0800901 FastbootDevice* device_;
902 const std::vector<std::string>* args_ = nullptr;
903 std::string partition_name_;
904 PartitionHandle handle_;
905 uint64_t partition_size_ = 0;
906 uint64_t start_offset_ = 0;
907 uint64_t total_size_to_read_ = 0;
908
909 // What FetchHandler should return.
910 std::optional<bool> ret_ = std::nullopt;
911};
912} // namespace
913
914bool FetchHandler(FastbootDevice* device, const std::vector<std::string>& args) {
915 return PartitionFetcher::Fetch(device, args);
916}