xref: /aosp_15_r20/frameworks/base/cmds/idmap2/idmap2d/Idmap2Service.cpp (revision d57664e9bc4670b3ecf6748a746a57c557b6bc9e)
1 /*
2  * Copyright (C) 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "idmap2d/Idmap2Service.h"
18 
19 #include <sys/stat.h>   // umask
20 #include <sys/types.h>  // umask
21 
22 #include <cerrno>
23 #include <cstring>
24 #include <filesystem>
25 #include <fstream>
26 #include <limits>
27 #include <memory>
28 #include <ostream>
29 #include <string>
30 #include <utility>
31 #include <vector>
32 
33 #include "android-base/macros.h"
34 #include "android-base/stringprintf.h"
35 #include "binder/IPCThreadState.h"
36 #include "idmap2/BinaryStreamVisitor.h"
37 #include "idmap2/FileUtils.h"
38 #include "idmap2/Idmap.h"
39 #include "idmap2/PrettyPrintVisitor.h"
40 #include "idmap2/Result.h"
41 #include "idmap2/SysTrace.h"
42 #include <fcntl.h>
43 
44 using android::base::StringPrintf;
45 using android::binder::Status;
46 using android::idmap2::BinaryStreamVisitor;
47 using android::idmap2::FabricatedOverlayContainer;
48 using android::idmap2::Idmap;
49 using android::idmap2::IdmapHeader;
50 using android::idmap2::OverlayResourceContainer;
51 using android::idmap2::PrettyPrintVisitor;
52 using android::idmap2::TargetResourceContainer;
53 using android::idmap2::utils::kIdmapCacheDir;
54 using android::idmap2::utils::kIdmapFilePermissionMask;
55 using android::idmap2::utils::RandomStringForPath;
56 using android::idmap2::utils::UidHasWriteAccessToPath;
57 
58 using PolicyBitmask = android::ResTable_overlayable_policy_header::PolicyBitmask;
59 
60 namespace {
61 
62 constexpr std::string_view kFrameworkPath = "/system/framework/framework-res.apk";
63 
ok()64 Status ok() {
65   return Status::ok();
66 }
67 
error(const std::string & msg)68 Status error(const std::string& msg) {
69   LOG(ERROR) << msg;
70   return Status::fromExceptionCode(Status::EX_NONE, msg.c_str());
71 }
72 
ConvertAidlArgToPolicyBitmask(int32_t arg)73 PolicyBitmask ConvertAidlArgToPolicyBitmask(int32_t arg) {
74   return static_cast<PolicyBitmask>(arg);
75 }
76 
77 }  // namespace
78 
79 namespace android::os {
80 
81 template <typename T>
GetPointer(const OwningPtr<T> & ptr)82 const T* Idmap2Service::GetPointer(const OwningPtr<T>& ptr) {
83     return std::visit([](auto&& ptr) { return ptr.get(); }, ptr);
84 }
85 
getIdmapPath(const std::string & overlay_path,int32_t user_id ATTRIBUTE_UNUSED,std::string * _aidl_return)86 Status Idmap2Service::getIdmapPath(const std::string& overlay_path,
87                                    int32_t user_id ATTRIBUTE_UNUSED, std::string* _aidl_return) {
88   assert(_aidl_return);
89   SYSTRACE << "Idmap2Service::getIdmapPath " << overlay_path;
90   *_aidl_return = Idmap::CanonicalIdmapPathFor(kIdmapCacheDir, overlay_path);
91   return ok();
92 }
93 
removeIdmap(const std::string & overlay_path,int32_t user_id ATTRIBUTE_UNUSED,bool * _aidl_return)94 Status Idmap2Service::removeIdmap(const std::string& overlay_path, int32_t user_id ATTRIBUTE_UNUSED,
95                                   bool* _aidl_return) {
96   assert(_aidl_return);
97   SYSTRACE << "Idmap2Service::removeIdmap " << overlay_path;
98   const uid_t uid = IPCThreadState::self()->getCallingUid();
99   const std::string idmap_path = Idmap::CanonicalIdmapPathFor(kIdmapCacheDir, overlay_path);
100   if (!UidHasWriteAccessToPath(uid, idmap_path)) {
101     *_aidl_return = false;
102     return error(base::StringPrintf("failed to unlink %s: calling uid %d lacks write access",
103                                     idmap_path.c_str(), uid));
104   }
105   if (unlink(idmap_path.c_str()) != 0) {
106     *_aidl_return = false;
107     return error("failed to unlink " + idmap_path + ": " + strerror(errno));
108   }
109   *_aidl_return = true;
110   return ok();
111 }
112 
verifyIdmap(const std::string & target_path,const std::string & overlay_path,const std::string & overlay_name,int32_t fulfilled_policies,bool enforce_overlayable,int32_t user_id ATTRIBUTE_UNUSED,bool * _aidl_return)113 Status Idmap2Service::verifyIdmap(const std::string& target_path, const std::string& overlay_path,
114                                   const std::string& overlay_name, int32_t fulfilled_policies,
115                                   bool enforce_overlayable, int32_t user_id ATTRIBUTE_UNUSED,
116                                   bool* _aidl_return) {
117   SYSTRACE << "Idmap2Service::verifyIdmap " << overlay_path;
118   assert(_aidl_return);
119 
120   const std::string idmap_path = Idmap::CanonicalIdmapPathFor(kIdmapCacheDir, overlay_path);
121   std::ifstream fin(idmap_path);
122   const std::unique_ptr<const IdmapHeader> header = IdmapHeader::FromBinaryStream(fin);
123   fin.close();
124   if (!header) {
125     *_aidl_return = false;
126     LOG(WARNING) << "failed to parse idmap header of '" << idmap_path << "'";
127     return ok();
128   }
129 
130   const auto target = GetTargetContainer(target_path);
131   if (!target) {
132     *_aidl_return = false;
133     LOG(WARNING) << "failed to load target '" << target_path << "'";
134     return ok();
135   }
136 
137   const auto overlay = OverlayResourceContainer::FromPath(overlay_path);
138   if (!overlay) {
139     *_aidl_return = false;
140     LOG(WARNING) << "failed to load overlay '" << overlay_path << "'";
141     return ok();
142   }
143 
144   auto up_to_date =
145       header->IsUpToDate(*GetPointer(*target), **overlay, overlay_name,
146                          ConvertAidlArgToPolicyBitmask(fulfilled_policies), enforce_overlayable);
147 
148   *_aidl_return = static_cast<bool>(up_to_date);
149   if (!up_to_date) {
150     LOG(WARNING) << "idmap '" << idmap_path
151                  << "' not up to date : " << up_to_date.GetErrorMessage();
152   }
153   return ok();
154 }
155 
createIdmap(const std::string & target_path,const std::string & overlay_path,const std::string & overlay_name,int32_t fulfilled_policies,bool enforce_overlayable,int32_t user_id ATTRIBUTE_UNUSED,std::optional<std::string> * _aidl_return)156 Status Idmap2Service::createIdmap(const std::string& target_path, const std::string& overlay_path,
157                                   const std::string& overlay_name, int32_t fulfilled_policies,
158                                   bool enforce_overlayable, int32_t user_id ATTRIBUTE_UNUSED,
159                                   std::optional<std::string>* _aidl_return) {
160   assert(_aidl_return);
161   SYSTRACE << "Idmap2Service::createIdmap " << target_path << " " << overlay_path;
162   _aidl_return->reset();
163 
164   const PolicyBitmask policy_bitmask = ConvertAidlArgToPolicyBitmask(fulfilled_policies);
165 
166   const std::string idmap_path = Idmap::CanonicalIdmapPathFor(kIdmapCacheDir, overlay_path);
167   const uid_t uid = IPCThreadState::self()->getCallingUid();
168   if (!UidHasWriteAccessToPath(uid, idmap_path)) {
169     return error(base::StringPrintf("will not write to %s: calling uid %d lacks write accesss",
170                                     idmap_path.c_str(), uid));
171   }
172 
173   // idmap files are mapped with mmap in libandroidfw. Deleting and recreating the idmap guarantees
174   // that existing memory maps will continue to be valid and unaffected. The file must be deleted
175   // before attempting to create the idmap, so that if idmap  creation fails, the overlay will no
176   // longer be usable.
177   unlink(idmap_path.c_str());
178 
179   const auto target = GetTargetContainer(target_path);
180   if (!target) {
181     return error("failed to load target '%s'" + target_path);
182   }
183 
184   const auto overlay = OverlayResourceContainer::FromPath(overlay_path);
185   if (!overlay) {
186     return error("failed to load apk overlay '%s'" + overlay_path);
187   }
188 
189   const auto idmap = Idmap::FromContainers(*GetPointer(*target), **overlay, overlay_name,
190                                            policy_bitmask, enforce_overlayable);
191   if (!idmap) {
192     return error(idmap.GetErrorMessage());
193   }
194 
195   umask(kIdmapFilePermissionMask);
196   std::ofstream fout(idmap_path);
197   if (fout.fail()) {
198     return error("failed to open idmap path " + idmap_path);
199   }
200 
201   BinaryStreamVisitor visitor(fout);
202   (*idmap)->accept(&visitor);
203   fout.close();
204   if (fout.fail()) {
205     unlink(idmap_path.c_str());
206     return error("failed to write to idmap path " + idmap_path);
207   }
208 
209   *_aidl_return = idmap_path;
210   return ok();
211 }
212 
GetTargetContainer(const std::string & target_path)213 idmap2::Result<Idmap2Service::TargetResourceContainerPtr> Idmap2Service::GetTargetContainer(
214     const std::string& target_path) {
215   const bool is_framework = target_path == kFrameworkPath;
216   bool use_cache;
217   struct stat st = {};
218   if (is_framework || !::stat(target_path.c_str(), &st)) {
219     use_cache = true;
220   } else {
221     LOG(WARNING) << "failed to stat target path '" << target_path << "' for the cache";
222     use_cache = false;
223   }
224 
225   if (use_cache) {
226     std::lock_guard lock(container_cache_mutex_);
227     if (auto cache_it = container_cache_.find(target_path); cache_it != container_cache_.end()) {
228       const auto& item = cache_it->second;
229       if (is_framework ||
230         (item.dev == st.st_dev && item.inode == st.st_ino && item.size == st.st_size
231           && item.mtime.tv_sec == st.st_mtim.tv_sec && item.mtime.tv_nsec == st.st_mtim.tv_nsec)) {
232         return {item.apk};
233       }
234       container_cache_.erase(cache_it);
235     }
236   }
237 
238   auto target = TargetResourceContainer::FromPath(target_path);
239   if (!target) {
240     return target.GetError();
241   }
242   if (!use_cache) {
243     return {std::move(*target)};
244   }
245 
246   auto res = std::shared_ptr(std::move(*target));
247   std::lock_guard lock(container_cache_mutex_);
248   container_cache_.emplace(target_path, CachedContainer {
249     .dev = dev_t(st.st_dev),
250     .inode = ino_t(st.st_ino),
251     .size = st.st_size,
252     .mtime = st.st_mtim,
253     .apk = res
254   });
255   return {res};
256 }
257 
createFabricatedOverlay(const os::FabricatedOverlayInternal & overlay,std::optional<os::FabricatedOverlayInfo> * _aidl_return)258 Status Idmap2Service::createFabricatedOverlay(
259     const os::FabricatedOverlayInternal& overlay,
260     std::optional<os::FabricatedOverlayInfo>* _aidl_return) {
261   idmap2::FabricatedOverlay::Builder builder(overlay.packageName, overlay.overlayName,
262                                              overlay.targetPackageName);
263   if (!overlay.targetOverlayable.empty()) {
264     builder.SetOverlayable(overlay.targetOverlayable);
265   }
266 
267   for (const auto& res : overlay.entries) {
268     if (res.dataType == Res_value::TYPE_STRING) {
269       builder.SetResourceValue(res.resourceName, res.dataType, res.stringData.value(),
270             res.configuration.value_or(std::string()));
271     } else if (res.binaryData.has_value()) {
272       builder.SetResourceValue(res.resourceName, res.binaryData->get(),
273                                res.binaryDataOffset, res.binaryDataSize,
274                                res.configuration.value_or(std::string()),
275                                res.isNinePatch);
276     } else {
277       builder.SetResourceValue(res.resourceName, res.dataType, res.data,
278             res.configuration.value_or(std::string()));
279     }
280   }
281 
282   // Generate the file path of the fabricated overlay and ensure it does not collide with an
283   // existing path. Re-registering a fabricated overlay will always result in an updated path.
284   std::string path;
285   std::string file_name;
286   do {
287     constexpr size_t kSuffixLength = 4;
288     const std::string random_suffix = RandomStringForPath(kSuffixLength);
289     file_name = StringPrintf("%s-%s-%s.frro", overlay.packageName.c_str(),
290                              overlay.overlayName.c_str(), random_suffix.c_str());
291     path = StringPrintf("%s/%s", kIdmapCacheDir.data(), file_name.c_str());
292 
293     // Invoking std::filesystem::exists with a file name greater than 255 characters will cause this
294     // process to abort since the name exceeds the maximum file name size.
295     const size_t kMaxFileNameLength = 255;
296     if (file_name.size() > kMaxFileNameLength) {
297       return error(
298           base::StringPrintf("fabricated overlay file name '%s' longer than %zu characters",
299                              file_name.c_str(), kMaxFileNameLength));
300     }
301   } while (std::filesystem::exists(path));
302   builder.setFrroPath(path);
303 
304   const uid_t uid = IPCThreadState::self()->getCallingUid();
305   if (!UidHasWriteAccessToPath(uid, path)) {
306     return error(base::StringPrintf("will not write to %s: calling uid %d lacks write access",
307                                     path.c_str(), uid));
308   }
309 
310   const auto frro = builder.Build();
311   if (!frro) {
312     return error(StringPrintf("failed to serialize '%s:%s': %s", overlay.packageName.c_str(),
313                               overlay.overlayName.c_str(), frro.GetErrorMessage().c_str()));
314   }
315   // Persist the fabricated overlay.
316   umask(kIdmapFilePermissionMask);
317   std::ofstream fout(path);
318   if (fout.fail()) {
319     return error("failed to open frro path " + path);
320   }
321   auto result = frro->ToBinaryStream(fout);
322   if (!result) {
323     unlink(path.c_str());
324     return error("failed to write to frro path " + path + ": " + result.GetErrorMessage());
325   }
326   if (fout.fail()) {
327     unlink(path.c_str());
328     return error("failed to write to frro path " + path);
329   }
330 
331   os::FabricatedOverlayInfo out_info;
332   out_info.packageName = overlay.packageName;
333   out_info.overlayName = overlay.overlayName;
334   out_info.targetPackageName = overlay.targetPackageName;
335   out_info.targetOverlayable = overlay.targetOverlayable;
336   out_info.path = path;
337   *_aidl_return = out_info;
338   return ok();
339 }
340 
acquireFabricatedOverlayIterator(int32_t * _aidl_return)341 Status Idmap2Service::acquireFabricatedOverlayIterator(int32_t* _aidl_return) {
342   std::lock_guard l(frro_iter_mutex_);
343   if (frro_iter_.has_value()) {
344     LOG(WARNING) << "active ffro iterator was not previously released";
345   }
346   frro_iter_ = std::filesystem::directory_iterator(kIdmapCacheDir);
347   if (frro_iter_id_ == std::numeric_limits<int32_t>::max()) {
348     frro_iter_id_ = 0;
349   } else {
350     ++frro_iter_id_;
351   }
352   *_aidl_return = frro_iter_id_;
353   return ok();
354 }
355 
releaseFabricatedOverlayIterator(int32_t iteratorId)356 Status Idmap2Service::releaseFabricatedOverlayIterator(int32_t iteratorId) {
357   std::lock_guard l(frro_iter_mutex_);
358   if (!frro_iter_.has_value()) {
359     LOG(WARNING) << "no active ffro iterator to release";
360   } else if (frro_iter_id_ != iteratorId) {
361     LOG(WARNING) << "incorrect iterator id in a call to release";
362   } else {
363     frro_iter_.reset();
364   }
365   return ok();
366 }
367 
nextFabricatedOverlayInfos(int32_t iteratorId,std::vector<os::FabricatedOverlayInfo> * _aidl_return)368 Status Idmap2Service::nextFabricatedOverlayInfos(int32_t iteratorId,
369     std::vector<os::FabricatedOverlayInfo>* _aidl_return) {
370   std::lock_guard l(frro_iter_mutex_);
371 
372   constexpr size_t kMaxEntryCount = 100;
373   if (!frro_iter_.has_value()) {
374     return error("no active frro iterator");
375   } else if (frro_iter_id_ != iteratorId) {
376     return error("incorrect iterator id in a call to next");
377   }
378 
379   size_t count = 0;
380   auto& entry_iter = *frro_iter_;
381   auto entry_iter_end = end(*frro_iter_);
382   for (; entry_iter != entry_iter_end && count < kMaxEntryCount; ++entry_iter) {
383     auto& entry = *entry_iter;
384     if (!entry.is_regular_file() || !android::IsFabricatedOverlay(entry.path().native())) {
385       continue;
386     }
387 
388     const auto overlay = FabricatedOverlayContainer::FromPath(entry.path().native());
389     if (!overlay) {
390       LOG(WARNING) << "Failed to open '" << entry.path() << "': " << overlay.GetErrorMessage();
391       continue;
392     }
393 
394     auto info = (*overlay)->GetManifestInfo();
395     os::FabricatedOverlayInfo out_info;
396     out_info.packageName = std::move(info.package_name);
397     out_info.overlayName = std::move(info.name);
398     out_info.targetPackageName = std::move(info.target_package);
399     out_info.targetOverlayable = std::move(info.target_name);
400     out_info.path = entry.path();
401     _aidl_return->emplace_back(std::move(out_info));
402     count++;
403   }
404   return ok();
405 }
406 
deleteFabricatedOverlay(const std::string & overlay_path,bool * _aidl_return)407 binder::Status Idmap2Service::deleteFabricatedOverlay(const std::string& overlay_path,
408                                                       bool* _aidl_return) {
409   SYSTRACE << "Idmap2Service::deleteFabricatedOverlay " << overlay_path;
410   const uid_t uid = IPCThreadState::self()->getCallingUid();
411 
412   if (!UidHasWriteAccessToPath(uid, overlay_path)) {
413     *_aidl_return = false;
414     return error(base::StringPrintf("failed to unlink %s: calling uid %d lacks write access",
415                                     overlay_path.c_str(), uid));
416   }
417 
418   const std::string idmap_path = Idmap::CanonicalIdmapPathFor(kIdmapCacheDir, overlay_path);
419   if (!UidHasWriteAccessToPath(uid, idmap_path)) {
420     *_aidl_return = false;
421     return error(base::StringPrintf("failed to unlink %s: calling uid %d lacks write access",
422                                     idmap_path.c_str(), uid));
423   }
424 
425   if (unlink(overlay_path.c_str()) != 0) {
426     *_aidl_return = false;
427     return error("failed to unlink " + overlay_path + ": " + strerror(errno));
428   }
429 
430   if (unlink(idmap_path.c_str()) != 0) {
431     *_aidl_return = false;
432     return error("failed to unlink " + idmap_path + ": " + strerror(errno));
433   }
434 
435   *_aidl_return = true;
436   return ok();
437 }
438 
dumpIdmap(const std::string & overlay_path,std::string * _aidl_return)439 binder::Status Idmap2Service::dumpIdmap(const std::string& overlay_path,
440                                         std::string* _aidl_return) {
441   assert(_aidl_return);
442 
443   const auto idmap_path = Idmap::CanonicalIdmapPathFor(kIdmapCacheDir, overlay_path);
444   std::ifstream fin(idmap_path);
445   const auto idmap = Idmap::FromBinaryStream(fin);
446   fin.close();
447   if (!idmap) {
448     return error(idmap.GetErrorMessage());
449   }
450 
451   std::stringstream stream;
452   PrettyPrintVisitor visitor(stream);
453   (*idmap)->accept(&visitor);
454   *_aidl_return = stream.str();
455 
456   return ok();
457 }
458 
459 }  // namespace android::os
460