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 "BinderIncrementalService.h"
18 
19 #include <android-base/logging.h>
20 #include <android-base/no_destructor.h>
21 #include <android/os/IVold.h>
22 #include <binder/IResultReceiver.h>
23 #include <binder/PermissionCache.h>
24 #include <incfs.h>
25 
26 #include "ServiceWrappers.h"
27 #include "jni.h"
28 #include "path.h"
29 
30 using namespace std::literals;
31 using namespace android::incremental;
32 
33 namespace android::os::incremental {
34 
35 static constexpr auto kAndroidDataEnv = "ANDROID_DATA"sv;
36 static constexpr auto kDataDir = "/data"sv;
37 static constexpr auto kIncrementalSubDir = "incremental"sv;
38 
getIncrementalDir()39 static std::string getIncrementalDir() {
40     const char* dataDir = getenv(kAndroidDataEnv.data());
41     if (!dataDir || !*dataDir) {
42         dataDir = kDataDir.data();
43     }
44     return path::normalize(path::join(dataDir, kIncrementalSubDir));
45 }
46 
incFsEnabled()47 static bool incFsEnabled() {
48     // TODO(b/136132412): use vold to check /sys/fs/incfs/version (per selinux compliance)
49     return incfs::enabled();
50 }
51 
incFsValid(const sp<IVold> & vold)52 static bool incFsValid(const sp<IVold>& vold) {
53     bool enabled = false;
54     auto status = vold->incFsEnabled(&enabled);
55     if (!status.isOk() || !enabled) {
56         return false;
57     }
58     return true;
59 }
60 
BinderIncrementalService(const sp<IServiceManager> & sm,JNIEnv * env)61 BinderIncrementalService::BinderIncrementalService(const sp<IServiceManager>& sm, JNIEnv* env)
62       : mImpl(RealServiceManager(sm, env), getIncrementalDir()) {}
63 
start(JNIEnv * env)64 BinderIncrementalService* BinderIncrementalService::start(JNIEnv* env) {
65     if (!incFsEnabled()) {
66         return nullptr;
67     }
68 
69     IPCThreadState::self()->disableBackgroundScheduling(true);
70     sp<IServiceManager> sm(defaultServiceManager());
71     if (!sm) {
72         return nullptr;
73     }
74 
75     sp<IBinder> voldBinder(sm->getService(String16("vold")));
76     if (voldBinder == nullptr) {
77         return nullptr;
78     }
79     sp<IVold> vold = interface_cast<IVold>(voldBinder);
80     if (!incFsValid(vold)) {
81         return nullptr;
82     }
83 
84     sp<BinderIncrementalService> self(new BinderIncrementalService(sm, env));
85     status_t ret = sm->addService(String16{getServiceName()}, self);
86     if (ret != android::OK) {
87         return nullptr;
88     }
89     sp<ProcessState> ps(ProcessState::self());
90     ps->startThreadPool();
91     // sm->addService increments the reference count, and now we're OK with returning the pointer.
92     return self.get();
93 }
94 
dump(int fd,const Vector<String16> &)95 status_t BinderIncrementalService::dump(int fd, const Vector<String16>&) {
96     static const android::base::NoDestructor<String16> kDump("android.permission.DUMP");
97     if (!PermissionCache::checkCallingPermission(*kDump)) {
98         return PERMISSION_DENIED;
99     }
100     mImpl.onDump(fd);
101     return NO_ERROR;
102 }
103 
onSystemReady()104 void BinderIncrementalService::onSystemReady() {
105     mImpl.onSystemReady();
106 }
107 
ok()108 static binder::Status ok() {
109     return binder::Status::ok();
110 }
111 
openStorage(const std::string & path,int32_t * _aidl_return)112 binder::Status BinderIncrementalService::openStorage(const std::string& path,
113                                                      int32_t* _aidl_return) {
114     *_aidl_return = mImpl.openStorage(path);
115     return ok();
116 }
117 
createStorage(const::std::string & path,const::android::content::pm::DataLoaderParamsParcel & params,int32_t createMode,int32_t * _aidl_return)118 binder::Status BinderIncrementalService::createStorage(
119         const ::std::string& path, const ::android::content::pm::DataLoaderParamsParcel& params,
120         int32_t createMode, int32_t* _aidl_return) {
121     *_aidl_return =
122             mImpl.createStorage(path, const_cast<content::pm::DataLoaderParamsParcel&&>(params),
123                                 android::incremental::IncrementalService::CreateOptions(
124                                         createMode));
125     return ok();
126 }
127 
createLinkedStorage(const std::string & path,int32_t otherStorageId,int32_t createMode,int32_t * _aidl_return)128 binder::Status BinderIncrementalService::createLinkedStorage(const std::string& path,
129                                                              int32_t otherStorageId,
130                                                              int32_t createMode,
131                                                              int32_t* _aidl_return) {
132     *_aidl_return =
133             mImpl.createLinkedStorage(path, otherStorageId,
134                                       android::incremental::IncrementalService::CreateOptions(
135                                               createMode));
136     return ok();
137 }
138 
startLoading(int32_t storageId,const::android::content::pm::DataLoaderParamsParcel & params,const::android::sp<::android::content::pm::IDataLoaderStatusListener> & statusListener,const::android::os::incremental::StorageHealthCheckParams & healthCheckParams,const::android::sp<IStorageHealthListener> & healthListener,const::std::vector<::android::os::incremental::PerUidReadTimeouts> & perUidReadTimeouts,bool * _aidl_return)139 binder::Status BinderIncrementalService::startLoading(
140         int32_t storageId, const ::android::content::pm::DataLoaderParamsParcel& params,
141         const ::android::sp<::android::content::pm::IDataLoaderStatusListener>& statusListener,
142         const ::android::os::incremental::StorageHealthCheckParams& healthCheckParams,
143         const ::android::sp<IStorageHealthListener>& healthListener,
144         const ::std::vector<::android::os::incremental::PerUidReadTimeouts>& perUidReadTimeouts,
145         bool* _aidl_return) {
146     *_aidl_return =
147             mImpl.startLoading(storageId, const_cast<content::pm::DataLoaderParamsParcel&&>(params),
148                                statusListener, healthCheckParams, healthListener,
149                                perUidReadTimeouts);
150     return ok();
151 }
152 
onInstallationComplete(int32_t storageId)153 binder::Status BinderIncrementalService::onInstallationComplete(int32_t storageId) {
154     mImpl.onInstallationComplete(storageId);
155     return ok();
156 }
157 
makeBindMount(int32_t storageId,const std::string & sourcePath,const std::string & targetFullPath,int32_t bindType,int32_t * _aidl_return)158 binder::Status BinderIncrementalService::makeBindMount(int32_t storageId,
159                                                        const std::string& sourcePath,
160                                                        const std::string& targetFullPath,
161                                                        int32_t bindType, int32_t* _aidl_return) {
162     *_aidl_return = mImpl.bind(storageId, sourcePath, targetFullPath,
163                                android::incremental::IncrementalService::BindKind(bindType));
164     return ok();
165 }
166 
deleteBindMount(int32_t storageId,const std::string & targetFullPath,int32_t * _aidl_return)167 binder::Status BinderIncrementalService::deleteBindMount(int32_t storageId,
168                                                          const std::string& targetFullPath,
169                                                          int32_t* _aidl_return) {
170     *_aidl_return = mImpl.unbind(storageId, targetFullPath);
171     return ok();
172 }
173 
deleteStorage(int32_t storageId)174 binder::Status BinderIncrementalService::deleteStorage(int32_t storageId) {
175     mImpl.deleteStorage(storageId);
176     return ok();
177 }
178 
disallowReadLogs(int32_t storageId)179 binder::Status BinderIncrementalService::disallowReadLogs(int32_t storageId) {
180     mImpl.disallowReadLogs(storageId);
181     return ok();
182 }
183 
makeDirectory(int32_t storageId,const std::string & path,int32_t * _aidl_return)184 binder::Status BinderIncrementalService::makeDirectory(int32_t storageId, const std::string& path,
185                                                        int32_t* _aidl_return) {
186     *_aidl_return = mImpl.makeDir(storageId, path);
187     return ok();
188 }
189 
toMakeFileParams(const android::os::incremental::IncrementalNewFileParams & params)190 static std::tuple<int, incfs::FileId, incfs::NewFileParams> toMakeFileParams(
191         const android::os::incremental::IncrementalNewFileParams& params) {
192     incfs::FileId id;
193     if (params.fileId.empty()) {
194         if (params.metadata.empty()) {
195             return {EINVAL, {}, {}};
196         }
197         id = IncrementalService::idFromMetadata(params.metadata);
198     } else if (params.fileId.size() != sizeof(id)) {
199         return {EINVAL, {}, {}};
200     } else {
201         memcpy(&id, params.fileId.data(), sizeof(id));
202     }
203     incfs::NewFileParams nfp;
204     nfp.size = params.size;
205     nfp.metadata = {(const char*)params.metadata.data(), (IncFsSize)params.metadata.size()};
206     if (!params.signature) {
207         nfp.signature = {};
208     } else {
209         nfp.signature = {(const char*)params.signature->data(),
210                          (IncFsSize)params.signature->size()};
211     }
212     return {0, id, nfp};
213 }
214 
toSpan(const::std::optional<::std::vector<uint8_t>> & content)215 static std::span<const uint8_t> toSpan(const ::std::optional<::std::vector<uint8_t>>& content) {
216     if (!content) {
217         return {};
218     }
219     // TODO(b/175635923): Replace with {content->data(), content->size()} after libc++ is upgraded.
220     // The type of the second std::span ctor param changed from ptrdiff_t to size_t between the old
221     // libc++ and the finalized C++20.
222     return std::span<const uint8_t>(content->data(), content->size());
223 }
224 
makeFile(int32_t storageId,const std::string & path,int32_t mode,const::android::os::incremental::IncrementalNewFileParams & params,const::std::optional<::std::vector<uint8_t>> & content,int32_t * _aidl_return)225 binder::Status BinderIncrementalService::makeFile(
226         int32_t storageId, const std::string& path, int32_t mode,
227         const ::android::os::incremental::IncrementalNewFileParams& params,
228         const ::std::optional<::std::vector<uint8_t>>& content, int32_t* _aidl_return) {
229     auto [err, fileId, nfp] = toMakeFileParams(params);
230     if (err) {
231         *_aidl_return = err;
232         return ok();
233     }
234 
235     *_aidl_return = mImpl.makeFile(storageId, path, mode, fileId, nfp, toSpan(content));
236     return ok();
237 }
makeFileFromRange(int32_t storageId,const std::string & targetPath,const std::string & sourcePath,int64_t start,int64_t end,int32_t * _aidl_return)238 binder::Status BinderIncrementalService::makeFileFromRange(int32_t storageId,
239                                                            const std::string& targetPath,
240                                                            const std::string& sourcePath,
241                                                            int64_t start, int64_t end,
242                                                            int32_t* _aidl_return) {
243     // TODO(b/136132412): implement this
244     *_aidl_return = ENOSYS; // not implemented
245     return ok();
246 }
247 
makeLink(int32_t sourceStorageId,const std::string & sourcePath,int32_t destStorageId,const std::string & destPath,int32_t * _aidl_return)248 binder::Status BinderIncrementalService::makeLink(int32_t sourceStorageId,
249                                                   const std::string& sourcePath,
250                                                   int32_t destStorageId,
251                                                   const std::string& destPath,
252                                                   int32_t* _aidl_return) {
253     *_aidl_return = mImpl.link(sourceStorageId, sourcePath, destStorageId, destPath);
254     return ok();
255 }
256 
unlink(int32_t storageId,const std::string & path,int32_t * _aidl_return)257 binder::Status BinderIncrementalService::unlink(int32_t storageId, const std::string& path,
258                                                 int32_t* _aidl_return) {
259     *_aidl_return = mImpl.unlink(storageId, path);
260     return ok();
261 }
262 
isFileFullyLoaded(int32_t storageId,const std::string & path,int32_t * _aidl_return)263 binder::Status BinderIncrementalService::isFileFullyLoaded(int32_t storageId,
264                                                            const std::string& path,
265                                                            int32_t* _aidl_return) {
266     *_aidl_return = (int)mImpl.isFileFullyLoaded(storageId, path);
267     return ok();
268 }
269 
isFullyLoaded(int32_t storageId,int32_t * _aidl_return)270 binder::Status BinderIncrementalService::isFullyLoaded(int32_t storageId, int32_t* _aidl_return) {
271     *_aidl_return = (int)mImpl.isMountFullyLoaded(storageId);
272     return ok();
273 }
274 
getLoadingProgress(int32_t storageId,float * _aidl_return)275 binder::Status BinderIncrementalService::getLoadingProgress(int32_t storageId,
276                                                             float* _aidl_return) {
277     *_aidl_return = mImpl.getLoadingProgress(storageId).getProgress();
278     return ok();
279 }
280 
getMetadataByPath(int32_t storageId,const std::string & path,std::vector<uint8_t> * _aidl_return)281 binder::Status BinderIncrementalService::getMetadataByPath(int32_t storageId,
282                                                            const std::string& path,
283                                                            std::vector<uint8_t>* _aidl_return) {
284     auto metadata = mImpl.getMetadata(storageId, path);
285     _aidl_return->assign(metadata.begin(), metadata.end());
286     return ok();
287 }
288 
toFileId(const std::vector<uint8_t> & id)289 static FileId toFileId(const std::vector<uint8_t>& id) {
290     FileId fid = {};
291     memcpy(&fid, id.data(), std::min(sizeof(fid), id.size()));
292     return fid;
293 }
294 
getMetadataById(int32_t storageId,const std::vector<uint8_t> & id,std::vector<uint8_t> * _aidl_return)295 binder::Status BinderIncrementalService::getMetadataById(int32_t storageId,
296                                                          const std::vector<uint8_t>& id,
297                                                          std::vector<uint8_t>* _aidl_return) {
298     if (id.size() != sizeof(incfs::FileId)) {
299         return ok();
300     }
301     auto fid = toFileId(id);
302     auto metadata = mImpl.getMetadata(storageId, fid);
303     _aidl_return->assign(metadata.begin(), metadata.end());
304     return ok();
305 }
306 
makeDirectories(int32_t storageId,const std::string & path,int32_t * _aidl_return)307 binder::Status BinderIncrementalService::makeDirectories(int32_t storageId, const std::string& path,
308                                                          int32_t* _aidl_return) {
309     *_aidl_return = mImpl.makeDirs(storageId, path);
310     return ok();
311 }
312 
configureNativeBinaries(int32_t storageId,const std::string & apkFullPath,const std::string & libDirRelativePath,const std::string & abi,bool extractNativeLibs,bool * _aidl_return)313 binder::Status BinderIncrementalService::configureNativeBinaries(
314         int32_t storageId, const std::string& apkFullPath, const std::string& libDirRelativePath,
315         const std::string& abi, bool extractNativeLibs, bool* _aidl_return) {
316     *_aidl_return = mImpl.configureNativeBinaries(storageId, apkFullPath, libDirRelativePath, abi,
317                                                   extractNativeLibs);
318     return ok();
319 }
320 
waitForNativeBinariesExtraction(int storageId,bool * _aidl_return)321 binder::Status BinderIncrementalService::waitForNativeBinariesExtraction(int storageId,
322                                                                          bool* _aidl_return) {
323     *_aidl_return = mImpl.waitForNativeBinariesExtraction(storageId);
324     return ok();
325 }
326 
registerLoadingProgressListener(int32_t storageId,const::android::sp<::android::os::incremental::IStorageLoadingProgressListener> & progressListener,bool * _aidl_return)327 binder::Status BinderIncrementalService::registerLoadingProgressListener(
328         int32_t storageId,
329         const ::android::sp<::android::os::incremental::IStorageLoadingProgressListener>&
330                 progressListener,
331         bool* _aidl_return) {
332     *_aidl_return = mImpl.registerLoadingProgressListener(storageId, progressListener);
333     return ok();
334 }
unregisterLoadingProgressListener(int32_t storageId,bool * _aidl_return)335 binder::Status BinderIncrementalService::unregisterLoadingProgressListener(int32_t storageId,
336                                                                            bool* _aidl_return) {
337     *_aidl_return = mImpl.unregisterLoadingProgressListener(storageId);
338     return ok();
339 }
340 
getMetrics(int32_t storageId,android::os::PersistableBundle * _aidl_return)341 binder::Status BinderIncrementalService::getMetrics(int32_t storageId,
342                                                     android::os::PersistableBundle* _aidl_return) {
343     mImpl.getMetrics(storageId, _aidl_return);
344     return ok();
345 }
346 
347 } // namespace android::os::incremental
348 
Incremental_IncrementalService_Start(JNIEnv * env)349 jlong Incremental_IncrementalService_Start(JNIEnv* env) {
350     return (jlong)android::os::incremental::BinderIncrementalService::start(env);
351 }
Incremental_IncrementalService_OnSystemReady(jlong self)352 void Incremental_IncrementalService_OnSystemReady(jlong self) {
353     if (self) {
354         ((android::os::incremental::BinderIncrementalService*)self)->onSystemReady();
355     }
356 }
Incremental_IncrementalService_OnDump(jlong self,jint fd)357 void Incremental_IncrementalService_OnDump(jlong self, jint fd) {
358     if (self) {
359         ((android::os::incremental::BinderIncrementalService*)self)->dump(fd, {});
360     } else {
361         dprintf(fd, "BinderIncrementalService is stopped.");
362     }
363 }
364