1 /*
2  * Copyright (C) 2019 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 "gsi_service.h"
18 
19 #include <errno.h>
20 #include <linux/fs.h>
21 #include <stdio.h>
22 #include <sys/ioctl.h>
23 #include <sys/stat.h>
24 #include <sys/types.h>
25 #include <sys/vfs.h>
26 #include <unistd.h>
27 
28 #include <array>
29 #include <chrono>
30 #include <string>
31 #include <vector>
32 
33 #include <android-base/errors.h>
34 #include <android-base/file.h>
35 #include <android-base/logging.h>
36 #include <android-base/properties.h>
37 #include <android-base/stringprintf.h>
38 #include <android-base/strings.h>
39 #include <android/gsi/BnImageService.h>
40 #include <android/gsi/IGsiService.h>
41 #include <binder/LazyServiceRegistrar.h>
42 #include <ext4_utils/ext4_utils.h>
43 #include <fs_mgr.h>
44 #include <libavb/libavb.h>
45 #include <libdm/dm.h>
46 #include <libfiemap/image_manager.h>
47 #include <openssl/sha.h>
48 #include <private/android_filesystem_config.h>
49 
50 #include "file_paths.h"
51 #include "libgsi_private.h"
52 
53 namespace android {
54 namespace gsi {
55 
56 using namespace std::literals;
57 using namespace android::fs_mgr;
58 using namespace android::fiemap;
59 using android::base::ReadFileToString;
60 using android::base::ReadFullyAtOffset;
61 using android::base::RemoveFileIfExists;
62 using android::base::SetProperty;
63 using android::base::StringPrintf;
64 using android::base::unique_fd;
65 using android::base::WriteStringToFd;
66 using android::base::WriteStringToFile;
67 using android::binder::LazyServiceRegistrar;
68 using android::dm::DeviceMapper;
69 
70 static std::mutex sInstanceLock;
71 
72 // Default userdata image size.
73 static constexpr int64_t kDefaultUserdataSize = int64_t(2) * 1024 * 1024 * 1024;
74 
75 static bool GetAvbPublicKeyFromFd(int fd, AvbPublicKey* dst);
76 
77 GsiService::GsiService() {
78     progress_ = {};
79 }
80 
81 void GsiService::Register() {
82     auto lazyRegistrar = LazyServiceRegistrar::getInstance();
83     android::sp<GsiService> service = new GsiService();
84     auto ret = lazyRegistrar.registerService(service, kGsiServiceName);
85 
86     if (ret != android::OK) {
87         LOG(FATAL) << "Could not register gsi service: " << ret;
88     }
89 }
90 
91 #define ENFORCE_SYSTEM                      \
92     do {                                    \
93         binder::Status status = CheckUid(); \
94         if (!status.isOk()) return status;  \
95     } while (0)
96 
97 #define ENFORCE_SYSTEM_OR_SHELL                                       \
98     do {                                                              \
99         binder::Status status = CheckUid(AccessLevel::SystemOrShell); \
100         if (!status.isOk()) return status;                            \
101     } while (0)
102 
103 int GsiService::SaveInstallation(const std::string& installation) {
104     auto dsu_slot = GetDsuSlot(installation);
105     auto install_dir_file = DsuInstallDirFile(dsu_slot);
106     auto metadata_dir = android::base::Dirname(install_dir_file);
107     if (access(metadata_dir.c_str(), F_OK) != 0) {
108         if (mkdir(metadata_dir.c_str(), 0777) != 0) {
109             PLOG(ERROR) << "Failed to mkdir " << metadata_dir;
110             return INSTALL_ERROR_GENERIC;
111         }
112     }
113     auto fd = android::base::unique_fd(
114             open(install_dir_file.c_str(), O_RDWR | O_SYNC | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR));
115     if (!WriteStringToFd(installation, fd)) {
116         PLOG(ERROR) << "write failed: " << DsuInstallDirFile(dsu_slot);
117         return INSTALL_ERROR_GENERIC;
118     }
119     return INSTALL_OK;
120 }
121 
122 binder::Status GsiService::openInstall(const std::string& install_dir, int* _aidl_return) {
123     ENFORCE_SYSTEM;
124     std::lock_guard<std::mutex> guard(lock_);
125     if (IsGsiRunning()) {
126         *_aidl_return = IGsiService::INSTALL_ERROR_GENERIC;
127         return binder::Status::ok();
128     }
129     install_dir_ = install_dir;
130     if (int status = ValidateInstallParams(install_dir_)) {
131         *_aidl_return = status;
132         return binder::Status::ok();
133     }
134     std::string message;
135     auto dsu_slot = GetDsuSlot(install_dir_);
136     if (!RemoveFileIfExists(GetCompleteIndication(dsu_slot), &message)) {
137         LOG(ERROR) << message;
138     }
139     // Remember the installation directory before allocate any resource
140     *_aidl_return = SaveInstallation(install_dir_);
141     return binder::Status::ok();
142 }
143 
144 binder::Status GsiService::closeInstall(int* _aidl_return) {
145     ENFORCE_SYSTEM;
146     std::lock_guard<std::mutex> guard(lock_);
147     auto dsu_slot = GetDsuSlot(install_dir_);
148     std::string file = GetCompleteIndication(dsu_slot);
149     if (!WriteStringToFile("OK", file)) {
150         PLOG(ERROR) << "write failed: " << file;
151         *_aidl_return = INSTALL_ERROR_GENERIC;
152     }
153     *_aidl_return = INSTALL_OK;
154     return binder::Status::ok();
155 }
156 
157 binder::Status GsiService::createPartition(const ::std::string& name, int64_t size, bool readOnly,
158                                            int32_t* _aidl_return) {
159     ENFORCE_SYSTEM;
160     std::lock_guard<std::mutex> guard(lock_);
161 
162     if (install_dir_.empty()) {
163         PLOG(ERROR) << "open is required for createPartition";
164         *_aidl_return = INSTALL_ERROR_GENERIC;
165         return binder::Status::ok();
166     }
167 
168     // Make sure a pending interrupted installations are cleaned up.
169     installer_ = nullptr;
170 
171     // Do some precursor validation on the arguments before diving into the
172     // install process.
173     if (size % LP_SECTOR_SIZE) {
174         LOG(ERROR) << " size " << size << " is not a multiple of " << LP_SECTOR_SIZE;
175         *_aidl_return = INSTALL_ERROR_GENERIC;
176         return binder::Status::ok();
177     }
178 
179     if (size == 0 && name == "userdata") {
180         size = kDefaultUserdataSize;
181     }
182     installer_ = std::make_unique<PartitionInstaller>(this, install_dir_, name,
183                                                       GetDsuSlot(install_dir_), size, readOnly);
184     progress_ = {};
185     int status = installer_->StartInstall();
186     if (status != INSTALL_OK) {
187         installer_ = nullptr;
188     }
189     *_aidl_return = status;
190     return binder::Status::ok();
191 }
192 
193 binder::Status GsiService::commitGsiChunkFromStream(const android::os::ParcelFileDescriptor& stream,
194                                                     int64_t bytes, bool* _aidl_return) {
195     ENFORCE_SYSTEM;
196     std::lock_guard<std::mutex> guard(lock_);
197 
198     if (!installer_) {
199         *_aidl_return = false;
200         return binder::Status::ok();
201     }
202 
203     *_aidl_return = installer_->CommitGsiChunk(stream.get(), bytes);
204     return binder::Status::ok();
205 }
206 
207 void GsiService::StartAsyncOperation(const std::string& step, int64_t total_bytes) {
208     std::lock_guard<std::mutex> guard(progress_lock_);
209 
210     progress_.step = step;
211     progress_.status = STATUS_WORKING;
212     progress_.bytes_processed = 0;
213     progress_.total_bytes = total_bytes;
214 }
215 
216 void GsiService::UpdateProgress(int status, int64_t bytes_processed) {
217     std::lock_guard<std::mutex> guard(progress_lock_);
218 
219     progress_.status = status;
220     if (status == STATUS_COMPLETE) {
221         progress_.bytes_processed = progress_.total_bytes;
222     } else {
223         progress_.bytes_processed = bytes_processed;
224     }
225 }
226 
227 binder::Status GsiService::getInstallProgress(::android::gsi::GsiProgress* _aidl_return) {
228     ENFORCE_SYSTEM;
229     std::lock_guard<std::mutex> guard(progress_lock_);
230 
231     if (installer_ == nullptr) {
232         progress_ = {};
233     }
234     *_aidl_return = progress_;
235     return binder::Status::ok();
236 }
237 
238 binder::Status GsiService::commitGsiChunkFromAshmem(int64_t bytes, bool* _aidl_return) {
239     ENFORCE_SYSTEM;
240     std::lock_guard<std::mutex> guard(lock_);
241 
242     if (!installer_) {
243         *_aidl_return = false;
244         return binder::Status::ok();
245     }
246     *_aidl_return = installer_->CommitGsiChunk(bytes);
247     return binder::Status::ok();
248 }
249 
250 binder::Status GsiService::setGsiAshmem(const ::android::os::ParcelFileDescriptor& ashmem,
251                                         int64_t size, bool* _aidl_return) {
252     ENFORCE_SYSTEM;
253     if (!installer_) {
254         *_aidl_return = false;
255         return binder::Status::ok();
256     }
257     *_aidl_return = installer_->MapAshmem(ashmem.get(), size);
258     return binder::Status::ok();
259 }
260 
261 binder::Status GsiService::enableGsiAsync(bool one_shot, const std::string& dsuSlot,
262                                           const sp<IGsiServiceCallback>& resultCallback) {
263     int result;
264     auto status = enableGsi(one_shot, dsuSlot, &result);
265     if (!status.isOk()) {
266         LOG(ERROR) << "Could not enableGsi: " << status.exceptionMessage().string();
267         result = IGsiService::INSTALL_ERROR_GENERIC;
268     }
269     resultCallback->onResult(result);
270     return binder::Status::ok();
271 }
272 
273 binder::Status GsiService::enableGsi(bool one_shot, const std::string& dsuSlot, int* _aidl_return) {
274     std::lock_guard<std::mutex> guard(lock_);
275 
276     if (!WriteStringToFile(dsuSlot, kDsuActiveFile)) {
277         PLOG(ERROR) << "write failed: " << GetDsuSlot(install_dir_);
278         *_aidl_return = INSTALL_ERROR_GENERIC;
279         return binder::Status::ok();
280     }
281     if (installer_) {
282         ENFORCE_SYSTEM;
283         installer_ = {};
284         // Note: create the install status file last, since this is the actual boot
285         // indicator.
286         if (!SetBootMode(one_shot) || !CreateInstallStatusFile()) {
287             *_aidl_return = IGsiService::INSTALL_ERROR_GENERIC;
288         } else {
289             *_aidl_return = INSTALL_OK;
290         }
291     } else {
292         ENFORCE_SYSTEM_OR_SHELL;
293         *_aidl_return = ReenableGsi(one_shot);
294     }
295 
296     installer_ = nullptr;
297     return binder::Status::ok();
298 }
299 
300 binder::Status GsiService::isGsiEnabled(bool* _aidl_return) {
301     ENFORCE_SYSTEM_OR_SHELL;
302     std::lock_guard<std::mutex> guard(lock_);
303     std::string boot_key;
304     if (!GetInstallStatus(&boot_key)) {
305         *_aidl_return = false;
306     } else {
307         *_aidl_return = (boot_key != kInstallStatusDisabled);
308     }
309     return binder::Status::ok();
310 }
311 
312 binder::Status GsiService::removeGsiAsync(const sp<IGsiServiceCallback>& resultCallback) {
313     bool result;
314     auto status = removeGsi(&result);
315     if (!status.isOk()) {
316         LOG(ERROR) << "Could not removeGsi: " << status.exceptionMessage().string();
317         result = IGsiService::INSTALL_ERROR_GENERIC;
318     }
319     resultCallback->onResult(result);
320     return binder::Status::ok();
321 }
322 
323 binder::Status GsiService::removeGsi(bool* _aidl_return) {
324     ENFORCE_SYSTEM_OR_SHELL;
325     std::lock_guard<std::mutex> guard(lock_);
326 
327     std::string install_dir = GetActiveInstalledImageDir();
328     if (IsGsiRunning()) {
329         // Can't remove gsi files while running.
330         *_aidl_return = UninstallGsi();
331     } else {
332         installer_ = {};
333         *_aidl_return = RemoveGsiFiles(install_dir);
334     }
335     return binder::Status::ok();
336 }
337 
338 binder::Status GsiService::disableGsi(bool* _aidl_return) {
339     ENFORCE_SYSTEM_OR_SHELL;
340     std::lock_guard<std::mutex> guard(lock_);
341 
342     *_aidl_return = DisableGsiInstall();
343     return binder::Status::ok();
344 }
345 
346 binder::Status GsiService::isGsiRunning(bool* _aidl_return) {
347     ENFORCE_SYSTEM_OR_SHELL;
348     std::lock_guard<std::mutex> guard(lock_);
349 
350     *_aidl_return = IsGsiRunning();
351     return binder::Status::ok();
352 }
353 
354 binder::Status GsiService::isGsiInstalled(bool* _aidl_return) {
355     ENFORCE_SYSTEM_OR_SHELL;
356     std::lock_guard<std::mutex> guard(lock_);
357 
358     *_aidl_return = IsGsiInstalled();
359     return binder::Status::ok();
360 }
361 
362 binder::Status GsiService::isGsiInstallInProgress(bool* _aidl_return) {
363     ENFORCE_SYSTEM_OR_SHELL;
364     std::lock_guard<std::mutex> guard(lock_);
365 
366     *_aidl_return = !!installer_;
367     return binder::Status::ok();
368 }
369 
370 binder::Status GsiService::cancelGsiInstall(bool* _aidl_return) {
371     ENFORCE_SYSTEM;
372     should_abort_ = true;
373     std::lock_guard<std::mutex> guard(lock_);
374 
375     should_abort_ = false;
376     installer_ = nullptr;
377 
378     *_aidl_return = true;
379     return binder::Status::ok();
380 }
381 
382 binder::Status GsiService::getInstalledGsiImageDir(std::string* _aidl_return) {
383     ENFORCE_SYSTEM;
384     std::lock_guard<std::mutex> guard(lock_);
385 
386     *_aidl_return = GetActiveInstalledImageDir();
387     return binder::Status::ok();
388 }
389 
390 binder::Status GsiService::getActiveDsuSlot(std::string* _aidl_return) {
391     ENFORCE_SYSTEM_OR_SHELL;
392     std::lock_guard<std::mutex> guard(lock_);
393 
394     *_aidl_return = GetActiveDsuSlot();
395     return binder::Status::ok();
396 }
397 
398 binder::Status GsiService::getInstalledDsuSlots(std::vector<std::string>* _aidl_return) {
399     ENFORCE_SYSTEM;
400     std::lock_guard<std::mutex> guard(lock_);
401     *_aidl_return = GetInstalledDsuSlots();
402     return binder::Status::ok();
403 }
404 
405 binder::Status GsiService::zeroPartition(const std::string& name, int* _aidl_return) {
406     ENFORCE_SYSTEM_OR_SHELL;
407     std::lock_guard<std::mutex> guard(lock_);
408 
409     if (IsGsiRunning() || !IsGsiInstalled()) {
410         *_aidl_return = IGsiService::INSTALL_ERROR_GENERIC;
411         return binder::Status::ok();
412     }
413 
414     std::string install_dir = GetActiveInstalledImageDir();
415     *_aidl_return = PartitionInstaller::WipeWritable(GetDsuSlot(install_dir), install_dir, name);
416 
417     return binder::Status::ok();
418 }
419 
420 static binder::Status BinderError(const std::string& message,
421                                   FiemapStatus::ErrorCode status = FiemapStatus::ErrorCode::ERROR) {
422     return binder::Status::fromServiceSpecificError(static_cast<int32_t>(status), message.c_str());
423 }
424 
425 binder::Status GsiService::dumpDeviceMapperDevices(std::string* _aidl_return) {
426     ENFORCE_SYSTEM_OR_SHELL;
427 
428     auto& dm = DeviceMapper::Instance();
429 
430     std::vector<DeviceMapper::DmBlockDevice> devices;
431     if (!dm.GetAvailableDevices(&devices)) {
432         return BinderError("Could not list devices");
433     }
434 
435     std::stringstream text;
436     for (const auto& device : devices) {
437         text << "Device " << device.name() << " (" << device.Major() << ":" << device.Minor()
438              << ")\n";
439 
440         std::vector<DeviceMapper::TargetInfo> table;
441         if (!dm.GetTableInfo(device.name(), &table)) {
442             continue;
443         }
444 
445         for (const auto& target : table) {
446             const auto& spec = target.spec;
447             auto target_type = DeviceMapper::GetTargetType(spec);
448             text << "    " << target_type << " " << spec.sector_start << " " << spec.length << " "
449                  << target.data << "\n";
450         }
451     }
452 
453     *_aidl_return = text.str();
454     return binder::Status::ok();
455 }
456 
457 binder::Status GsiService::getAvbPublicKey(AvbPublicKey* dst, int32_t* _aidl_return) {
458     ENFORCE_SYSTEM;
459     std::lock_guard<std::mutex> guard(lock_);
460 
461     if (!installer_) {
462         *_aidl_return = INSTALL_ERROR_GENERIC;
463         return binder::Status::ok();
464     }
465     int fd = installer_->GetPartitionFd();
466     if (!GetAvbPublicKeyFromFd(fd, dst)) {
467         LOG(ERROR) << "Failed to extract AVB public key";
468         *_aidl_return = INSTALL_ERROR_GENERIC;
469         return binder::Status::ok();
470     }
471     *_aidl_return = INSTALL_OK;
472     return binder::Status::ok();
473 }
474 
475 bool GsiService::CreateInstallStatusFile() {
476     if (!android::base::WriteStringToFile("0", kDsuInstallStatusFile)) {
477         PLOG(ERROR) << "write " << kDsuInstallStatusFile;
478         return false;
479     }
480     SetProperty(kGsiInstalledProp, "1");
481     return true;
482 }
483 
484 bool GsiService::SetBootMode(bool one_shot) {
485     if (one_shot) {
486         if (!android::base::WriteStringToFile("1", kDsuOneShotBootFile)) {
487             PLOG(ERROR) << "write " << kDsuOneShotBootFile;
488             return false;
489         }
490     } else if (!access(kDsuOneShotBootFile, F_OK)) {
491         std::string error;
492         if (!android::base::RemoveFileIfExists(kDsuOneShotBootFile, &error)) {
493             LOG(ERROR) << error;
494             return false;
495         }
496     }
497     return true;
498 }
499 
500 static binder::Status UidSecurityError() {
501     uid_t uid = IPCThreadState::self()->getCallingUid();
502     auto message = StringPrintf("UID %d is not allowed", uid);
503     return binder::Status::fromExceptionCode(binder::Status::EX_SECURITY, String8(message.c_str()));
504 }
505 
506 class ImageService : public BinderService<ImageService>, public BnImageService {
507   public:
508     ImageService(GsiService* service, std::unique_ptr<ImageManager>&& impl, uid_t uid);
509     binder::Status getAllBackingImages(std::vector<std::string>* _aidl_return);
510     binder::Status createBackingImage(const std::string& name, int64_t size, int flags,
511                                       const sp<IProgressCallback>& on_progress) override;
512     binder::Status deleteBackingImage(const std::string& name) override;
513     binder::Status mapImageDevice(const std::string& name, int32_t timeout_ms,
514                                   MappedImage* mapping) override;
515     binder::Status unmapImageDevice(const std::string& name) override;
516     binder::Status backingImageExists(const std::string& name, bool* _aidl_return) override;
517     binder::Status isImageMapped(const std::string& name, bool* _aidl_return) override;
518     binder::Status getAvbPublicKey(const std::string& name, AvbPublicKey* dst,
519                                    int32_t* _aidl_return) override;
520     binder::Status zeroFillNewImage(const std::string& name, int64_t bytes) override;
521     binder::Status removeAllImages() override;
522     binder::Status removeDisabledImages() override;
523     binder::Status getMappedImageDevice(const std::string& name, std::string* device) override;
524 
525   private:
526     bool CheckUid();
527 
528     android::sp<GsiService> service_;
529     std::unique_ptr<ImageManager> impl_;
530     uid_t uid_;
531 };
532 
533 ImageService::ImageService(GsiService* service, std::unique_ptr<ImageManager>&& impl, uid_t uid)
534     : service_(service), impl_(std::move(impl)), uid_(uid) {}
535 
536 binder::Status ImageService::getAllBackingImages(std::vector<std::string>* _aidl_return) {
537     *_aidl_return = impl_->GetAllBackingImages();
538     return binder::Status::ok();
539 }
540 
541 binder::Status ImageService::createBackingImage(const std::string& name, int64_t size, int flags,
542                                                 const sp<IProgressCallback>& on_progress) {
543     if (!CheckUid()) return UidSecurityError();
544 
545     std::lock_guard<std::mutex> guard(service_->lock());
546 
547     std::function<bool(uint64_t, uint64_t)> callback;
548     if (on_progress) {
549         callback = [on_progress](uint64_t current, uint64_t total) -> bool {
550             auto status = on_progress->onProgress(static_cast<int64_t>(current),
551                                                   static_cast<int64_t>(total));
552             if (!status.isOk()) {
553                 LOG(ERROR) << "progress callback returned: " << status.toString8().string();
554                 return false;
555             }
556             return true;
557         };
558     }
559 
560     auto res = impl_->CreateBackingImage(name, size, flags, std::move(callback));
561     if (!res.is_ok()) {
562         return BinderError("Failed to create: " + res.string(), res.error_code());
563     }
564     return binder::Status::ok();
565 }
566 
567 binder::Status ImageService::deleteBackingImage(const std::string& name) {
568     if (!CheckUid()) return UidSecurityError();
569 
570     std::lock_guard<std::mutex> guard(service_->lock());
571 
572     if (!impl_->DeleteBackingImage(name)) {
573         return BinderError("Failed to delete");
574     }
575     return binder::Status::ok();
576 }
577 
578 binder::Status ImageService::mapImageDevice(const std::string& name, int32_t timeout_ms,
579                                             MappedImage* mapping) {
580     if (!CheckUid()) return UidSecurityError();
581 
582     std::lock_guard<std::mutex> guard(service_->lock());
583 
584     if (!impl_->MapImageDevice(name, std::chrono::milliseconds(timeout_ms), &mapping->path)) {
585         return BinderError("Failed to map");
586     }
587     return binder::Status::ok();
588 }
589 
590 binder::Status ImageService::unmapImageDevice(const std::string& name) {
591     if (!CheckUid()) return UidSecurityError();
592 
593     std::lock_guard<std::mutex> guard(service_->lock());
594 
595     if (!impl_->UnmapImageDevice(name)) {
596         return BinderError("Failed to unmap");
597     }
598     return binder::Status::ok();
599 }
600 
601 binder::Status ImageService::backingImageExists(const std::string& name, bool* _aidl_return) {
602     if (!CheckUid()) return UidSecurityError();
603 
604     std::lock_guard<std::mutex> guard(service_->lock());
605 
606     *_aidl_return = impl_->BackingImageExists(name);
607     return binder::Status::ok();
608 }
609 
610 binder::Status ImageService::isImageMapped(const std::string& name, bool* _aidl_return) {
611     if (!CheckUid()) return UidSecurityError();
612 
613     std::lock_guard<std::mutex> guard(service_->lock());
614 
615     *_aidl_return = impl_->IsImageMapped(name);
616     return binder::Status::ok();
617 }
618 
619 binder::Status ImageService::getAvbPublicKey(const std::string& name, AvbPublicKey* dst,
620                                              int32_t* _aidl_return) {
621     if (!CheckUid()) return UidSecurityError();
622 
623     std::lock_guard<std::mutex> guard(service_->lock());
624 
625     std::string device_path;
626     std::unique_ptr<MappedDevice> mapped_device;
627     if (!impl_->IsImageMapped(name)) {
628         mapped_device = MappedDevice::Open(impl_.get(), 10s, name);
629         if (!mapped_device) {
630             PLOG(ERROR) << "Fail to map image: " << name;
631             *_aidl_return = IMAGE_ERROR;
632             return binder::Status::ok();
633         }
634         device_path = mapped_device->path();
635     } else {
636         if (!impl_->GetMappedImageDevice(name, &device_path)) {
637             PLOG(ERROR) << "GetMappedImageDevice() failed";
638             *_aidl_return = IMAGE_ERROR;
639             return binder::Status::ok();
640         }
641     }
642     android::base::unique_fd fd(open(device_path.c_str(), O_RDONLY | O_CLOEXEC));
643     if (!fd.ok()) {
644         PLOG(ERROR) << "Fail to open mapped device: " << device_path;
645         *_aidl_return = IMAGE_ERROR;
646         return binder::Status::ok();
647     }
648     bool ok = GetAvbPublicKeyFromFd(fd.get(), dst);
649     fd = {};
650     if (!ok) {
651         LOG(ERROR) << "Failed to extract AVB public key";
652         *_aidl_return = IMAGE_ERROR;
653         return binder::Status::ok();
654     }
655     *_aidl_return = IMAGE_OK;
656     return binder::Status::ok();
657 }
658 
659 binder::Status ImageService::zeroFillNewImage(const std::string& name, int64_t bytes) {
660     if (!CheckUid()) return UidSecurityError();
661 
662     std::lock_guard<std::mutex> guard(service_->lock());
663 
664     if (bytes < 0) {
665         return BinderError("Cannot use negative values");
666     }
667     auto res = impl_->ZeroFillNewImage(name, bytes);
668     if (!res.is_ok()) {
669         return BinderError("Failed to fill image with zeros: " + res.string(), res.error_code());
670     }
671     return binder::Status::ok();
672 }
673 
674 binder::Status ImageService::removeAllImages() {
675     if (!CheckUid()) return UidSecurityError();
676 
677     std::lock_guard<std::mutex> guard(service_->lock());
678     if (!impl_->RemoveAllImages()) {
679         return BinderError("Failed to remove all images");
680     }
681     return binder::Status::ok();
682 }
683 
684 binder::Status ImageService::removeDisabledImages() {
685     if (!CheckUid()) return UidSecurityError();
686 
687     std::lock_guard<std::mutex> guard(service_->lock());
688     if (!impl_->RemoveDisabledImages()) {
689         return BinderError("Failed to remove disabled images");
690     }
691     return binder::Status::ok();
692 }
693 
694 binder::Status ImageService::getMappedImageDevice(const std::string& name, std::string* device) {
695     if (!CheckUid()) return UidSecurityError();
696 
697     std::lock_guard<std::mutex> guard(service_->lock());
698     if (!impl_->GetMappedImageDevice(name, device)) {
699         *device = "";
700     }
701     return binder::Status::ok();
702 }
703 
704 bool ImageService::CheckUid() {
705     return uid_ == IPCThreadState::self()->getCallingUid();
706 }
707 
708 binder::Status GsiService::openImageService(const std::string& prefix,
709                                             android::sp<IImageService>* _aidl_return) {
710     static constexpr char kImageMetadataPrefix[] = "/metadata/gsi/";
711     static constexpr char kImageDataPrefix[] = "/data/gsi/";
712 
713     auto in_metadata_dir = kImageMetadataPrefix + prefix;
714     auto in_data_dir = kImageDataPrefix + prefix;
715     auto install_dir_file = DsuInstallDirFile(GetDsuSlot(prefix));
716 
717     std::string in_data_dir_tmp;
718     if (android::base::ReadFileToString(install_dir_file, &in_data_dir_tmp)) {
719         in_data_dir = in_data_dir_tmp;
720         LOG(INFO) << "load " << install_dir_file << ":" << in_data_dir;
721     }
722     std::string metadata_dir, data_dir;
723     if (!android::base::Realpath(in_metadata_dir, &metadata_dir)) {
724         PLOG(ERROR) << "realpath failed for metadata: " << in_metadata_dir;
725         return BinderError("Invalid path");
726     }
727     if (!android::base::Realpath(in_data_dir, &data_dir)) {
728         PLOG(ERROR) << "realpath failed for data: " << in_data_dir;
729         return BinderError("Invalid path");
730     }
731     if (!android::base::StartsWith(metadata_dir, kImageMetadataPrefix) ||
732         !android::base::StartsWith(data_dir, kImageDataPrefix)) {
733         return BinderError("Invalid path");
734     }
735 
736     uid_t uid = IPCThreadState::self()->getCallingUid();
737     if (uid != AID_ROOT) {
738         return UidSecurityError();
739     }
740 
741     auto impl = ImageManager::Open(metadata_dir, data_dir);
742     if (!impl) {
743         return BinderError("Unknown error");
744     }
745 
746     *_aidl_return = new ImageService(this, std::move(impl), uid);
747     return binder::Status::ok();
748 }
749 
750 binder::Status GsiService::CheckUid(AccessLevel level) {
751     std::vector<uid_t> allowed_uids{AID_ROOT, AID_SYSTEM};
752     if (level == AccessLevel::SystemOrShell) {
753         allowed_uids.push_back(AID_SHELL);
754     }
755 
756     uid_t uid = IPCThreadState::self()->getCallingUid();
757     for (const auto& allowed_uid : allowed_uids) {
758         if (allowed_uid == uid) {
759             return binder::Status::ok();
760         }
761     }
762     return UidSecurityError();
763 }
764 
765 static bool IsExternalStoragePath(const std::string& path) {
766     if (!android::base::StartsWith(path, "/mnt/media_rw/")) {
767         return false;
768     }
769     unique_fd fd(open(path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
770     if (fd < 0) {
771         PLOG(ERROR) << "open failed: " << path;
772         return false;
773     }
774     struct statfs info;
775     if (fstatfs(fd, &info)) {
776         PLOG(ERROR) << "statfs failed: " << path;
777         return false;
778     }
779     LOG(ERROR) << "fs type: " << info.f_type;
780     return info.f_type == MSDOS_SUPER_MAGIC;
781 }
782 
783 int GsiService::ValidateInstallParams(std::string& install_dir) {
784     // If no install path was specified, use the default path. We also allow
785     // specifying the top-level folder, and then we choose the correct location
786     // underneath.
787     if (install_dir.empty() || install_dir == "/data/gsi") {
788         install_dir = kDefaultDsuImageFolder;
789     }
790 
791     // Normalize the path and add a trailing slash.
792     std::string origInstallDir = install_dir;
793     if (!android::base::Realpath(origInstallDir, &install_dir)) {
794         PLOG(ERROR) << "realpath failed: " << origInstallDir;
795         return INSTALL_ERROR_GENERIC;
796     }
797     // Ensure the path ends in / for consistency.
798     if (!android::base::EndsWith(install_dir, "/")) {
799         install_dir += "/";
800     }
801 
802     // Currently, we can only install to /data/gsi/ or external storage.
803     if (IsExternalStoragePath(install_dir)) {
804         Fstab fstab;
805         if (!ReadDefaultFstab(&fstab)) {
806             LOG(ERROR) << "cannot read default fstab";
807             return INSTALL_ERROR_GENERIC;
808         }
809         FstabEntry* system = GetEntryForMountPoint(&fstab, "/system");
810         if (!system) {
811             LOG(ERROR) << "cannot find /system fstab entry";
812             return INSTALL_ERROR_GENERIC;
813         }
814         if (fs_mgr_verity_is_check_at_most_once(*system)) {
815             LOG(ERROR) << "cannot install GSIs to external media if verity uses check_at_most_once";
816             return INSTALL_ERROR_GENERIC;
817         }
818     } else if (install_dir != kDefaultDsuImageFolder) {
819         LOG(ERROR) << "cannot install DSU to " << install_dir;
820         return INSTALL_ERROR_GENERIC;
821     }
822     return INSTALL_OK;
823 }
824 
825 std::string GsiService::GetActiveDsuSlot() {
826     if (!install_dir_.empty()) {
827         return GetDsuSlot(install_dir_);
828     } else {
829         std::string active_dsu;
830         return GetActiveDsu(&active_dsu) ? active_dsu : "";
831     }
832 }
833 
834 std::string GsiService::GetActiveInstalledImageDir() {
835     // Just in case an install was left hanging.
836     if (installer_) {
837         return installer_->install_dir();
838     } else {
839         return GetInstalledImageDir();
840     }
841 }
842 
843 std::string GsiService::GetInstalledImageDir() {
844     // If there's no install left, just return /data/gsi since that's where
845     // installs go by default.
846     std::string active_dsu;
847     std::string dir;
848     if (GetActiveDsu(&active_dsu) &&
849         android::base::ReadFileToString(DsuInstallDirFile(active_dsu), &dir)) {
850         return dir;
851     }
852     return kDefaultDsuImageFolder;
853 }
854 
855 int GsiService::ReenableGsi(bool one_shot) {
856     if (!android::gsi::IsGsiInstalled()) {
857         LOG(ERROR) << "no gsi installed - cannot re-enable";
858         return INSTALL_ERROR_GENERIC;
859     }
860     std::string boot_key;
861     if (!GetInstallStatus(&boot_key)) {
862         PLOG(ERROR) << "read " << kDsuInstallStatusFile;
863         return INSTALL_ERROR_GENERIC;
864     }
865     if (boot_key != kInstallStatusDisabled) {
866         LOG(ERROR) << "GSI is not currently disabled";
867         return INSTALL_ERROR_GENERIC;
868     }
869     if (IsGsiRunning()) {
870         if (!SetBootMode(one_shot) || !CreateInstallStatusFile()) {
871             return IGsiService::INSTALL_ERROR_GENERIC;
872         }
873         return IGsiService::INSTALL_OK;
874     }
875     if (!SetBootMode(one_shot) || !CreateInstallStatusFile()) {
876         return IGsiService::INSTALL_ERROR_GENERIC;
877     }
878     return IGsiService::INSTALL_OK;
879 }
880 
881 bool GsiService::RemoveGsiFiles(const std::string& install_dir) {
882     bool ok = true;
883     auto active_dsu = GetDsuSlot(install_dir);
884     if (auto manager = ImageManager::Open(MetadataDir(active_dsu), install_dir)) {
885         std::vector<std::string> images = manager->GetAllBackingImages();
886         for (auto&& image : images) {
887             if (!android::base::EndsWith(image, kDsuPostfix)) {
888                 continue;
889             }
890             if (manager->IsImageMapped(image)) {
891                 ok &= manager->UnmapImageDevice(image);
892             }
893             ok &= manager->DeleteBackingImage(image);
894         }
895     }
896     auto dsu_slot = GetDsuSlot(install_dir);
897     std::vector<std::string> files{
898             kDsuInstallStatusFile,
899             kDsuOneShotBootFile,
900             DsuInstallDirFile(dsu_slot),
901             GetCompleteIndication(dsu_slot),
902     };
903     for (const auto& file : files) {
904         std::string message;
905         if (!RemoveFileIfExists(file, &message)) {
906             LOG(ERROR) << message;
907             ok = false;
908         }
909     }
910     if (ok) {
911         SetProperty(kGsiInstalledProp, "0");
912     }
913     return ok;
914 }
915 
916 bool GsiService::DisableGsiInstall() {
917     if (!android::gsi::IsGsiInstalled()) {
918         LOG(ERROR) << "cannot disable gsi install - no install detected";
919         return false;
920     }
921     if (installer_) {
922         LOG(ERROR) << "cannot disable gsi during GSI installation";
923         return false;
924     }
925     if (!DisableGsi()) {
926         PLOG(ERROR) << "could not write gsi status";
927         return false;
928     }
929     return true;
930 }
931 
932 std::string GsiService::GetCompleteIndication(const std::string& dsu_slot) {
933     return DSU_METADATA_PREFIX + dsu_slot + "/complete";
934 }
935 
936 bool GsiService::IsInstallationComplete(const std::string& dsu_slot) {
937     if (access(kDsuInstallStatusFile, F_OK) != 0) {
938         return false;
939     }
940     std::string file = GetCompleteIndication(dsu_slot);
941     std::string content;
942     if (!ReadFileToString(file, &content)) {
943         return false;
944     }
945     return content == "OK";
946 }
947 
948 std::vector<std::string> GsiService::GetInstalledDsuSlots() {
949     std::vector<std::string> dsu_slots;
950     auto d = std::unique_ptr<DIR, decltype(&closedir)>(opendir(DSU_METADATA_PREFIX), closedir);
951     if (d != nullptr) {
952         struct dirent* de;
953         while ((de = readdir(d.get())) != nullptr) {
954             if (de->d_name[0] == '.') {
955                 continue;
956             }
957             auto dsu_slot = std::string(de->d_name);
958             if (access(DsuInstallDirFile(dsu_slot).c_str(), F_OK) != 0) {
959                 continue;
960             }
961             dsu_slots.push_back(dsu_slot);
962         }
963     }
964     return dsu_slots;
965 }
966 
967 void GsiService::CleanCorruptedInstallation() {
968     for (auto&& slot : GetInstalledDsuSlots()) {
969         bool is_complete = IsInstallationComplete(slot);
970         if (!is_complete) {
971             LOG(INFO) << "CleanCorruptedInstallation for slot: " << slot;
972             std::string install_dir;
973             if (!android::base::ReadFileToString(DsuInstallDirFile(slot), &install_dir) ||
974                 !RemoveGsiFiles(install_dir)) {
975                 LOG(ERROR) << "Failed to CleanCorruptedInstallation on " << slot;
976             }
977         }
978     }
979 }
980 
981 void GsiService::RunStartupTasks() {
982     CleanCorruptedInstallation();
983 
984     std::string active_dsu;
985     if (!GetActiveDsu(&active_dsu)) {
986         PLOG(INFO) << "no DSU";
987         return;
988     }
989     std::string boot_key;
990     if (!GetInstallStatus(&boot_key)) {
991         PLOG(ERROR) << "read " << kDsuInstallStatusFile;
992         return;
993     }
994 
995     if (!IsGsiRunning()) {
996         // Check if a wipe was requested from fastboot or adb-in-gsi.
997         if (boot_key == kInstallStatusWipe) {
998             RemoveGsiFiles(GetInstalledImageDir());
999         }
1000     } else {
1001         // NB: When single-boot is enabled, init will write "disabled" into the
1002         // install_status file, which will cause GetBootAttempts to return
1003         // false. Thus, we won't write "ok" here.
1004         int ignore;
1005         if (GetBootAttempts(boot_key, &ignore)) {
1006             // Mark the GSI as having successfully booted.
1007             if (!android::base::WriteStringToFile(kInstallStatusOk, kDsuInstallStatusFile)) {
1008                 PLOG(ERROR) << "write " << kDsuInstallStatusFile;
1009             }
1010         }
1011     }
1012 }
1013 
1014 static bool GetAvbPublicKeyFromFd(int fd, AvbPublicKey* dst) {
1015     // Read the AVB footer from EOF.
1016     int64_t total_size = get_block_device_size(fd);
1017     int64_t footer_offset = total_size - AVB_FOOTER_SIZE;
1018     std::array<uint8_t, AVB_FOOTER_SIZE> footer_bytes;
1019     if (!ReadFullyAtOffset(fd, footer_bytes.data(), AVB_FOOTER_SIZE, footer_offset)) {
1020         PLOG(ERROR) << "cannot read AVB footer";
1021         return false;
1022     }
1023     // Validate the AVB footer data and byte swap to native byte order.
1024     AvbFooter footer;
1025     if (!avb_footer_validate_and_byteswap((const AvbFooter*)footer_bytes.data(), &footer)) {
1026         LOG(ERROR) << "invalid AVB footer";
1027         return false;
1028     }
1029     // Read the VBMeta image.
1030     std::vector<uint8_t> vbmeta_bytes(footer.vbmeta_size);
1031     if (!ReadFullyAtOffset(fd, vbmeta_bytes.data(), vbmeta_bytes.size(), footer.vbmeta_offset)) {
1032         PLOG(ERROR) << "cannot read VBMeta image";
1033         return false;
1034     }
1035     // Validate the VBMeta image and retrieve AVB public key.
1036     // After a successful call to avb_vbmeta_image_verify(), public_key_data
1037     // will point to the serialized AVB public key, in the same format generated
1038     // by the `avbtool extract_public_key` command.
1039     const uint8_t* public_key_data;
1040     size_t public_key_size;
1041     AvbVBMetaVerifyResult result = avb_vbmeta_image_verify(vbmeta_bytes.data(), vbmeta_bytes.size(),
1042                                                            &public_key_data, &public_key_size);
1043     if (result != AVB_VBMETA_VERIFY_RESULT_OK) {
1044         LOG(ERROR) << "invalid VBMeta image: " << avb_vbmeta_verify_result_to_string(result);
1045         return false;
1046     }
1047     if (public_key_data != nullptr) {
1048         dst->bytes.resize(public_key_size);
1049         memcpy(dst->bytes.data(), public_key_data, public_key_size);
1050         dst->sha1.resize(SHA_DIGEST_LENGTH);
1051         SHA1(public_key_data, public_key_size, dst->sha1.data());
1052     }
1053     return true;
1054 }
1055 
1056 }  // namespace gsi
1057 }  // namespace android
1058