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