blob: d60539332aea655a22766eb4ea0579c94f6f9bb9 [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}},
137 {FB_VAR_BATTERY_SOC_OK, {GetBatterySoCOk, nullptr}},
138 {FB_VAR_HW_REVISION, {GetHardwareRevision, nullptr}},
139 {FB_VAR_SUPER_PARTITION_NAME, {GetSuperPartitionName, nullptr}},
140 {FB_VAR_SNAPSHOT_UPDATE_STATUS, {GetSnapshotUpdateStatus, nullptr}},
141 {FB_VAR_CPU_ABI, {GetCpuAbi, nullptr}},
142 {FB_VAR_SYSTEM_FINGERPRINT, {GetSystemFingerprint, nullptr}},
143 {FB_VAR_VENDOR_FINGERPRINT, {GetVendorFingerprint, nullptr}},
144 {FB_VAR_DYNAMIC_PARTITION, {GetDynamicPartition, nullptr}},
145 {FB_VAR_FIRST_API_LEVEL, {GetFirstApiLevel, nullptr}},
146 {FB_VAR_SECURITY_PATCH_LEVEL, {GetSecurityPatchLevel, nullptr}},
147 {FB_VAR_TREBLE_ENABLED, {GetTrebleEnabled, nullptr}},
148 {FB_VAR_MAX_FETCH_SIZE, {GetMaxFetchSize, nullptr}},
149};
David Anderson0f626632018-08-31 16:44:25 -0700150
David Andersonebc8fe12022-06-17 19:17:43 -0700151static bool GetVarAll(FastbootDevice* device) {
152 for (const auto& [name, handlers] : kVariableMap) {
153 GetAllVars(device, name, handlers);
154 }
155 return true;
156}
157
Florian Mayer4c3c5262022-09-14 16:02:11 -0700158static void PostWipeData() {
159 std::string err;
160 // Reset mte state of device.
161 if (!WriteMiscMemtagMessage({}, &err)) {
162 LOG(ERROR) << "Failed to reset MTE state: " << err;
163 }
164}
165
David Andersonebc8fe12022-06-17 19:17:43 -0700166const std::unordered_map<std::string, std::function<bool(FastbootDevice*)>> kSpecialVars = {
167 {"all", GetVarAll},
168 {"dmesg", GetDmesg},
169};
170
171bool GetVarHandler(FastbootDevice* device, const std::vector<std::string>& args) {
David Anderson0f626632018-08-31 16:44:25 -0700172 if (args.size() < 2) {
173 return device->WriteFail("Missing argument");
174 }
175
David Andersonebc8fe12022-06-17 19:17:43 -0700176 // "all" and "dmesg" are multiline and handled specially.
177 auto found_special = kSpecialVars.find(args[1]);
178 if (found_special != kSpecialVars.end()) {
179 if (!found_special->second(device)) {
180 return false;
David Anderson0f626632018-08-31 16:44:25 -0700181 }
182 return device->WriteOkay("");
183 }
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700184
185 // args[0] is command name, args[1] is variable.
186 auto found_variable = kVariableMap.find(args[1]);
187 if (found_variable == kVariableMap.end()) {
David Anderson1fb3fd72018-08-31 14:40:22 -0700188 return device->WriteFail("Unknown variable");
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700189 }
190
David Anderson1fb3fd72018-08-31 14:40:22 -0700191 std::string message;
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700192 std::vector<std::string> getvar_args(args.begin() + 2, args.end());
David Anderson0f626632018-08-31 16:44:25 -0700193 if (!found_variable->second.get(device, getvar_args, &message)) {
David Anderson1fb3fd72018-08-31 14:40:22 -0700194 return device->WriteFail(message);
195 }
196 return device->WriteOkay(message);
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700197}
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700198
josephjang29069752020-09-23 16:28:03 +0800199bool OemPostWipeData(FastbootDevice* device) {
200 auto fastboot_hal = device->fastboot_hal();
201 if (!fastboot_hal) {
202 return false;
203 }
204
Sandeep Dhavale2534d482022-11-08 22:30:05 +0000205 auto status = fastboot_hal->doOemSpecificErase();
206 if (status.isOk()) {
josephjang29069752020-09-23 16:28:03 +0800207 device->WriteStatus(FastbootResult::OKAY, "Erasing succeeded");
Sandeep Dhavale2534d482022-11-08 22:30:05 +0000208 return true;
josephjang29069752020-09-23 16:28:03 +0800209 }
Sandeep Dhavale2534d482022-11-08 22:30:05 +0000210 switch (status.getExceptionCode()) {
211 case EX_UNSUPPORTED_OPERATION:
212 return false;
213 case EX_SERVICE_SPECIFIC:
214 device->WriteStatus(FastbootResult::FAIL, status.getDescription());
215 return false;
216 default:
217 LOG(ERROR) << "Erase operation failed" << status.getDescription();
218 return false;
219 }
josephjang29069752020-09-23 16:28:03 +0800220}
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 }
Sandeep Dhavale2534d482022-11-08 22:30:05 +0000269 std::string message;
270 auto status = fastboot_hal->doOemCommand(args[0], &message);
271 if (!status.isOk()) {
272 LOG(ERROR) << "Unable to do OEM command " << args[0].c_str() << status.getDescription();
273 return device->WriteStatus(FastbootResult::FAIL,
274 "Unable to do OEM command " + status.getDescription());
Hridya Valsarajua15fe312018-09-14 13:58:21 -0700275 }
276
Sandeep Dhavale2534d482022-11-08 22:30:05 +0000277 device->WriteInfo(message);
278 return device->WriteStatus(FastbootResult::OKAY, message);
Hridya Valsarajua15fe312018-09-14 13:58:21 -0700279}
280
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700281bool DownloadHandler(FastbootDevice* device, const std::vector<std::string>& args) {
282 if (args.size() < 2) {
283 return device->WriteStatus(FastbootResult::FAIL, "size argument unspecified");
284 }
Hridya Valsarajud1e62312018-10-08 09:13:17 -0700285
286 if (GetDeviceLockStatus()) {
287 return device->WriteStatus(FastbootResult::FAIL,
288 "Download is not allowed on locked devices");
289 }
290
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700291 // arg[0] is the command name, arg[1] contains size of data to be downloaded
Keith Mok3724bbc2021-12-30 20:08:04 +0000292 // which should always be 8 bytes
293 if (args[1].length() != 8) {
294 return device->WriteStatus(FastbootResult::FAIL,
295 "Invalid size (length of size != 8)");
296 }
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700297 unsigned int size;
Hridya Valsarajuaae84e82018-10-08 13:10:25 -0700298 if (!android::base::ParseUint("0x" + args[1], &size, kMaxDownloadSizeDefault)) {
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700299 return device->WriteStatus(FastbootResult::FAIL, "Invalid size");
300 }
Keith Mok3724bbc2021-12-30 20:08:04 +0000301 if (size == 0) {
302 return device->WriteStatus(FastbootResult::FAIL, "Invalid size (0)");
303 }
David Anderson12211d12018-07-24 15:21:20 -0700304 device->download_data().resize(size);
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700305 if (!device->WriteStatus(FastbootResult::DATA, android::base::StringPrintf("%08x", size))) {
306 return false;
307 }
308
David Anderson12211d12018-07-24 15:21:20 -0700309 if (device->HandleData(true, &device->download_data())) {
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700310 return device->WriteStatus(FastbootResult::OKAY, "");
311 }
312
313 PLOG(ERROR) << "Couldn't download data";
314 return device->WriteStatus(FastbootResult::FAIL, "Couldn't download data");
315}
316
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700317bool SetActiveHandler(FastbootDevice* device, const std::vector<std::string>& args) {
318 if (args.size() < 2) {
319 return device->WriteStatus(FastbootResult::FAIL, "Missing slot argument");
320 }
321
Hridya Valsarajud1e62312018-10-08 09:13:17 -0700322 if (GetDeviceLockStatus()) {
323 return device->WriteStatus(FastbootResult::FAIL,
324 "set_active command is not allowed on locked devices");
325 }
326
Kelvin Zhang6befe782022-06-21 14:20:54 -0700327 int32_t slot = 0;
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700328 if (!GetSlotNumber(args[1], &slot)) {
David Anderson220ddb12019-10-31 18:02:41 -0700329 // Slot suffix needs to be between 'a' and 'z'.
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700330 return device->WriteStatus(FastbootResult::FAIL, "Bad slot suffix");
331 }
332
333 // Non-A/B devices will not have a boot control HAL.
334 auto boot_control_hal = device->boot_control_hal();
335 if (!boot_control_hal) {
336 return device->WriteStatus(FastbootResult::FAIL,
337 "Cannot set slot: boot control HAL absent");
338 }
Kelvin Zhang6befe782022-06-21 14:20:54 -0700339 if (slot >= boot_control_hal->GetNumSlots()) {
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700340 return device->WriteStatus(FastbootResult::FAIL, "Slot out of range");
341 }
David Anderson220ddb12019-10-31 18:02:41 -0700342
343 // If the slot is not changing, do nothing.
Hridya Valsaraju45719a82020-03-02 13:03:47 -0800344 if (args[1] == device->GetCurrentSlot()) {
David Anderson220ddb12019-10-31 18:02:41 -0700345 return device->WriteOkay("");
346 }
347
348 // Check how to handle the current snapshot state.
349 if (auto hal11 = device->boot1_1()) {
350 auto merge_status = hal11->getSnapshotMergeStatus();
351 if (merge_status == MergeStatus::MERGING) {
352 return device->WriteFail("Cannot change slots while a snapshot update is in progress");
353 }
354 // Note: we allow the slot change if the state is SNAPSHOTTED. First-
355 // stage init does not have access to the HAL, and uses the slot number
356 // and /metadata OTA state to determine whether a slot change occurred.
357 // Booting into the old slot would erase the OTA, and switching A->B->A
358 // would simply resume it if no boots occur in between. Re-flashing
359 // partitions implicitly cancels the OTA, so leaving the state as-is is
360 // safe.
361 if (merge_status == MergeStatus::SNAPSHOTTED) {
362 device->WriteInfo(
363 "Changing the active slot with a snapshot applied may cancel the"
364 " update.");
365 }
366 }
367
Kelvin Zhang6befe782022-06-21 14:20:54 -0700368 CommandResult ret = boot_control_hal->SetActiveBootSlot(slot);
369 if (ret.success) {
Hridya Valsaraju20bdf892018-10-10 11:02:19 -0700370 // Save as slot suffix to match the suffix format as returned from
371 // the boot control HAL.
372 auto current_slot = "_" + args[1];
373 device->set_active_slot(current_slot);
374 return device->WriteStatus(FastbootResult::OKAY, "");
375 }
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700376 return device->WriteStatus(FastbootResult::FAIL, "Unable to set slot");
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700377}
378
379bool ShutDownHandler(FastbootDevice* device, const std::vector<std::string>& /* args */) {
380 auto result = device->WriteStatus(FastbootResult::OKAY, "Shutting down");
381 android::base::SetProperty(ANDROID_RB_PROPERTY, "shutdown,fastboot");
382 device->CloseDevice();
383 TEMP_FAILURE_RETRY(pause());
384 return result;
385}
386
387bool RebootHandler(FastbootDevice* device, const std::vector<std::string>& /* args */) {
388 auto result = device->WriteStatus(FastbootResult::OKAY, "Rebooting");
389 android::base::SetProperty(ANDROID_RB_PROPERTY, "reboot,from_fastboot");
390 device->CloseDevice();
391 TEMP_FAILURE_RETRY(pause());
392 return result;
393}
394
395bool RebootBootloaderHandler(FastbootDevice* device, const std::vector<std::string>& /* args */) {
396 auto result = device->WriteStatus(FastbootResult::OKAY, "Rebooting bootloader");
397 android::base::SetProperty(ANDROID_RB_PROPERTY, "reboot,bootloader");
398 device->CloseDevice();
399 TEMP_FAILURE_RETRY(pause());
400 return result;
401}
402
403bool RebootFastbootHandler(FastbootDevice* device, const std::vector<std::string>& /* args */) {
404 auto result = device->WriteStatus(FastbootResult::OKAY, "Rebooting fastboot");
405 android::base::SetProperty(ANDROID_RB_PROPERTY, "reboot,fastboot");
406 device->CloseDevice();
407 TEMP_FAILURE_RETRY(pause());
408 return result;
409}
410
411static bool EnterRecovery() {
412 const char msg_switch_to_recovery = 'r';
413
414 android::base::unique_fd sock(socket(AF_UNIX, SOCK_STREAM, 0));
415 if (sock < 0) {
416 PLOG(ERROR) << "Couldn't create sock";
417 return false;
418 }
419
420 struct sockaddr_un addr = {.sun_family = AF_UNIX};
421 strncpy(addr.sun_path, "/dev/socket/recovery", sizeof(addr.sun_path) - 1);
Yifan Hong07e947f2021-03-22 19:21:34 -0700422 if (connect(sock.get(), (struct sockaddr*)&addr, sizeof(addr)) < 0) {
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700423 PLOG(ERROR) << "Couldn't connect to recovery";
424 return false;
425 }
426 // Switch to recovery will not update the boot reason since it does not
427 // require a reboot.
Yifan Hong07e947f2021-03-22 19:21:34 -0700428 auto ret = write(sock.get(), &msg_switch_to_recovery, sizeof(msg_switch_to_recovery));
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700429 if (ret != sizeof(msg_switch_to_recovery)) {
430 PLOG(ERROR) << "Couldn't write message to switch to recovery";
431 return false;
432 }
433
434 return true;
435}
436
437bool RebootRecoveryHandler(FastbootDevice* device, const std::vector<std::string>& /* args */) {
438 auto status = true;
439 if (EnterRecovery()) {
440 status = device->WriteStatus(FastbootResult::OKAY, "Rebooting to recovery");
441 } else {
442 status = device->WriteStatus(FastbootResult::FAIL, "Unable to reboot to recovery");
443 }
444 device->CloseDevice();
445 TEMP_FAILURE_RETRY(pause());
446 return status;
447}
David Anderson0d4277d2018-07-31 13:27:37 -0700448
449// Helper class for opening a handle to a MetadataBuilder and writing the new
450// partition table to the same place it was read.
451class PartitionBuilder {
452 public:
David Andersond25f1c32018-11-09 20:41:33 -0800453 explicit PartitionBuilder(FastbootDevice* device, const std::string& partition_name);
David Anderson0d4277d2018-07-31 13:27:37 -0700454
455 bool Write();
456 bool Valid() const { return !!builder_; }
457 MetadataBuilder* operator->() const { return builder_.get(); }
458
459 private:
David Anderson4d307b02018-12-17 17:07:34 -0800460 FastbootDevice* device_;
David Anderson0d4277d2018-07-31 13:27:37 -0700461 std::string super_device_;
David Andersond25f1c32018-11-09 20:41:33 -0800462 uint32_t slot_number_;
David Anderson0d4277d2018-07-31 13:27:37 -0700463 std::unique_ptr<MetadataBuilder> builder_;
464};
465
David Anderson4d307b02018-12-17 17:07:34 -0800466PartitionBuilder::PartitionBuilder(FastbootDevice* device, const std::string& partition_name)
467 : device_(device) {
David Andersond25f1c32018-11-09 20:41:33 -0800468 std::string slot_suffix = GetSuperSlotSuffix(device, partition_name);
David Anderson27475322019-06-11 14:00:08 -0700469 slot_number_ = android::fs_mgr::SlotNumberForSlotSuffix(slot_suffix);
David Andersond25f1c32018-11-09 20:41:33 -0800470 auto super_device = FindPhysicalPartition(fs_mgr_get_super_partition_name(slot_number_));
David Anderson0d4277d2018-07-31 13:27:37 -0700471 if (!super_device) {
472 return;
473 }
474 super_device_ = *super_device;
David Andersond25f1c32018-11-09 20:41:33 -0800475 builder_ = MetadataBuilder::New(super_device_, slot_number_);
David Anderson0d4277d2018-07-31 13:27:37 -0700476}
477
478bool PartitionBuilder::Write() {
David Anderson27475322019-06-11 14:00:08 -0700479 auto metadata = builder_->Export();
David Anderson0d4277d2018-07-31 13:27:37 -0700480 if (!metadata) {
481 return false;
482 }
David Anderson4d307b02018-12-17 17:07:34 -0800483 return UpdateAllPartitionMetadata(device_, super_device_, *metadata.get());
David Anderson0d4277d2018-07-31 13:27:37 -0700484}
485
486bool CreatePartitionHandler(FastbootDevice* device, const std::vector<std::string>& args) {
487 if (args.size() < 3) {
488 return device->WriteFail("Invalid partition name and size");
489 }
490
Hridya Valsarajudca328d2018-09-24 16:01:35 -0700491 if (GetDeviceLockStatus()) {
492 return device->WriteStatus(FastbootResult::FAIL, "Command not available on locked devices");
493 }
494
David Anderson0d4277d2018-07-31 13:27:37 -0700495 uint64_t partition_size;
496 std::string partition_name = args[1];
497 if (!android::base::ParseUint(args[2].c_str(), &partition_size)) {
498 return device->WriteFail("Invalid partition size");
499 }
500
David Andersond25f1c32018-11-09 20:41:33 -0800501 PartitionBuilder builder(device, partition_name);
David Anderson0d4277d2018-07-31 13:27:37 -0700502 if (!builder.Valid()) {
503 return device->WriteFail("Could not open super partition");
504 }
505 // TODO(112433293) Disallow if the name is in the physical table as well.
506 if (builder->FindPartition(partition_name)) {
507 return device->WriteFail("Partition already exists");
508 }
509
David Anderson27475322019-06-11 14:00:08 -0700510 auto partition = builder->AddPartition(partition_name, 0);
David Anderson0d4277d2018-07-31 13:27:37 -0700511 if (!partition) {
512 return device->WriteFail("Failed to add partition");
513 }
514 if (!builder->ResizePartition(partition, partition_size)) {
515 builder->RemovePartition(partition_name);
516 return device->WriteFail("Not enough space for partition");
517 }
518 if (!builder.Write()) {
519 return device->WriteFail("Failed to write partition table");
520 }
521 return device->WriteOkay("Partition created");
522}
523
524bool DeletePartitionHandler(FastbootDevice* device, const std::vector<std::string>& args) {
525 if (args.size() < 2) {
526 return device->WriteFail("Invalid partition name and size");
527 }
528
Hridya Valsarajudca328d2018-09-24 16:01:35 -0700529 if (GetDeviceLockStatus()) {
530 return device->WriteStatus(FastbootResult::FAIL, "Command not available on locked devices");
531 }
532
David Andersond25f1c32018-11-09 20:41:33 -0800533 std::string partition_name = args[1];
534
535 PartitionBuilder builder(device, partition_name);
David Anderson0d4277d2018-07-31 13:27:37 -0700536 if (!builder.Valid()) {
537 return device->WriteFail("Could not open super partition");
538 }
David Andersond25f1c32018-11-09 20:41:33 -0800539 builder->RemovePartition(partition_name);
David Anderson0d4277d2018-07-31 13:27:37 -0700540 if (!builder.Write()) {
541 return device->WriteFail("Failed to write partition table");
542 }
543 return device->WriteOkay("Partition deleted");
544}
545
546bool ResizePartitionHandler(FastbootDevice* device, const std::vector<std::string>& args) {
547 if (args.size() < 3) {
548 return device->WriteFail("Invalid partition name and size");
549 }
550
Hridya Valsarajudca328d2018-09-24 16:01:35 -0700551 if (GetDeviceLockStatus()) {
552 return device->WriteStatus(FastbootResult::FAIL, "Command not available on locked devices");
553 }
554
David Anderson0d4277d2018-07-31 13:27:37 -0700555 uint64_t partition_size;
556 std::string partition_name = args[1];
557 if (!android::base::ParseUint(args[2].c_str(), &partition_size)) {
558 return device->WriteFail("Invalid partition size");
559 }
560
David Andersond25f1c32018-11-09 20:41:33 -0800561 PartitionBuilder builder(device, partition_name);
David Anderson0d4277d2018-07-31 13:27:37 -0700562 if (!builder.Valid()) {
563 return device->WriteFail("Could not open super partition");
564 }
565
David Anderson27475322019-06-11 14:00:08 -0700566 auto partition = builder->FindPartition(partition_name);
David Anderson0d4277d2018-07-31 13:27:37 -0700567 if (!partition) {
568 return device->WriteFail("Partition does not exist");
569 }
David Andersonad970fc2019-08-27 14:01:16 -0700570
571 // Remove the updated flag to cancel any snapshots.
572 uint32_t attrs = partition->attributes();
573 partition->set_attributes(attrs & ~LP_PARTITION_ATTR_UPDATED);
574
David Anderson0d4277d2018-07-31 13:27:37 -0700575 if (!builder->ResizePartition(partition, partition_size)) {
576 return device->WriteFail("Not enough space to resize partition");
577 }
578 if (!builder.Write()) {
579 return device->WriteFail("Failed to write partition table");
580 }
581 return device->WriteOkay("Partition resized");
582}
David Anderson38b3c7a2018-08-15 16:27:42 -0700583
David Andersonad970fc2019-08-27 14:01:16 -0700584void CancelPartitionSnapshot(FastbootDevice* device, const std::string& partition_name) {
585 PartitionBuilder builder(device, partition_name);
586 if (!builder.Valid()) return;
587
588 auto partition = builder->FindPartition(partition_name);
589 if (!partition) return;
590
591 // Remove the updated flag to cancel any snapshots.
592 uint32_t attrs = partition->attributes();
593 partition->set_attributes(attrs & ~LP_PARTITION_ATTR_UPDATED);
594
595 builder.Write();
596}
597
598bool FlashHandler(FastbootDevice* device, const std::vector<std::string>& args) {
599 if (args.size() < 2) {
600 return device->WriteStatus(FastbootResult::FAIL, "Invalid arguments");
601 }
602
603 if (GetDeviceLockStatus()) {
604 return device->WriteStatus(FastbootResult::FAIL,
605 "Flashing is not allowed on locked devices");
606 }
607
608 const auto& partition_name = args[1];
David Anderson220ddb12019-10-31 18:02:41 -0700609 if (IsProtectedPartitionDuringMerge(device, partition_name)) {
610 auto message = "Cannot flash " + partition_name + " while a snapshot update is in progress";
611 return device->WriteFail(message);
612 }
613
David Andersonad970fc2019-08-27 14:01:16 -0700614 if (LogicalPartitionExists(device, partition_name)) {
615 CancelPartitionSnapshot(device, partition_name);
616 }
617
618 int ret = Flash(device, partition_name);
619 if (ret < 0) {
620 return device->WriteStatus(FastbootResult::FAIL, strerror(-ret));
621 }
Florian Mayer4c3c5262022-09-14 16:02:11 -0700622 if (partition_name == "userdata") {
623 PostWipeData();
624 }
625
David Andersonad970fc2019-08-27 14:01:16 -0700626 return device->WriteStatus(FastbootResult::OKAY, "Flashing succeeded");
627}
628
David Anderson38b3c7a2018-08-15 16:27:42 -0700629bool UpdateSuperHandler(FastbootDevice* device, const std::vector<std::string>& args) {
630 if (args.size() < 2) {
631 return device->WriteFail("Invalid arguments");
632 }
Hridya Valsarajudca328d2018-09-24 16:01:35 -0700633
634 if (GetDeviceLockStatus()) {
635 return device->WriteStatus(FastbootResult::FAIL, "Command not available on locked devices");
636 }
637
David Anderson38b3c7a2018-08-15 16:27:42 -0700638 bool wipe = (args.size() >= 3 && args[2] == "wipe");
639 return UpdateSuper(device, args[1], wipe);
640}
David Anderson1d504e32019-01-15 14:38:20 -0800641
David Anderson3d782d52019-01-29 13:09:49 -0800642bool GsiHandler(FastbootDevice* device, const std::vector<std::string>& args) {
David Anderson1d504e32019-01-15 14:38:20 -0800643 if (args.size() != 2) {
644 return device->WriteFail("Invalid arguments");
645 }
David Anderson3d782d52019-01-29 13:09:49 -0800646
647 AutoMountMetadata mount_metadata;
648 if (!mount_metadata) {
649 return device->WriteFail("Could not find GSI install");
650 }
651
652 if (!android::gsi::IsGsiInstalled()) {
653 return device->WriteStatus(FastbootResult::FAIL, "No GSI is installed");
654 }
655
David Anderson1d504e32019-01-15 14:38:20 -0800656 if (args[1] == "wipe") {
657 if (!android::gsi::UninstallGsi()) {
658 return device->WriteStatus(FastbootResult::FAIL, strerror(errno));
659 }
660 } else if (args[1] == "disable") {
661 if (!android::gsi::DisableGsi()) {
662 return device->WriteStatus(FastbootResult::FAIL, strerror(errno));
663 }
Chun-Wei Wang671a2a52023-08-30 07:55:43 +0000664 } else if (args[1] == "status") {
665 std::string active_dsu;
666 if (!android::gsi::IsGsiRunning()) {
667 device->WriteInfo("Not running");
668 } else if (!android::gsi::GetActiveDsu(&active_dsu)) {
669 return device->WriteFail(strerror(errno));
670 } else {
671 device->WriteInfo("Running active DSU: " + active_dsu);
672 }
673 } else {
674 return device->WriteFail("Invalid arguments");
David Anderson1d504e32019-01-15 14:38:20 -0800675 }
676 return device->WriteStatus(FastbootResult::OKAY, "Success");
677}
David Andersonab8f4662019-10-21 16:45:59 -0700678
679bool SnapshotUpdateHandler(FastbootDevice* device, const std::vector<std::string>& args) {
680 // Note that we use the HAL rather than mounting /metadata, since we want
681 // our results to match the bootloader.
David Anderson220ddb12019-10-31 18:02:41 -0700682 auto hal = device->boot1_1();
David Andersonab8f4662019-10-21 16:45:59 -0700683 if (!hal) return device->WriteFail("Not supported");
684
David Andersonab8f4662019-10-21 16:45:59 -0700685 // If no arguments, return the same thing as a getvar. Note that we get the
686 // HAL first so we can return "not supported" before we return the less
687 // specific error message below.
688 if (args.size() < 2 || args[1].empty()) {
689 std::string message;
690 if (!GetSnapshotUpdateStatus(device, {}, &message)) {
691 return device->WriteFail("Could not determine update status");
692 }
693 device->WriteInfo(message);
694 return device->WriteOkay("");
695 }
696
David Anderson220ddb12019-10-31 18:02:41 -0700697 MergeStatus status = hal->getSnapshotMergeStatus();
698
699 if (args.size() != 2) {
David Andersonab8f4662019-10-21 16:45:59 -0700700 return device->WriteFail("Invalid arguments");
701 }
David Anderson220ddb12019-10-31 18:02:41 -0700702 if (args[1] == "cancel") {
703 switch (status) {
704 case MergeStatus::SNAPSHOTTED:
Kelvin Zhang6befe782022-06-21 14:20:54 -0700705 case MergeStatus::MERGING: {
706 const auto ret = hal->SetSnapshotMergeStatus(MergeStatus::CANCELLED);
707 if (!ret.success) {
708 device->WriteFail("Failed to SetSnapshotMergeStatus(MergeStatus::CANCELLED) " +
709 ret.errMsg);
710 }
David Anderson220ddb12019-10-31 18:02:41 -0700711 break;
Kelvin Zhang6befe782022-06-21 14:20:54 -0700712 }
David Anderson220ddb12019-10-31 18:02:41 -0700713 default:
714 break;
715 }
716 } else if (args[1] == "merge") {
717 if (status != MergeStatus::MERGING) {
718 return device->WriteFail("No snapshot merge is in progress");
719 }
David Andersonab8f4662019-10-21 16:45:59 -0700720
David Anderson565577f2021-02-04 20:14:18 -0800721 auto sm = SnapshotManager::New();
David Anderson220ddb12019-10-31 18:02:41 -0700722 if (!sm) {
723 return device->WriteFail("Unable to create SnapshotManager");
724 }
David Anderson5a0177d2020-04-30 18:53:23 -0700725 if (!sm->FinishMergeInRecovery()) {
David Anderson220ddb12019-10-31 18:02:41 -0700726 return device->WriteFail("Unable to finish snapshot merge");
727 }
728 } else {
729 return device->WriteFail("Invalid parameter to snapshot-update");
David Andersonab8f4662019-10-21 16:45:59 -0700730 }
731 return device->WriteStatus(FastbootResult::OKAY, "Success");
732}
Yifan Honga4eb4752021-02-16 19:37:21 -0800733
734namespace {
735// Helper of FetchHandler.
736class PartitionFetcher {
737 public:
738 static bool Fetch(FastbootDevice* device, const std::vector<std::string>& args) {
739 if constexpr (!kEnableFetch) {
740 return device->WriteFail("Fetch is not allowed on user build");
741 }
742
743 if (GetDeviceLockStatus()) {
744 return device->WriteFail("Fetch is not allowed on locked devices");
745 }
746
747 PartitionFetcher fetcher(device, args);
748 if (fetcher.Open()) {
749 fetcher.Fetch();
750 }
751 CHECK(fetcher.ret_.has_value());
752 return *fetcher.ret_;
753 }
754
755 private:
756 PartitionFetcher(FastbootDevice* device, const std::vector<std::string>& args)
757 : device_(device), args_(&args) {}
758 // Return whether the partition is successfully opened.
759 // If successfully opened, ret_ is left untouched. Otherwise, ret_ is set to the value
760 // that FetchHandler should return.
761 bool Open() {
Yifan Hongbcd27702021-02-16 19:37:32 -0800762 if (args_->size() < 2) {
763 ret_ = device_->WriteFail("Missing partition arg");
Yifan Honga4eb4752021-02-16 19:37:21 -0800764 return false;
765 }
766
Yifan Hongbcd27702021-02-16 19:37:32 -0800767 partition_name_ = args_->at(1);
768 if (std::find(kAllowedPartitions.begin(), kAllowedPartitions.end(), partition_name_) ==
769 kAllowedPartitions.end()) {
770 ret_ = device_->WriteFail("Fetch is only allowed on [" +
771 android::base::Join(kAllowedPartitions, ", ") + "]");
772 return false;
773 }
774
Konstantin Vyshetsky81cc1192021-11-04 10:27:06 -0700775 if (!OpenPartition(device_, partition_name_, &handle_, O_RDONLY)) {
Yifan Honga4eb4752021-02-16 19:37:21 -0800776 ret_ = device_->WriteFail(
777 android::base::StringPrintf("Cannot open %s", partition_name_.c_str()));
778 return false;
779 }
780
781 partition_size_ = get_block_device_size(handle_.fd());
782 if (partition_size_ == 0) {
783 ret_ = device_->WriteOkay(android::base::StringPrintf("Partition %s has size 0",
784 partition_name_.c_str()));
785 return false;
786 }
787
788 start_offset_ = 0;
789 if (args_->size() >= 3) {
790 if (!android::base::ParseUint(args_->at(2), &start_offset_)) {
791 ret_ = device_->WriteFail("Invalid offset, must be integer");
792 return false;
793 }
794 if (start_offset_ > std::numeric_limits<off64_t>::max()) {
795 ret_ = device_->WriteFail(
796 android::base::StringPrintf("Offset overflows: %" PRIx64, start_offset_));
797 return false;
798 }
799 }
800 if (start_offset_ > partition_size_) {
801 ret_ = device_->WriteFail(android::base::StringPrintf(
802 "Invalid offset 0x%" PRIx64 ", partition %s has size 0x%" PRIx64, start_offset_,
803 partition_name_.c_str(), partition_size_));
804 return false;
805 }
806 uint64_t maximum_total_size_to_read = partition_size_ - start_offset_;
807 total_size_to_read_ = maximum_total_size_to_read;
808 if (args_->size() >= 4) {
809 if (!android::base::ParseUint(args_->at(3), &total_size_to_read_)) {
810 ret_ = device_->WriteStatus(FastbootResult::FAIL, "Invalid size, must be integer");
811 return false;
812 }
813 }
814 if (total_size_to_read_ == 0) {
815 ret_ = device_->WriteOkay("Read 0 bytes");
816 return false;
817 }
818 if (total_size_to_read_ > maximum_total_size_to_read) {
819 ret_ = device_->WriteFail(android::base::StringPrintf(
820 "Invalid size to read 0x%" PRIx64 ", partition %s has size 0x%" PRIx64
821 " and fetching from offset 0x%" PRIx64,
822 total_size_to_read_, partition_name_.c_str(), partition_size_, start_offset_));
823 return false;
824 }
825
826 if (total_size_to_read_ > kMaxFetchSizeDefault) {
827 ret_ = device_->WriteFail(android::base::StringPrintf(
828 "Cannot fetch 0x%" PRIx64
829 " bytes because it exceeds maximum transport size 0x%x",
830 partition_size_, kMaxDownloadSizeDefault));
831 return false;
832 }
833
834 return true;
835 }
836
837 // Assume Open() returns true.
838 // After execution, ret_ is set to the value that FetchHandler should return.
839 void Fetch() {
840 CHECK(start_offset_ <= std::numeric_limits<off64_t>::max());
841 if (lseek64(handle_.fd(), start_offset_, SEEK_SET) != static_cast<off64_t>(start_offset_)) {
842 ret_ = device_->WriteFail(android::base::StringPrintf(
843 "On partition %s, unable to lseek(0x%" PRIx64 ": %s", partition_name_.c_str(),
844 start_offset_, strerror(errno)));
845 return;
846 }
847
848 if (!device_->WriteStatus(FastbootResult::DATA,
849 android::base::StringPrintf(
850 "%08x", static_cast<uint32_t>(total_size_to_read_)))) {
851 ret_ = false;
852 return;
853 }
854 uint64_t end_offset = start_offset_ + total_size_to_read_;
855 std::vector<char> buf(1_MiB);
856 uint64_t current_offset = start_offset_;
857 while (current_offset < end_offset) {
858 // On any error, exit. We can't return a status message to the driver because
859 // we are in the middle of writing data, so just let the driver guess what's wrong
860 // by ending the data stream prematurely.
861 uint64_t remaining = end_offset - current_offset;
862 uint64_t chunk_size = std::min<uint64_t>(buf.size(), remaining);
863 if (!android::base::ReadFully(handle_.fd(), buf.data(), chunk_size)) {
864 PLOG(ERROR) << std::hex << "Unable to read 0x" << chunk_size << " bytes from "
865 << partition_name_ << " @ offset 0x" << current_offset;
866 ret_ = false;
867 return;
868 }
869 if (!device_->HandleData(false /* is read */, buf.data(), chunk_size)) {
870 PLOG(ERROR) << std::hex << "Unable to send 0x" << chunk_size << " bytes of "
871 << partition_name_ << " @ offset 0x" << current_offset;
872 ret_ = false;
873 return;
874 }
875 current_offset += chunk_size;
876 }
877
878 ret_ = device_->WriteOkay(android::base::StringPrintf(
879 "Fetched %s (offset=0x%" PRIx64 ", size=0x%" PRIx64, partition_name_.c_str(),
880 start_offset_, total_size_to_read_));
881 }
882
Yifan Hongbcd27702021-02-16 19:37:32 -0800883 static constexpr std::array<const char*, 3> kAllowedPartitions{
884 "vendor_boot",
885 "vendor_boot_a",
886 "vendor_boot_b",
887 };
888
Yifan Honga4eb4752021-02-16 19:37:21 -0800889 FastbootDevice* device_;
890 const std::vector<std::string>* args_ = nullptr;
891 std::string partition_name_;
892 PartitionHandle handle_;
893 uint64_t partition_size_ = 0;
894 uint64_t start_offset_ = 0;
895 uint64_t total_size_to_read_ = 0;
896
897 // What FetchHandler should return.
898 std::optional<bool> ret_ = std::nullopt;
899};
900} // namespace
901
902bool FetchHandler(FastbootDevice* device, const std::vector<std::string>& args) {
903 return PartitionFetcher::Fetch(device, args);
904}