• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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 
19 #include <inttypes.h>
20 #include <sys/socket.h>
21 #include <sys/un.h>
22 
23 #include <unordered_set>
24 
25 #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>
31 #include <android/hardware/boot/1.1/IBootControl.h>
32 #include <cutils/android_reboot.h>
33 #include <ext4_utils/wipe.h>
34 #include <fs_mgr.h>
35 #include <fs_mgr/roots.h>
36 #include <libgsi/libgsi.h>
37 #include <liblp/builder.h>
38 #include <liblp/liblp.h>
39 #include <libsnapshot/snapshot.h>
40 #include <storage_literals/storage_literals.h>
41 #include <uuid/uuid.h>
42 
43 #include "constants.h"
44 #include "fastboot_device.h"
45 #include "flashing.h"
46 #include "utility.h"
47 
48 #ifdef FB_ENABLE_FETCH
49 static constexpr bool kEnableFetch = true;
50 #else
51 static constexpr bool kEnableFetch = false;
52 #endif
53 
54 using android::fs_mgr::MetadataBuilder;
55 using ::android::hardware::hidl_string;
56 using ::android::hardware::boot::V1_0::BoolResult;
57 using ::android::hardware::boot::V1_0::CommandResult;
58 using ::android::hardware::boot::V1_0::Slot;
59 using ::android::hardware::boot::V1_1::MergeStatus;
60 using ::android::hardware::fastboot::V1_0::Result;
61 using ::android::hardware::fastboot::V1_0::Status;
62 using android::snapshot::SnapshotManager;
63 using IBootControl1_1 = ::android::hardware::boot::V1_1::IBootControl;
64 
65 using namespace android::storage_literals;
66 
67 struct 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 
IsSnapshotUpdateInProgress(FastbootDevice * device)74 static 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 
IsProtectedPartitionDuringMerge(FastbootDevice * device,const std::string & name)83 static 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 
GetAllVars(FastbootDevice * device,const std::string & name,const VariableHandlers & handlers)92 static 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 
GetVarHandler(FastbootDevice * device,const std::vector<std::string> & args)115 bool GetVarHandler(FastbootDevice* device, const std::vector<std::string>& args) {
116     const std::unordered_map<std::string, VariableHandlers> kVariableMap = {
117             {FB_VAR_VERSION, {GetVersion, nullptr}},
118             {FB_VAR_VERSION_BOOTLOADER, {GetBootloaderVersion, nullptr}},
119             {FB_VAR_VERSION_BASEBAND, {GetBasebandVersion, nullptr}},
120             {FB_VAR_VERSION_OS, {GetOsVersion, nullptr}},
121             {FB_VAR_VERSION_VNDK, {GetVndkVersion, nullptr}},
122             {FB_VAR_PRODUCT, {GetProduct, nullptr}},
123             {FB_VAR_SERIALNO, {GetSerial, nullptr}},
124             {FB_VAR_VARIANT, {GetVariant, nullptr}},
125             {FB_VAR_SECURE, {GetSecure, nullptr}},
126             {FB_VAR_UNLOCKED, {GetUnlocked, nullptr}},
127             {FB_VAR_MAX_DOWNLOAD_SIZE, {GetMaxDownloadSize, nullptr}},
128             {FB_VAR_CURRENT_SLOT, {::GetCurrentSlot, nullptr}},
129             {FB_VAR_SLOT_COUNT, {GetSlotCount, nullptr}},
130             {FB_VAR_HAS_SLOT, {GetHasSlot, GetAllPartitionArgsNoSlot}},
131             {FB_VAR_SLOT_SUCCESSFUL, {GetSlotSuccessful, nullptr}},
132             {FB_VAR_SLOT_UNBOOTABLE, {GetSlotUnbootable, nullptr}},
133             {FB_VAR_PARTITION_SIZE, {GetPartitionSize, GetAllPartitionArgsWithSlot}},
134             {FB_VAR_PARTITION_TYPE, {GetPartitionType, GetAllPartitionArgsWithSlot}},
135             {FB_VAR_IS_LOGICAL, {GetPartitionIsLogical, GetAllPartitionArgsWithSlot}},
136             {FB_VAR_IS_USERSPACE, {GetIsUserspace, nullptr}},
137             {FB_VAR_OFF_MODE_CHARGE_STATE, {GetOffModeChargeState, nullptr}},
138             {FB_VAR_BATTERY_VOLTAGE, {GetBatteryVoltage, nullptr}},
139             {FB_VAR_BATTERY_SOC_OK, {GetBatterySoCOk, nullptr}},
140             {FB_VAR_HW_REVISION, {GetHardwareRevision, nullptr}},
141             {FB_VAR_SUPER_PARTITION_NAME, {GetSuperPartitionName, nullptr}},
142             {FB_VAR_SNAPSHOT_UPDATE_STATUS, {GetSnapshotUpdateStatus, nullptr}},
143             {FB_VAR_CPU_ABI, {GetCpuAbi, nullptr}},
144             {FB_VAR_SYSTEM_FINGERPRINT, {GetSystemFingerprint, nullptr}},
145             {FB_VAR_VENDOR_FINGERPRINT, {GetVendorFingerprint, nullptr}},
146             {FB_VAR_DYNAMIC_PARTITION, {GetDynamicPartition, nullptr}},
147             {FB_VAR_FIRST_API_LEVEL, {GetFirstApiLevel, nullptr}},
148             {FB_VAR_SECURITY_PATCH_LEVEL, {GetSecurityPatchLevel, nullptr}},
149             {FB_VAR_TREBLE_ENABLED, {GetTrebleEnabled, nullptr}},
150             {FB_VAR_MAX_FETCH_SIZE, {GetMaxFetchSize, nullptr}},
151     };
152 
153     if (args.size() < 2) {
154         return device->WriteFail("Missing argument");
155     }
156 
157     // Special case: return all variables that we can.
158     if (args[1] == "all") {
159         for (const auto& [name, handlers] : kVariableMap) {
160             GetAllVars(device, name, handlers);
161         }
162         return device->WriteOkay("");
163     }
164 
165     // args[0] is command name, args[1] is variable.
166     auto found_variable = kVariableMap.find(args[1]);
167     if (found_variable == kVariableMap.end()) {
168         return device->WriteFail("Unknown variable");
169     }
170 
171     std::string message;
172     std::vector<std::string> getvar_args(args.begin() + 2, args.end());
173     if (!found_variable->second.get(device, getvar_args, &message)) {
174         return device->WriteFail(message);
175     }
176     return device->WriteOkay(message);
177 }
178 
OemPostWipeData(FastbootDevice * device)179 bool OemPostWipeData(FastbootDevice* device) {
180     auto fastboot_hal = device->fastboot_hal();
181     if (!fastboot_hal) {
182         return false;
183     }
184 
185     Result ret;
186     auto ret_val = fastboot_hal->doOemSpecificErase([&](Result result) { ret = result; });
187     if (!ret_val.isOk()) {
188         return false;
189     }
190     if (ret.status == Status::NOT_SUPPORTED) {
191         return false;
192     } else if (ret.status != Status::SUCCESS) {
193         device->WriteStatus(FastbootResult::FAIL, ret.message);
194     } else {
195         device->WriteStatus(FastbootResult::OKAY, "Erasing succeeded");
196     }
197 
198     return true;
199 }
200 
EraseHandler(FastbootDevice * device,const std::vector<std::string> & args)201 bool EraseHandler(FastbootDevice* device, const std::vector<std::string>& args) {
202     if (args.size() < 2) {
203         return device->WriteStatus(FastbootResult::FAIL, "Invalid arguments");
204     }
205 
206     if (GetDeviceLockStatus()) {
207         return device->WriteStatus(FastbootResult::FAIL, "Erase is not allowed on locked devices");
208     }
209 
210     const auto& partition_name = args[1];
211     if (IsProtectedPartitionDuringMerge(device, partition_name)) {
212         auto message = "Cannot erase " + partition_name + " while a snapshot update is in progress";
213         return device->WriteFail(message);
214     }
215 
216     PartitionHandle handle;
217     if (!OpenPartition(device, partition_name, &handle)) {
218         return device->WriteStatus(FastbootResult::FAIL, "Partition doesn't exist");
219     }
220     if (wipe_block_device(handle.fd(), get_block_device_size(handle.fd())) == 0) {
221         //Perform oem PostWipeData if Android userdata partition has been erased
222         bool support_oem_postwipedata = false;
223         if (partition_name == "userdata") {
224             support_oem_postwipedata = OemPostWipeData(device);
225         }
226 
227         if (!support_oem_postwipedata) {
228             return device->WriteStatus(FastbootResult::OKAY, "Erasing succeeded");
229         } else {
230             //Write device status in OemPostWipeData(), so just return true
231             return true;
232         }
233     }
234     return device->WriteStatus(FastbootResult::FAIL, "Erasing failed");
235 }
236 
OemCmdHandler(FastbootDevice * device,const std::vector<std::string> & args)237 bool OemCmdHandler(FastbootDevice* device, const std::vector<std::string>& args) {
238     auto fastboot_hal = device->fastboot_hal();
239     if (!fastboot_hal) {
240         return device->WriteStatus(FastbootResult::FAIL, "Unable to open fastboot HAL");
241     }
242 
243     //Disable "oem postwipedata userdata" to prevent user wipe oem userdata only.
244     if (args[0] == "oem postwipedata userdata") {
245         return device->WriteStatus(FastbootResult::FAIL, "Unable to do oem postwipedata userdata");
246     }
247 
248     Result ret;
249     auto ret_val = fastboot_hal->doOemCommand(args[0], [&](Result result) { ret = result; });
250     if (!ret_val.isOk()) {
251         return device->WriteStatus(FastbootResult::FAIL, "Unable to do OEM command");
252     }
253     if (ret.status != Status::SUCCESS) {
254         return device->WriteStatus(FastbootResult::FAIL, ret.message);
255     }
256 
257     return device->WriteStatus(FastbootResult::OKAY, ret.message);
258 }
259 
DownloadHandler(FastbootDevice * device,const std::vector<std::string> & args)260 bool DownloadHandler(FastbootDevice* device, const std::vector<std::string>& args) {
261     if (args.size() < 2) {
262         return device->WriteStatus(FastbootResult::FAIL, "size argument unspecified");
263     }
264 
265     if (GetDeviceLockStatus()) {
266         return device->WriteStatus(FastbootResult::FAIL,
267                                    "Download is not allowed on locked devices");
268     }
269 
270     // arg[0] is the command name, arg[1] contains size of data to be downloaded
271     // which should always be 8 bytes
272     if (args[1].length() != 8) {
273         return device->WriteStatus(FastbootResult::FAIL,
274                                    "Invalid size (length of size != 8)");
275     }
276     unsigned int size;
277     if (!android::base::ParseUint("0x" + args[1], &size, kMaxDownloadSizeDefault)) {
278         return device->WriteStatus(FastbootResult::FAIL, "Invalid size");
279     }
280     if (size == 0) {
281         return device->WriteStatus(FastbootResult::FAIL, "Invalid size (0)");
282     }
283     device->download_data().resize(size);
284     if (!device->WriteStatus(FastbootResult::DATA, android::base::StringPrintf("%08x", size))) {
285         return false;
286     }
287 
288     if (device->HandleData(true, &device->download_data())) {
289         return device->WriteStatus(FastbootResult::OKAY, "");
290     }
291 
292     PLOG(ERROR) << "Couldn't download data";
293     return device->WriteStatus(FastbootResult::FAIL, "Couldn't download data");
294 }
295 
SetActiveHandler(FastbootDevice * device,const std::vector<std::string> & args)296 bool SetActiveHandler(FastbootDevice* device, const std::vector<std::string>& args) {
297     if (args.size() < 2) {
298         return device->WriteStatus(FastbootResult::FAIL, "Missing slot argument");
299     }
300 
301     if (GetDeviceLockStatus()) {
302         return device->WriteStatus(FastbootResult::FAIL,
303                                    "set_active command is not allowed on locked devices");
304     }
305 
306     Slot slot;
307     if (!GetSlotNumber(args[1], &slot)) {
308         // Slot suffix needs to be between 'a' and 'z'.
309         return device->WriteStatus(FastbootResult::FAIL, "Bad slot suffix");
310     }
311 
312     // Non-A/B devices will not have a boot control HAL.
313     auto boot_control_hal = device->boot_control_hal();
314     if (!boot_control_hal) {
315         return device->WriteStatus(FastbootResult::FAIL,
316                                    "Cannot set slot: boot control HAL absent");
317     }
318     if (slot >= boot_control_hal->getNumberSlots()) {
319         return device->WriteStatus(FastbootResult::FAIL, "Slot out of range");
320     }
321 
322     // If the slot is not changing, do nothing.
323     if (args[1] == device->GetCurrentSlot()) {
324         return device->WriteOkay("");
325     }
326 
327     // Check how to handle the current snapshot state.
328     if (auto hal11 = device->boot1_1()) {
329         auto merge_status = hal11->getSnapshotMergeStatus();
330         if (merge_status == MergeStatus::MERGING) {
331             return device->WriteFail("Cannot change slots while a snapshot update is in progress");
332         }
333         // Note: we allow the slot change if the state is SNAPSHOTTED. First-
334         // stage init does not have access to the HAL, and uses the slot number
335         // and /metadata OTA state to determine whether a slot change occurred.
336         // Booting into the old slot would erase the OTA, and switching A->B->A
337         // would simply resume it if no boots occur in between. Re-flashing
338         // partitions implicitly cancels the OTA, so leaving the state as-is is
339         // safe.
340         if (merge_status == MergeStatus::SNAPSHOTTED) {
341             device->WriteInfo(
342                     "Changing the active slot with a snapshot applied may cancel the"
343                     " update.");
344         }
345     }
346 
347     CommandResult ret;
348     auto cb = [&ret](CommandResult result) { ret = result; };
349     auto result = boot_control_hal->setActiveBootSlot(slot, cb);
350     if (result.isOk() && ret.success) {
351         // Save as slot suffix to match the suffix format as returned from
352         // the boot control HAL.
353         auto current_slot = "_" + args[1];
354         device->set_active_slot(current_slot);
355         return device->WriteStatus(FastbootResult::OKAY, "");
356     }
357     return device->WriteStatus(FastbootResult::FAIL, "Unable to set slot");
358 }
359 
ShutDownHandler(FastbootDevice * device,const std::vector<std::string> &)360 bool ShutDownHandler(FastbootDevice* device, const std::vector<std::string>& /* args */) {
361     auto result = device->WriteStatus(FastbootResult::OKAY, "Shutting down");
362     android::base::SetProperty(ANDROID_RB_PROPERTY, "shutdown,fastboot");
363     device->CloseDevice();
364     TEMP_FAILURE_RETRY(pause());
365     return result;
366 }
367 
RebootHandler(FastbootDevice * device,const std::vector<std::string> &)368 bool RebootHandler(FastbootDevice* device, const std::vector<std::string>& /* args */) {
369     auto result = device->WriteStatus(FastbootResult::OKAY, "Rebooting");
370     android::base::SetProperty(ANDROID_RB_PROPERTY, "reboot,from_fastboot");
371     device->CloseDevice();
372     TEMP_FAILURE_RETRY(pause());
373     return result;
374 }
375 
RebootBootloaderHandler(FastbootDevice * device,const std::vector<std::string> &)376 bool RebootBootloaderHandler(FastbootDevice* device, const std::vector<std::string>& /* args */) {
377     auto result = device->WriteStatus(FastbootResult::OKAY, "Rebooting bootloader");
378     android::base::SetProperty(ANDROID_RB_PROPERTY, "reboot,bootloader");
379     device->CloseDevice();
380     TEMP_FAILURE_RETRY(pause());
381     return result;
382 }
383 
RebootFastbootHandler(FastbootDevice * device,const std::vector<std::string> &)384 bool RebootFastbootHandler(FastbootDevice* device, const std::vector<std::string>& /* args */) {
385     auto result = device->WriteStatus(FastbootResult::OKAY, "Rebooting fastboot");
386     android::base::SetProperty(ANDROID_RB_PROPERTY, "reboot,fastboot");
387     device->CloseDevice();
388     TEMP_FAILURE_RETRY(pause());
389     return result;
390 }
391 
EnterRecovery()392 static bool EnterRecovery() {
393     const char msg_switch_to_recovery = 'r';
394 
395     android::base::unique_fd sock(socket(AF_UNIX, SOCK_STREAM, 0));
396     if (sock < 0) {
397         PLOG(ERROR) << "Couldn't create sock";
398         return false;
399     }
400 
401     struct sockaddr_un addr = {.sun_family = AF_UNIX};
402     strncpy(addr.sun_path, "/dev/socket/recovery", sizeof(addr.sun_path) - 1);
403     if (connect(sock.get(), (struct sockaddr*)&addr, sizeof(addr)) < 0) {
404         PLOG(ERROR) << "Couldn't connect to recovery";
405         return false;
406     }
407     // Switch to recovery will not update the boot reason since it does not
408     // require a reboot.
409     auto ret = write(sock.get(), &msg_switch_to_recovery, sizeof(msg_switch_to_recovery));
410     if (ret != sizeof(msg_switch_to_recovery)) {
411         PLOG(ERROR) << "Couldn't write message to switch to recovery";
412         return false;
413     }
414 
415     return true;
416 }
417 
RebootRecoveryHandler(FastbootDevice * device,const std::vector<std::string> &)418 bool RebootRecoveryHandler(FastbootDevice* device, const std::vector<std::string>& /* args */) {
419     auto status = true;
420     if (EnterRecovery()) {
421         status = device->WriteStatus(FastbootResult::OKAY, "Rebooting to recovery");
422     } else {
423         status = device->WriteStatus(FastbootResult::FAIL, "Unable to reboot to recovery");
424     }
425     device->CloseDevice();
426     TEMP_FAILURE_RETRY(pause());
427     return status;
428 }
429 
430 // Helper class for opening a handle to a MetadataBuilder and writing the new
431 // partition table to the same place it was read.
432 class PartitionBuilder {
433   public:
434     explicit PartitionBuilder(FastbootDevice* device, const std::string& partition_name);
435 
436     bool Write();
Valid() const437     bool Valid() const { return !!builder_; }
operator ->() const438     MetadataBuilder* operator->() const { return builder_.get(); }
439 
440   private:
441     FastbootDevice* device_;
442     std::string super_device_;
443     uint32_t slot_number_;
444     std::unique_ptr<MetadataBuilder> builder_;
445 };
446 
PartitionBuilder(FastbootDevice * device,const std::string & partition_name)447 PartitionBuilder::PartitionBuilder(FastbootDevice* device, const std::string& partition_name)
448     : device_(device) {
449     std::string slot_suffix = GetSuperSlotSuffix(device, partition_name);
450     slot_number_ = android::fs_mgr::SlotNumberForSlotSuffix(slot_suffix);
451     auto super_device = FindPhysicalPartition(fs_mgr_get_super_partition_name(slot_number_));
452     if (!super_device) {
453         return;
454     }
455     super_device_ = *super_device;
456     builder_ = MetadataBuilder::New(super_device_, slot_number_);
457 }
458 
Write()459 bool PartitionBuilder::Write() {
460     auto metadata = builder_->Export();
461     if (!metadata) {
462         return false;
463     }
464     return UpdateAllPartitionMetadata(device_, super_device_, *metadata.get());
465 }
466 
CreatePartitionHandler(FastbootDevice * device,const std::vector<std::string> & args)467 bool CreatePartitionHandler(FastbootDevice* device, const std::vector<std::string>& args) {
468     if (args.size() < 3) {
469         return device->WriteFail("Invalid partition name and size");
470     }
471 
472     if (GetDeviceLockStatus()) {
473         return device->WriteStatus(FastbootResult::FAIL, "Command not available on locked devices");
474     }
475 
476     uint64_t partition_size;
477     std::string partition_name = args[1];
478     if (!android::base::ParseUint(args[2].c_str(), &partition_size)) {
479         return device->WriteFail("Invalid partition size");
480     }
481 
482     PartitionBuilder builder(device, partition_name);
483     if (!builder.Valid()) {
484         return device->WriteFail("Could not open super partition");
485     }
486     // TODO(112433293) Disallow if the name is in the physical table as well.
487     if (builder->FindPartition(partition_name)) {
488         return device->WriteFail("Partition already exists");
489     }
490 
491     auto partition = builder->AddPartition(partition_name, 0);
492     if (!partition) {
493         return device->WriteFail("Failed to add partition");
494     }
495     if (!builder->ResizePartition(partition, partition_size)) {
496         builder->RemovePartition(partition_name);
497         return device->WriteFail("Not enough space for partition");
498     }
499     if (!builder.Write()) {
500         return device->WriteFail("Failed to write partition table");
501     }
502     return device->WriteOkay("Partition created");
503 }
504 
DeletePartitionHandler(FastbootDevice * device,const std::vector<std::string> & args)505 bool DeletePartitionHandler(FastbootDevice* device, const std::vector<std::string>& args) {
506     if (args.size() < 2) {
507         return device->WriteFail("Invalid partition name and size");
508     }
509 
510     if (GetDeviceLockStatus()) {
511         return device->WriteStatus(FastbootResult::FAIL, "Command not available on locked devices");
512     }
513 
514     std::string partition_name = args[1];
515 
516     PartitionBuilder builder(device, partition_name);
517     if (!builder.Valid()) {
518         return device->WriteFail("Could not open super partition");
519     }
520     builder->RemovePartition(partition_name);
521     if (!builder.Write()) {
522         return device->WriteFail("Failed to write partition table");
523     }
524     return device->WriteOkay("Partition deleted");
525 }
526 
ResizePartitionHandler(FastbootDevice * device,const std::vector<std::string> & args)527 bool ResizePartitionHandler(FastbootDevice* device, const std::vector<std::string>& args) {
528     if (args.size() < 3) {
529         return device->WriteFail("Invalid partition name and size");
530     }
531 
532     if (GetDeviceLockStatus()) {
533         return device->WriteStatus(FastbootResult::FAIL, "Command not available on locked devices");
534     }
535 
536     uint64_t partition_size;
537     std::string partition_name = args[1];
538     if (!android::base::ParseUint(args[2].c_str(), &partition_size)) {
539         return device->WriteFail("Invalid partition size");
540     }
541 
542     PartitionBuilder builder(device, partition_name);
543     if (!builder.Valid()) {
544         return device->WriteFail("Could not open super partition");
545     }
546 
547     auto partition = builder->FindPartition(partition_name);
548     if (!partition) {
549         return device->WriteFail("Partition does not exist");
550     }
551 
552     // Remove the updated flag to cancel any snapshots.
553     uint32_t attrs = partition->attributes();
554     partition->set_attributes(attrs & ~LP_PARTITION_ATTR_UPDATED);
555 
556     if (!builder->ResizePartition(partition, partition_size)) {
557         return device->WriteFail("Not enough space to resize partition");
558     }
559     if (!builder.Write()) {
560         return device->WriteFail("Failed to write partition table");
561     }
562     return device->WriteOkay("Partition resized");
563 }
564 
CancelPartitionSnapshot(FastbootDevice * device,const std::string & partition_name)565 void CancelPartitionSnapshot(FastbootDevice* device, const std::string& partition_name) {
566     PartitionBuilder builder(device, partition_name);
567     if (!builder.Valid()) return;
568 
569     auto partition = builder->FindPartition(partition_name);
570     if (!partition) return;
571 
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 
576     builder.Write();
577 }
578 
FlashHandler(FastbootDevice * device,const std::vector<std::string> & args)579 bool FlashHandler(FastbootDevice* device, const std::vector<std::string>& args) {
580     if (args.size() < 2) {
581         return device->WriteStatus(FastbootResult::FAIL, "Invalid arguments");
582     }
583 
584     if (GetDeviceLockStatus()) {
585         return device->WriteStatus(FastbootResult::FAIL,
586                                    "Flashing is not allowed on locked devices");
587     }
588 
589     const auto& partition_name = args[1];
590     if (IsProtectedPartitionDuringMerge(device, partition_name)) {
591         auto message = "Cannot flash " + partition_name + " while a snapshot update is in progress";
592         return device->WriteFail(message);
593     }
594 
595     if (LogicalPartitionExists(device, partition_name)) {
596         CancelPartitionSnapshot(device, partition_name);
597     }
598 
599     int ret = Flash(device, partition_name);
600     if (ret < 0) {
601         return device->WriteStatus(FastbootResult::FAIL, strerror(-ret));
602     }
603     return device->WriteStatus(FastbootResult::OKAY, "Flashing succeeded");
604 }
605 
UpdateSuperHandler(FastbootDevice * device,const std::vector<std::string> & args)606 bool UpdateSuperHandler(FastbootDevice* device, const std::vector<std::string>& args) {
607     if (args.size() < 2) {
608         return device->WriteFail("Invalid arguments");
609     }
610 
611     if (GetDeviceLockStatus()) {
612         return device->WriteStatus(FastbootResult::FAIL, "Command not available on locked devices");
613     }
614 
615     bool wipe = (args.size() >= 3 && args[2] == "wipe");
616     return UpdateSuper(device, args[1], wipe);
617 }
618 
GsiHandler(FastbootDevice * device,const std::vector<std::string> & args)619 bool GsiHandler(FastbootDevice* device, const std::vector<std::string>& args) {
620     if (args.size() != 2) {
621         return device->WriteFail("Invalid arguments");
622     }
623 
624     AutoMountMetadata mount_metadata;
625     if (!mount_metadata) {
626         return device->WriteFail("Could not find GSI install");
627     }
628 
629     if (!android::gsi::IsGsiInstalled()) {
630         return device->WriteStatus(FastbootResult::FAIL, "No GSI is installed");
631     }
632 
633     if (args[1] == "wipe") {
634         if (!android::gsi::UninstallGsi()) {
635             return device->WriteStatus(FastbootResult::FAIL, strerror(errno));
636         }
637     } else if (args[1] == "disable") {
638         if (!android::gsi::DisableGsi()) {
639             return device->WriteStatus(FastbootResult::FAIL, strerror(errno));
640         }
641     }
642     return device->WriteStatus(FastbootResult::OKAY, "Success");
643 }
644 
SnapshotUpdateHandler(FastbootDevice * device,const std::vector<std::string> & args)645 bool SnapshotUpdateHandler(FastbootDevice* device, const std::vector<std::string>& args) {
646     // Note that we use the HAL rather than mounting /metadata, since we want
647     // our results to match the bootloader.
648     auto hal = device->boot1_1();
649     if (!hal) return device->WriteFail("Not supported");
650 
651     // If no arguments, return the same thing as a getvar. Note that we get the
652     // HAL first so we can return "not supported" before we return the less
653     // specific error message below.
654     if (args.size() < 2 || args[1].empty()) {
655         std::string message;
656         if (!GetSnapshotUpdateStatus(device, {}, &message)) {
657             return device->WriteFail("Could not determine update status");
658         }
659         device->WriteInfo(message);
660         return device->WriteOkay("");
661     }
662 
663     MergeStatus status = hal->getSnapshotMergeStatus();
664 
665     if (args.size() != 2) {
666         return device->WriteFail("Invalid arguments");
667     }
668     if (args[1] == "cancel") {
669         switch (status) {
670             case MergeStatus::SNAPSHOTTED:
671             case MergeStatus::MERGING:
672                 hal->setSnapshotMergeStatus(MergeStatus::CANCELLED);
673                 break;
674             default:
675                 break;
676         }
677     } else if (args[1] == "merge") {
678         if (status != MergeStatus::MERGING) {
679             return device->WriteFail("No snapshot merge is in progress");
680         }
681 
682         auto sm = SnapshotManager::New();
683         if (!sm) {
684             return device->WriteFail("Unable to create SnapshotManager");
685         }
686         if (!sm->FinishMergeInRecovery()) {
687             return device->WriteFail("Unable to finish snapshot merge");
688         }
689     } else {
690         return device->WriteFail("Invalid parameter to snapshot-update");
691     }
692     return device->WriteStatus(FastbootResult::OKAY, "Success");
693 }
694 
695 namespace {
696 // Helper of FetchHandler.
697 class PartitionFetcher {
698   public:
Fetch(FastbootDevice * device,const std::vector<std::string> & args)699     static bool Fetch(FastbootDevice* device, const std::vector<std::string>& args) {
700         if constexpr (!kEnableFetch) {
701             return device->WriteFail("Fetch is not allowed on user build");
702         }
703 
704         if (GetDeviceLockStatus()) {
705             return device->WriteFail("Fetch is not allowed on locked devices");
706         }
707 
708         PartitionFetcher fetcher(device, args);
709         if (fetcher.Open()) {
710             fetcher.Fetch();
711         }
712         CHECK(fetcher.ret_.has_value());
713         return *fetcher.ret_;
714     }
715 
716   private:
PartitionFetcher(FastbootDevice * device,const std::vector<std::string> & args)717     PartitionFetcher(FastbootDevice* device, const std::vector<std::string>& args)
718         : device_(device), args_(&args) {}
719     // Return whether the partition is successfully opened.
720     // If successfully opened, ret_ is left untouched. Otherwise, ret_ is set to the value
721     // that FetchHandler should return.
Open()722     bool Open() {
723         if (args_->size() < 2) {
724             ret_ = device_->WriteFail("Missing partition arg");
725             return false;
726         }
727 
728         partition_name_ = args_->at(1);
729         if (std::find(kAllowedPartitions.begin(), kAllowedPartitions.end(), partition_name_) ==
730             kAllowedPartitions.end()) {
731             ret_ = device_->WriteFail("Fetch is only allowed on [" +
732                                       android::base::Join(kAllowedPartitions, ", ") + "]");
733             return false;
734         }
735 
736         if (!OpenPartition(device_, partition_name_, &handle_, O_RDONLY)) {
737             ret_ = device_->WriteFail(
738                     android::base::StringPrintf("Cannot open %s", partition_name_.c_str()));
739             return false;
740         }
741 
742         partition_size_ = get_block_device_size(handle_.fd());
743         if (partition_size_ == 0) {
744             ret_ = device_->WriteOkay(android::base::StringPrintf("Partition %s has size 0",
745                                                                   partition_name_.c_str()));
746             return false;
747         }
748 
749         start_offset_ = 0;
750         if (args_->size() >= 3) {
751             if (!android::base::ParseUint(args_->at(2), &start_offset_)) {
752                 ret_ = device_->WriteFail("Invalid offset, must be integer");
753                 return false;
754             }
755             if (start_offset_ > std::numeric_limits<off64_t>::max()) {
756                 ret_ = device_->WriteFail(
757                         android::base::StringPrintf("Offset overflows: %" PRIx64, start_offset_));
758                 return false;
759             }
760         }
761         if (start_offset_ > partition_size_) {
762             ret_ = device_->WriteFail(android::base::StringPrintf(
763                     "Invalid offset 0x%" PRIx64 ", partition %s has size 0x%" PRIx64, start_offset_,
764                     partition_name_.c_str(), partition_size_));
765             return false;
766         }
767         uint64_t maximum_total_size_to_read = partition_size_ - start_offset_;
768         total_size_to_read_ = maximum_total_size_to_read;
769         if (args_->size() >= 4) {
770             if (!android::base::ParseUint(args_->at(3), &total_size_to_read_)) {
771                 ret_ = device_->WriteStatus(FastbootResult::FAIL, "Invalid size, must be integer");
772                 return false;
773             }
774         }
775         if (total_size_to_read_ == 0) {
776             ret_ = device_->WriteOkay("Read 0 bytes");
777             return false;
778         }
779         if (total_size_to_read_ > maximum_total_size_to_read) {
780             ret_ = device_->WriteFail(android::base::StringPrintf(
781                     "Invalid size to read 0x%" PRIx64 ", partition %s has size 0x%" PRIx64
782                     " and fetching from offset 0x%" PRIx64,
783                     total_size_to_read_, partition_name_.c_str(), partition_size_, start_offset_));
784             return false;
785         }
786 
787         if (total_size_to_read_ > kMaxFetchSizeDefault) {
788             ret_ = device_->WriteFail(android::base::StringPrintf(
789                     "Cannot fetch 0x%" PRIx64
790                     " bytes because it exceeds maximum transport size 0x%x",
791                     partition_size_, kMaxDownloadSizeDefault));
792             return false;
793         }
794 
795         return true;
796     }
797 
798     // Assume Open() returns true.
799     // After execution, ret_ is set to the value that FetchHandler should return.
Fetch()800     void Fetch() {
801         CHECK(start_offset_ <= std::numeric_limits<off64_t>::max());
802         if (lseek64(handle_.fd(), start_offset_, SEEK_SET) != static_cast<off64_t>(start_offset_)) {
803             ret_ = device_->WriteFail(android::base::StringPrintf(
804                     "On partition %s, unable to lseek(0x%" PRIx64 ": %s", partition_name_.c_str(),
805                     start_offset_, strerror(errno)));
806             return;
807         }
808 
809         if (!device_->WriteStatus(FastbootResult::DATA,
810                                   android::base::StringPrintf(
811                                           "%08x", static_cast<uint32_t>(total_size_to_read_)))) {
812             ret_ = false;
813             return;
814         }
815         uint64_t end_offset = start_offset_ + total_size_to_read_;
816         std::vector<char> buf(1_MiB);
817         uint64_t current_offset = start_offset_;
818         while (current_offset < end_offset) {
819             // On any error, exit. We can't return a status message to the driver because
820             // we are in the middle of writing data, so just let the driver guess what's wrong
821             // by ending the data stream prematurely.
822             uint64_t remaining = end_offset - current_offset;
823             uint64_t chunk_size = std::min<uint64_t>(buf.size(), remaining);
824             if (!android::base::ReadFully(handle_.fd(), buf.data(), chunk_size)) {
825                 PLOG(ERROR) << std::hex << "Unable to read 0x" << chunk_size << " bytes from "
826                             << partition_name_ << " @ offset 0x" << current_offset;
827                 ret_ = false;
828                 return;
829             }
830             if (!device_->HandleData(false /* is read */, buf.data(), chunk_size)) {
831                 PLOG(ERROR) << std::hex << "Unable to send 0x" << chunk_size << " bytes of "
832                             << partition_name_ << " @ offset 0x" << current_offset;
833                 ret_ = false;
834                 return;
835             }
836             current_offset += chunk_size;
837         }
838 
839         ret_ = device_->WriteOkay(android::base::StringPrintf(
840                 "Fetched %s (offset=0x%" PRIx64 ", size=0x%" PRIx64, partition_name_.c_str(),
841                 start_offset_, total_size_to_read_));
842     }
843 
844     static constexpr std::array<const char*, 3> kAllowedPartitions{
845             "vendor_boot",
846             "vendor_boot_a",
847             "vendor_boot_b",
848     };
849 
850     FastbootDevice* device_;
851     const std::vector<std::string>* args_ = nullptr;
852     std::string partition_name_;
853     PartitionHandle handle_;
854     uint64_t partition_size_ = 0;
855     uint64_t start_offset_ = 0;
856     uint64_t total_size_to_read_ = 0;
857 
858     // What FetchHandler should return.
859     std::optional<bool> ret_ = std::nullopt;
860 };
861 }  // namespace
862 
FetchHandler(FastbootDevice * device,const std::vector<std::string> & args)863 bool FetchHandler(FastbootDevice* device, const std::vector<std::string>& args) {
864     return PartitionFetcher::Fetch(device, args);
865 }
866