blob: 4de1e20305e908e52ce09bd21b8851827892e605 [file] [log] [blame]
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001/*
Tom Cherryed506f72017-05-25 15:58:59 -07002 * Copyright (C) 2007 The Android Open Source Project
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07003 *
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
Tom Cherrycc054c92017-04-05 17:55:46 -070017#include "devices.h"
18
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070019#include <errno.h>
Daniel Leungc0c1ffe2012-07-02 11:32:30 -070020#include <fnmatch.h>
Elliott Hughes51056c42017-05-18 09:13:15 -070021#include <sys/sysmacros.h>
Elliott Hughesf39f7f12016-08-31 14:41:51 -070022#include <unistd.h>
23
Mark Salyzyne419a792019-03-06 15:18:46 -080024#include <chrono>
David Anderson515a5bd2020-10-19 19:54:18 -070025#include <filesystem>
James Hawkins588a2ca2016-02-18 14:52:46 -080026#include <memory>
Mark Salyzyne419a792019-03-06 15:18:46 -080027#include <string>
Bart Van Assche564d9702024-05-22 13:07:13 -070028#include <string_view>
Mark Salyzyne419a792019-03-06 15:18:46 -080029#include <thread>
James Hawkins588a2ca2016-02-18 14:52:46 -080030
Mark Salyzyne419a792019-03-06 15:18:46 -080031#include <android-base/chrono_utils.h>
32#include <android-base/file.h>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070033#include <android-base/logging.h>
Rob Herring6de783a2016-05-06 10:06:59 -050034#include <android-base/stringprintf.h>
Tom Cherry2e344f92017-04-04 17:53:45 -070035#include <android-base/strings.h>
Yi-Yo Chiang79ad1e22023-07-29 17:37:23 +080036#include <fs_mgr.h>
David Anderson59abbfe2023-05-16 15:53:57 -070037#include <libdm/dm.h>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070038#include <private/android_filesystem_config.h>
39#include <selinux/android.h>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070040#include <selinux/selinux.h>
Vernon Tang3f582e92011-04-25 13:08:17 +100041
Vic Yang92c236e2019-05-28 15:58:35 -070042#include "selabel.h"
Colin Crossb0ab94b2010-04-08 16:16:20 -070043#include "util.h"
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070044
Mark Salyzyne419a792019-03-06 15:18:46 -080045using namespace std::chrono_literals;
46
Tom Cherry81f5d3e2017-06-22 12:53:17 -070047using android::base::Basename;
Douglas Anderson743e8f12024-11-06 09:24:50 -080048using android::base::ConsumePrefix;
Tom Cherry81f5d3e2017-06-22 12:53:17 -070049using android::base::Dirname;
Mark Salyzyne419a792019-03-06 15:18:46 -080050using android::base::ReadFileToString;
Tom Cherry81f5d3e2017-06-22 12:53:17 -070051using android::base::Readlink;
52using android::base::Realpath;
Tom Cherry96e5f9b2021-07-30 09:54:36 -070053using android::base::Split;
Tom Cherry81f5d3e2017-06-22 12:53:17 -070054using android::base::StartsWith;
55using android::base::StringPrintf;
Mark Salyzyne419a792019-03-06 15:18:46 -080056using android::base::Trim;
Tom Cherry81f5d3e2017-06-22 12:53:17 -070057
58namespace android {
59namespace init {
60
Andrew Boiea885d042013-09-13 17:41:20 -070061/* Given a path that may start with a PCI device, populate the supplied buffer
62 * with the PCI domain/bus number and the peripheral ID and return 0.
63 * If it doesn't start with a PCI device, or there is some error, return -1 */
Tom Cherryed506f72017-05-25 15:58:59 -070064static bool FindPciDevicePrefix(const std::string& path, std::string* result) {
Tom Cherry2e344f92017-04-04 17:53:45 -070065 result->clear();
Andrew Boiea885d042013-09-13 17:41:20 -070066
Tom Cherry81f5d3e2017-06-22 12:53:17 -070067 if (!StartsWith(path, "/devices/pci")) return false;
Andrew Boiea885d042013-09-13 17:41:20 -070068
69 /* Beginning of the prefix is the initial "pci" after "/devices/" */
Tom Cherry2e344f92017-04-04 17:53:45 -070070 std::string::size_type start = 9;
Andrew Boiea885d042013-09-13 17:41:20 -070071
72 /* End of the prefix is two path '/' later, capturing the domain/bus number
73 * and the peripheral ID. Example: pci0000:00/0000:00:1f.2 */
Tom Cherry2e344f92017-04-04 17:53:45 -070074 auto end = path.find('/', start);
75 if (end == std::string::npos) return false;
Andrew Boiea885d042013-09-13 17:41:20 -070076
Tom Cherry2e344f92017-04-04 17:53:45 -070077 end = path.find('/', end + 1);
78 if (end == std::string::npos) return false;
Andrew Boiea885d042013-09-13 17:41:20 -070079
Tom Cherry2e344f92017-04-04 17:53:45 -070080 auto length = end - start;
81 if (length <= 4) {
82 // The minimum string that will get to this check is 'pci/', which is malformed,
83 // so return false
84 return false;
85 }
86
87 *result = path.substr(start, length);
88 return true;
Andrew Boiea885d042013-09-13 17:41:20 -070089}
90
Jeremy Compostella937309d2017-03-03 16:27:29 +010091/* Given a path that may start with a virtual block device, populate
92 * the supplied buffer with the virtual block device ID and return 0.
93 * If it doesn't start with a virtual block device, or there is some
94 * error, return -1 */
Tom Cherryed506f72017-05-25 15:58:59 -070095static bool FindVbdDevicePrefix(const std::string& path, std::string* result) {
Tom Cherry2e344f92017-04-04 17:53:45 -070096 result->clear();
97
Tom Cherry81f5d3e2017-06-22 12:53:17 -070098 if (!StartsWith(path, "/devices/vbd-")) return false;
Jeremy Compostella937309d2017-03-03 16:27:29 +010099
100 /* Beginning of the prefix is the initial "vbd-" after "/devices/" */
Tom Cherry2e344f92017-04-04 17:53:45 -0700101 std::string::size_type start = 13;
Jeremy Compostella937309d2017-03-03 16:27:29 +0100102
103 /* End of the prefix is one path '/' later, capturing the
104 virtual block device ID. Example: 768 */
Tom Cherry2e344f92017-04-04 17:53:45 -0700105 auto end = path.find('/', start);
106 if (end == std::string::npos) return false;
Jeremy Compostella937309d2017-03-03 16:27:29 +0100107
Tom Cherry2e344f92017-04-04 17:53:45 -0700108 auto length = end - start;
109 if (length == 0) return false;
Jeremy Compostella937309d2017-03-03 16:27:29 +0100110
Tom Cherry2e344f92017-04-04 17:53:45 -0700111 *result = path.substr(start, length);
112 return true;
Jeremy Compostella937309d2017-03-03 16:27:29 +0100113}
114
Mark Salyzyne419a792019-03-06 15:18:46 -0800115// Given a path that may start with a virtual dm block device, populate
116// the supplied buffer with the dm module's instantiated name.
117// If it doesn't start with a virtual block device, or there is some
118// error, return false.
David Anderson59abbfe2023-05-16 15:53:57 -0700119static bool FindDmDevice(const Uevent& uevent, std::string* name, std::string* uuid) {
120 if (!StartsWith(uevent.path, "/devices/virtual/block/dm-")) return false;
121 if (uevent.action == "remove") return false; // Avoid error spam from ioctl
Mark Salyzyne419a792019-03-06 15:18:46 -0800122
David Anderson59abbfe2023-05-16 15:53:57 -0700123 dev_t dev = makedev(uevent.major, uevent.minor);
David Anderson924858c2019-06-26 17:00:00 -0700124
David Anderson59abbfe2023-05-16 15:53:57 -0700125 auto& dm = android::dm::DeviceMapper::Instance();
126 return dm.GetDeviceNameAndUuid(dev, name, uuid);
Mark Salyzyne419a792019-03-06 15:18:46 -0800127}
128
Tom Cherry47031c82020-12-07 13:33:46 -0800129Permissions::Permissions(const std::string& name, mode_t perm, uid_t uid, gid_t gid,
130 bool no_fnm_pathname)
131 : name_(name),
132 perm_(perm),
133 uid_(uid),
134 gid_(gid),
135 prefix_(false),
136 wildcard_(false),
137 no_fnm_pathname_(no_fnm_pathname) {
Tom Cherryed506f72017-05-25 15:58:59 -0700138 // Set 'prefix_' or 'wildcard_' based on the below cases:
139 //
140 // 1) No '*' in 'name' -> Neither are set and Match() checks a given path for strict
141 // equality with 'name'
142 //
143 // 2) '*' only appears as the last character in 'name' -> 'prefix'_ is set to true and
144 // Match() checks if 'name' is a prefix of a given path.
145 //
146 // 3) '*' appears elsewhere -> 'wildcard_' is set to true and Match() uses fnmatch()
147 // with FNM_PATHNAME to compare 'name' to a given path.
Tom Cherryed506f72017-05-25 15:58:59 -0700148 auto wildcard_position = name_.find('*');
149 if (wildcard_position != std::string::npos) {
150 if (wildcard_position == name_.length() - 1) {
151 prefix_ = true;
152 name_.pop_back();
153 } else {
154 wildcard_ = true;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700155 }
Elliott Hughesc0e919c2015-02-04 14:46:36 -0800156 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700157}
158
Tom Cherryed506f72017-05-25 15:58:59 -0700159bool Permissions::Match(const std::string& path) const {
Elliott Hughes579e6822017-12-20 09:41:00 -0800160 if (prefix_) return StartsWith(path, name_);
Tom Cherry47031c82020-12-07 13:33:46 -0800161 if (wildcard_)
162 return fnmatch(name_.c_str(), path.c_str(), no_fnm_pathname_ ? 0 : FNM_PATHNAME) == 0;
Tom Cherryed506f72017-05-25 15:58:59 -0700163 return path == name_;
164}
165
166bool SysfsPermissions::MatchWithSubsystem(const std::string& path,
167 const std::string& subsystem) const {
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700168 std::string path_basename = Basename(path);
Tom Cherryed506f72017-05-25 15:58:59 -0700169 if (name().find(subsystem) != std::string::npos) {
170 if (Match("/sys/class/" + subsystem + "/" + path_basename)) return true;
171 if (Match("/sys/bus/" + subsystem + "/devices/" + path_basename)) return true;
172 }
173 return Match(path);
174}
175
176void SysfsPermissions::SetPermissions(const std::string& path) const {
177 std::string attribute_file = path + "/" + attribute_;
178 LOG(VERBOSE) << "fixup " << attribute_file << " " << uid() << " " << gid() << " " << std::oct
179 << perm();
180
181 if (access(attribute_file.c_str(), F_OK) == 0) {
182 if (chown(attribute_file.c_str(), uid(), gid()) != 0) {
183 PLOG(ERROR) << "chown(" << attribute_file << ", " << uid() << ", " << gid()
184 << ") failed";
185 }
186 if (chmod(attribute_file.c_str(), perm()) != 0) {
187 PLOG(ERROR) << "chmod(" << attribute_file << ", " << perm() << ") failed";
188 }
189 }
190}
191
Douglas Anderson9481f972024-11-06 09:28:07 -0800192BlockDeviceInfo DeviceHandler::GetBlockDeviceInfo(const std::string& uevent_path) const {
193 BlockDeviceInfo info;
194
Douglas Andersone9de3102024-10-22 14:34:30 -0700195 if (!boot_part_uuid_.empty()) {
196 // Only use the more specific "MMC" or "SCSI" match if a partition UUID
197 // was passed. Old bootloaders that aren't passing the partition UUID
198 // instead pass the path to the closest "platform" device. It would
199 // break them if we chose this deeper (more specific) path.
200 //
201 // When we have a UUID we _want_ the more specific path since it can
202 // handle, for instance, differentiating two USB disks that are on
203 // the same USB controller. Using the closest platform device would
204 // classify them both the same by using the path to the USB controller.
205 if (FindMmcDevice(uevent_path, &info.str)) {
206 info.type = "mmc";
207 } else if (FindScsiDevice(uevent_path, &info.str)) {
208 info.type = "scsi";
209 }
210 } else if (FindPlatformDevice(uevent_path, &info.str)) {
Douglas Anderson9481f972024-11-06 09:28:07 -0800211 info.type = "platform";
212 } else if (FindPciDevicePrefix(uevent_path, &info.str)) {
213 info.type = "pci";
214 } else if (FindVbdDevicePrefix(uevent_path, &info.str)) {
215 info.type = "vbd";
216 } else {
217 // Re-clear device to be extra certain in case one of the FindXXX()
218 // functions returned false but still modified it.
219 info.str = "";
220 }
221
222 info.is_boot_device = boot_devices_.find(info.str) != boot_devices_.end();
223
224 return info;
225}
226
Douglas Andersoneb3d2802024-11-05 09:15:25 -0800227bool DeviceHandler::IsBootDeviceStrict() const {
228 // When using the newer "boot_part_uuid" to specify the boot device then
229 // we require all core system partitions to be on the boot device.
230 return !boot_part_uuid_.empty();
231}
232
233bool DeviceHandler::IsBootDevice(const Uevent& uevent) const {
234 auto device = GetBlockDeviceInfo(uevent.path);
235 return device.is_boot_device;
236}
237
Tom Cherry96e5f9b2021-07-30 09:54:36 -0700238std::string DeviceHandler::GetPartitionNameForDevice(const std::string& query_device) {
239 static const auto partition_map = [] {
240 std::vector<std::pair<std::string, std::string>> partition_map;
241 auto parser = [&partition_map](const std::string& key, const std::string& value) {
242 if (key != "androidboot.partition_map") {
243 return;
244 }
245 for (const auto& map : Split(value, ";")) {
246 auto map_pieces = Split(map, ",");
247 if (map_pieces.size() != 2) {
248 LOG(ERROR) << "Expected a comma separated device,partition mapping, but found '"
249 << map << "'";
250 continue;
251 }
252 partition_map.emplace_back(map_pieces[0], map_pieces[1]);
253 }
254 };
Yi-Yo Chiangda5323e2023-08-02 01:08:23 +0800255 android::fs_mgr::ImportKernelCmdline(parser);
Yi-Yo Chiang79ad1e22023-07-29 17:37:23 +0800256 android::fs_mgr::ImportBootconfig(parser);
Tom Cherry96e5f9b2021-07-30 09:54:36 -0700257 return partition_map;
258 }();
259
260 for (const auto& [device, partition] : partition_map) {
261 if (query_device == device) {
262 return partition;
263 }
264 }
265 return {};
266}
267
Douglas Anderson6519e6d2024-10-22 14:09:26 -0700268// Given a path to a device that may have a parent in the passed set of
269// subsystems, find the parent device that's in the passed set of subsystems.
270// If we don't find a parent in the passed set of subsystems, return false.
271bool DeviceHandler::FindSubsystemDevice(std::string path, std::string* device_path,
272 const std::set<std::string>& subsystem_paths) const {
273 device_path->clear();
Sandeep Patilcd2ba0d2017-06-21 12:46:41 -0700274
275 // Uevents don't contain the mount point, so we need to add it here.
276 path.insert(0, sysfs_mount_point_);
277
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700278 std::string directory = Dirname(path);
Sandeep Patilcd2ba0d2017-06-21 12:46:41 -0700279
280 while (directory != "/" && directory != ".") {
281 std::string subsystem_link_path;
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700282 if (Realpath(directory + "/subsystem", &subsystem_link_path) &&
Douglas Anderson6519e6d2024-10-22 14:09:26 -0700283 subsystem_paths.find(subsystem_link_path) != subsystem_paths.end()) {
Sandeep Patilcd2ba0d2017-06-21 12:46:41 -0700284 // We need to remove the mount point that we added above before returning.
285 directory.erase(0, sysfs_mount_point_.size());
Douglas Anderson3de05fc2024-10-22 14:13:19 -0700286
287 // Skip /devices/platform or /devices/ if present
288 static constexpr std::string_view devices_platform_prefix = "/devices/platform/";
289 static constexpr std::string_view devices_prefix = "/devices/";
290 std::string_view sv = directory;
291
292 if (!ConsumePrefix(&sv, devices_platform_prefix)) {
293 ConsumePrefix(&sv, devices_prefix);
294 }
295 *device_path = sv;
296
Tom Cherryed506f72017-05-25 15:58:59 -0700297 return true;
298 }
Sandeep Patilcd2ba0d2017-06-21 12:46:41 -0700299
300 auto last_slash = path.rfind('/');
301 if (last_slash == std::string::npos) return false;
302
303 path.erase(last_slash);
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700304 directory = Dirname(path);
Tom Cherryed506f72017-05-25 15:58:59 -0700305 }
Sandeep Patilcd2ba0d2017-06-21 12:46:41 -0700306
Tom Cherryed506f72017-05-25 15:58:59 -0700307 return false;
308}
309
Douglas Anderson6519e6d2024-10-22 14:09:26 -0700310bool DeviceHandler::FindPlatformDevice(std::string path, std::string* platform_device_path) const {
311 const std::set<std::string> subsystem_paths = {
312 sysfs_mount_point_ + "/bus/platform",
313 sysfs_mount_point_ + "/bus/amba",
314 };
315
316 return FindSubsystemDevice(path, platform_device_path, subsystem_paths);
317}
318
Douglas Andersone9de3102024-10-22 14:34:30 -0700319bool DeviceHandler::FindMmcDevice(std::string path, std::string* mmc_device_path) const {
320 const std::set<std::string> subsystem_paths = {
321 sysfs_mount_point_ + "/bus/mmc",
322 };
323
324 return FindSubsystemDevice(path, mmc_device_path, subsystem_paths);
325}
326
327bool DeviceHandler::FindScsiDevice(std::string path, std::string* scsi_device_path) const {
328 const std::set<std::string> subsystem_paths = {
329 sysfs_mount_point_ + "/bus/scsi",
330 };
331
332 return FindSubsystemDevice(path, scsi_device_path, subsystem_paths);
333}
334
Tom Cherryed506f72017-05-25 15:58:59 -0700335void DeviceHandler::FixupSysPermissions(const std::string& upath,
336 const std::string& subsystem) const {
337 // upaths omit the "/sys" that paths in this list
338 // contain, so we prepend it...
339 std::string path = "/sys" + upath;
340
341 for (const auto& s : sysfs_permissions_) {
342 if (s.MatchWithSubsystem(path, subsystem)) s.SetPermissions(path);
343 }
344
Tom Cherryc5833052017-05-16 15:35:41 -0700345 if (!skip_restorecon_ && access(path.c_str(), F_OK) == 0) {
Tom Cherryed506f72017-05-25 15:58:59 -0700346 LOG(VERBOSE) << "restorecon_recursive: " << path;
347 if (selinux_android_restorecon(path.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE) != 0) {
348 PLOG(ERROR) << "selinux_android_restorecon(" << path << ") failed";
349 }
350 }
351}
352
353std::tuple<mode_t, uid_t, gid_t> DeviceHandler::GetDevicePermissions(
354 const std::string& path, const std::vector<std::string>& links) const {
355 // Search the perms list in reverse so that ueventd.$hardware can override ueventd.rc.
356 for (auto it = dev_permissions_.crbegin(); it != dev_permissions_.crend(); ++it) {
357 if (it->Match(path) || std::any_of(links.cbegin(), links.cend(),
358 [it](const auto& link) { return it->Match(link); })) {
359 return {it->perm(), it->uid(), it->gid()};
360 }
361 }
362 /* Default if nothing found. */
363 return {0600, 0, 0};
364}
365
Tom Cherryb4dd8812017-06-23 12:43:48 -0700366void DeviceHandler::MakeDevice(const std::string& path, bool block, int major, int minor,
Tom Cherryed506f72017-05-25 15:58:59 -0700367 const std::vector<std::string>& links) const {
Eric Carusobb4a4092024-08-30 13:34:24 -0400368 auto [mode, uid, gid] = GetDevicePermissions(path, links);
Tom Cherryed506f72017-05-25 15:58:59 -0700369 mode |= (block ? S_IFBLK : S_IFCHR);
370
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700371 std::string secontext;
372 if (!SelabelLookupFileContextBestMatch(path, links, mode, &secontext)) {
373 PLOG(ERROR) << "Device '" << path << "' not created; cannot find SELinux label";
374 return;
375 }
376 if (!secontext.empty()) {
377 setfscreatecon(secontext.c_str());
Tom Cherryed506f72017-05-25 15:58:59 -0700378 }
379
David Andersonf8825fa2021-07-02 20:47:27 -0700380 gid_t new_group = -1;
381
Tom Cherryed506f72017-05-25 15:58:59 -0700382 dev_t dev = makedev(major, minor);
383 /* Temporarily change egid to avoid race condition setting the gid of the
384 * device node. Unforunately changing the euid would prevent creation of
385 * some device nodes, so the uid has to be set with chown() and is still
386 * racy. Fixing the gid race at least fixed the issue with system_server
387 * opening dynamic input devices under the AID_INPUT gid. */
388 if (setegid(gid)) {
389 PLOG(ERROR) << "setegid(" << gid << ") for " << path << " device failed";
390 goto out;
391 }
zexin.hou76cba8a2022-04-14 16:08:17 +0800392 /* If the node already exists update its SELinux label and the file mode to handle cases when
393 * it was created with the wrong context and file mode during coldboot procedure. */
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700394 if (mknod(path.c_str(), mode, dev) && (errno == EEXIST) && !secontext.empty()) {
Tom Cherryed506f72017-05-25 15:58:59 -0700395 char* fcon = nullptr;
396 int rc = lgetfilecon(path.c_str(), &fcon);
397 if (rc < 0) {
398 PLOG(ERROR) << "Cannot get SELinux label on '" << path << "' device";
399 goto out;
400 }
401
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700402 bool different = fcon != secontext;
Tom Cherryed506f72017-05-25 15:58:59 -0700403 freecon(fcon);
404
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700405 if (different && lsetfilecon(path.c_str(), secontext.c_str())) {
Tom Cherryed506f72017-05-25 15:58:59 -0700406 PLOG(ERROR) << "Cannot set '" << secontext << "' SELinux label on '" << path
407 << "' device";
408 }
David Andersonf8825fa2021-07-02 20:47:27 -0700409
410 struct stat s;
411 if (stat(path.c_str(), &s) == 0) {
412 if (gid != s.st_gid) {
413 new_group = gid;
414 }
Eric Caruso23276f62024-08-30 10:51:38 -0400415 if (mode != s.st_mode) {
416 if (chmod(path.c_str(), mode) != 0) {
417 PLOG(ERROR) << "Cannot chmod " << path << " to " << mode;
418 }
zexin.hou76cba8a2022-04-14 16:08:17 +0800419 }
David Andersonf8825fa2021-07-02 20:47:27 -0700420 } else {
421 PLOG(ERROR) << "Cannot stat " << path;
422 }
Tom Cherryed506f72017-05-25 15:58:59 -0700423 }
424
425out:
David Andersonf8825fa2021-07-02 20:47:27 -0700426 if (chown(path.c_str(), uid, new_group) < 0) {
427 PLOG(ERROR) << "Cannot chown " << path << " " << uid << " " << new_group;
428 }
Tom Cherryed506f72017-05-25 15:58:59 -0700429 if (setegid(AID_ROOT)) {
430 PLOG(FATAL) << "setegid(AID_ROOT) failed";
431 }
432
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700433 if (!secontext.empty()) {
Tom Cherryed506f72017-05-25 15:58:59 -0700434 setfscreatecon(nullptr);
435 }
436}
437
Tom Cherryc44f6a42017-04-05 15:58:31 -0700438// replaces any unacceptable characters with '_', the
439// length of the resulting string is equal to the input string
Tom Cherryed506f72017-05-25 15:58:59 -0700440void SanitizePartitionName(std::string* string) {
Tom Cherryc44f6a42017-04-05 15:58:31 -0700441 const char* accept =
442 "abcdefghijklmnopqrstuvwxyz"
443 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
444 "0123456789"
445 "_-.";
446
Tom Cherry2e344f92017-04-04 17:53:45 -0700447 if (!string) return;
Tom Cherryc44f6a42017-04-05 15:58:31 -0700448
Tom Cherry2e344f92017-04-04 17:53:45 -0700449 std::string::size_type pos = 0;
450 while ((pos = string->find_first_not_of(accept, pos)) != std::string::npos) {
451 (*string)[pos] = '_';
Tom Cherryc44f6a42017-04-05 15:58:31 -0700452 }
453}
454
Tom Cherryed506f72017-05-25 15:58:59 -0700455std::vector<std::string> DeviceHandler::GetBlockDeviceSymlinks(const Uevent& uevent) const {
Douglas Anderson9481f972024-11-06 09:28:07 -0800456 BlockDeviceInfo info;
Mark Salyzyne419a792019-03-06 15:18:46 -0800457 std::string partition;
David Anderson924858c2019-06-26 17:00:00 -0700458 std::string uuid;
Colin Crossb0ab94b2010-04-08 16:16:20 -0700459
Douglas Anderson9f760f82024-10-15 14:22:02 -0700460 if (FindDmDevice(uevent, &partition, &uuid)) {
461 std::vector<std::string> symlinks = {"/dev/block/mapper/" + partition};
462 if (!uuid.empty()) {
463 symlinks.emplace_back("/dev/block/mapper/by-uuid/" + uuid);
464 }
465 return symlinks;
Douglas Anderson9481f972024-11-06 09:28:07 -0800466 }
Tom Cherry1ab8f552017-04-06 14:41:30 -0700467
Douglas Anderson9481f972024-11-06 09:28:07 -0800468 info = GetBlockDeviceInfo(uevent.path);
Tom Cherry1ab8f552017-04-06 14:41:30 -0700469
Douglas Anderson9481f972024-11-06 09:28:07 -0800470 if (info.type.empty()) {
Tom Cherry2e344f92017-04-04 17:53:45 -0700471 return {};
Andrew Boiea885d042013-09-13 17:41:20 -0700472 }
Dima Zavinf395c922013-03-06 16:23:57 -0800473
Tom Cherry2e344f92017-04-04 17:53:45 -0700474 std::vector<std::string> links;
Colin Crossb0ab94b2010-04-08 16:16:20 -0700475
Douglas Anderson9481f972024-11-06 09:28:07 -0800476 LOG(VERBOSE) << "found " << info.type << " device " << info.str;
Colin Crossfadb85e2011-03-30 18:32:12 -0700477
Douglas Anderson9481f972024-11-06 09:28:07 -0800478 auto link_path = "/dev/block/" + info.type + "/" + info.str;
Colin Crossb0ab94b2010-04-08 16:16:20 -0700479
Tom Cherryed506f72017-05-25 15:58:59 -0700480 if (!uevent.partition_name.empty()) {
481 std::string partition_name_sanitized(uevent.partition_name);
482 SanitizePartitionName(&partition_name_sanitized);
483 if (partition_name_sanitized != uevent.partition_name) {
484 LOG(VERBOSE) << "Linking partition '" << uevent.partition_name << "' as '"
Tom Cherry2e344f92017-04-04 17:53:45 -0700485 << partition_name_sanitized << "'";
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700486 }
Tom Cherry2e344f92017-04-04 17:53:45 -0700487 links.emplace_back(link_path + "/by-name/" + partition_name_sanitized);
Bowgo Tsai8eec38f2018-05-16 18:33:44 +0800488 // Adds symlink: /dev/block/by-name/<partition_name>.
Douglas Anderson9481f972024-11-06 09:28:07 -0800489 if (info.is_boot_device) {
Bowgo Tsai8eec38f2018-05-16 18:33:44 +0800490 links.emplace_back("/dev/block/by-name/" + partition_name_sanitized);
491 }
Douglas Anderson9481f972024-11-06 09:28:07 -0800492 } else if (info.is_boot_device) {
Tom Cherry2c56d7c2018-12-20 14:36:49 -0800493 // If we don't have a partition name but we are a partition on a boot device, create a
494 // symlink of /dev/block/by-name/<device_name> for symmetry.
495 links.emplace_back("/dev/block/by-name/" + uevent.device_name);
Tom Cherry96e5f9b2021-07-30 09:54:36 -0700496 auto partition_name = GetPartitionNameForDevice(uevent.device_name);
497 if (!partition_name.empty()) {
498 links.emplace_back("/dev/block/by-name/" + partition_name);
499 }
Colin Crossb0ab94b2010-04-08 16:16:20 -0700500 }
501
Jaegeuk Kimb92e5b52023-01-12 13:08:15 -0800502 std::string model;
503 if (ReadFileToString("/sys/class/block/" + uevent.device_name + "/queue/zoned", &model) &&
504 !StartsWith(model, "none")) {
505 links.emplace_back("/dev/block/by-name/zoned_device");
Bart Van Assche262f1e82024-05-23 11:20:07 -0700506 links.emplace_back("/dev/sys/block/by-name/zoned_device");
Jaegeuk Kimb92e5b52023-01-12 13:08:15 -0800507 }
508
Tom Cherryed506f72017-05-25 15:58:59 -0700509 auto last_slash = uevent.path.rfind('/');
510 links.emplace_back(link_path + "/" + uevent.path.substr(last_slash + 1));
Colin Crossb0ab94b2010-04-08 16:16:20 -0700511
512 return links;
Colin Crossb0ab94b2010-04-08 16:16:20 -0700513}
514
David Anderson924858c2019-06-26 17:00:00 -0700515static void RemoveDeviceMapperLinks(const std::string& devpath) {
516 std::vector<std::string> dirs = {
517 "/dev/block/mapper",
518 "/dev/block/mapper/by-uuid",
519 };
520 for (const auto& dir : dirs) {
521 if (access(dir.c_str(), F_OK) != 0) continue;
522
523 std::unique_ptr<DIR, decltype(&closedir)> dh(opendir(dir.c_str()), closedir);
524 if (!dh) {
525 PLOG(ERROR) << "Failed to open directory " << dir;
526 continue;
527 }
528
529 struct dirent* dp;
530 std::string link_path;
531 while ((dp = readdir(dh.get())) != nullptr) {
532 if (dp->d_type != DT_LNK) continue;
533
534 auto path = dir + "/" + dp->d_name;
535 if (Readlink(path, &link_path) && link_path == devpath) {
536 unlink(path.c_str());
537 }
538 }
539 }
540}
541
Tom Cherryb4dd8812017-06-23 12:43:48 -0700542void DeviceHandler::HandleDevice(const std::string& action, const std::string& devpath, bool block,
Tom Cherryed506f72017-05-25 15:58:59 -0700543 int major, int minor, const std::vector<std::string>& links) const {
Tom Cherrye3e48212017-04-11 13:53:37 -0700544 if (action == "add") {
Tom Cherryed506f72017-05-25 15:58:59 -0700545 MakeDevice(devpath, block, major, minor, links);
David Anderson924858c2019-06-26 17:00:00 -0700546 }
547
David Andersond6bf86b2022-12-08 09:53:03 -0800548 // Handle device-mapper nodes.
549 // On kernels <= 5.10, the "add" event is fired on DM_DEV_CREATE, but does not contain name
550 // information until DM_TABLE_LOAD - thus, we wait for a "change" event.
551 // On kernels >= 5.15, the "add" event is fired on DM_TABLE_LOAD, followed by a "change"
552 // event.
David Anderson924858c2019-06-26 17:00:00 -0700553 if (action == "add" || (action == "change" && StartsWith(devpath, "/dev/block/dm-"))) {
Tom Cherry2e344f92017-04-04 17:53:45 -0700554 for (const auto& link : links) {
Bart Van Assche262f1e82024-05-23 11:20:07 -0700555 std::string target;
556 if (StartsWith(link, "/dev/block/")) {
557 target = devpath;
558 } else if (StartsWith(link, "/dev/sys/block/")) {
559 target = "/sys/class/block/" + Basename(devpath);
560 } else {
561 LOG(ERROR) << "Unrecognized link type: " << link;
562 continue;
563 }
564
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700565 if (!mkdir_recursive(Dirname(link), 0755)) {
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700566 PLOG(ERROR) << "Failed to create directory " << Dirname(link);
Tom Cherryed506f72017-05-25 15:58:59 -0700567 }
568
Bart Van Assche262f1e82024-05-23 11:20:07 -0700569 if (symlink(target.c_str(), link.c_str())) {
Bowgo Tsai8eec38f2018-05-16 18:33:44 +0800570 if (errno != EEXIST) {
571 PLOG(ERROR) << "Failed to symlink " << devpath << " to " << link;
572 } else if (std::string link_path;
573 Readlink(link, &link_path) && link_path != devpath) {
574 PLOG(ERROR) << "Failed to symlink " << devpath << " to " << link
575 << ", which already links to: " << link_path;
576 }
Tom Cherryed506f72017-05-25 15:58:59 -0700577 }
Colin Crossb0ab94b2010-04-08 16:16:20 -0700578 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700579 }
580
Tom Cherrye3e48212017-04-11 13:53:37 -0700581 if (action == "remove") {
David Anderson924858c2019-06-26 17:00:00 -0700582 if (StartsWith(devpath, "/dev/block/dm-")) {
583 RemoveDeviceMapperLinks(devpath);
584 }
Tom Cherry2e344f92017-04-04 17:53:45 -0700585 for (const auto& link : links) {
Tom Cherryed506f72017-05-25 15:58:59 -0700586 std::string link_path;
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700587 if (Readlink(link, &link_path) && link_path == devpath) {
Tom Cherryed506f72017-05-25 15:58:59 -0700588 unlink(link.c_str());
589 }
Colin Crossb0ab94b2010-04-08 16:16:20 -0700590 }
Tom Cherrye3e48212017-04-11 13:53:37 -0700591 unlink(devpath.c_str());
Colin Crossb0ab94b2010-04-08 16:16:20 -0700592 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700593}
594
Tri Voff89b8d2019-09-24 13:00:43 -0700595void DeviceHandler::HandleAshmemUevent(const Uevent& uevent) {
596 if (uevent.device_name == "ashmem") {
597 static const std::string boot_id_path = "/proc/sys/kernel/random/boot_id";
598 std::string boot_id;
599 if (!ReadFileToString(boot_id_path, &boot_id)) {
600 PLOG(ERROR) << "Cannot duplicate ashmem device node. Failed to read " << boot_id_path;
601 return;
Eric Carusobb4a4092024-08-30 13:34:24 -0400602 }
Tri Voff89b8d2019-09-24 13:00:43 -0700603 boot_id = Trim(boot_id);
604
605 Uevent dup_ashmem_uevent = uevent;
606 dup_ashmem_uevent.device_name += boot_id;
607 dup_ashmem_uevent.path += boot_id;
608 HandleUevent(dup_ashmem_uevent);
609 }
610}
611
Douglas Andersone9de3102024-10-22 14:34:30 -0700612// Check Uevents looking for the kernel's boot partition UUID
613//
614// When we can stop checking uevents (either because we're done or because
615// we weren't looking for the kernel's boot partition UUID) then return
616// true. Return false if we're not done yet.
617bool DeviceHandler::CheckUeventForBootPartUuid(const Uevent& uevent) {
618 // If we aren't using boot_part_uuid then we're done.
619 if (boot_part_uuid_.empty()) {
620 return true;
621 }
622
623 // Finding the boot partition is a one-time thing that we do at init
624 // time, not steady state. This is because the boot partition isn't
625 // allowed to go away or change. Once we found the boot partition we don't
626 // expect to run again.
627 if (found_boot_part_uuid_) {
628 LOG(WARNING) << __PRETTY_FUNCTION__
629 << " shouldn't run after kernel boot partition is found";
630 return true;
631 }
632
633 // We only need to look at newly-added block devices. Note that if someone
634 // is replaying events all existing devices will get "add"ed.
635 if (uevent.subsystem != "block" || uevent.action != "add") {
636 return false;
637 }
638
639 // If it's not the partition we care about then move on.
640 if (uevent.partition_uuid != boot_part_uuid_) {
641 return false;
642 }
643
644 auto device = GetBlockDeviceInfo(uevent.path);
645
646 LOG(INFO) << "Boot device " << device.str << " found via partition UUID";
647 found_boot_part_uuid_ = true;
648 boot_devices_.clear();
649 boot_devices_.insert(device.str);
650
651 return true;
652}
653
Tom Cherry457e28f2018-08-01 13:12:20 -0700654void DeviceHandler::HandleUevent(const Uevent& uevent) {
Eric Carusobb4a4092024-08-30 13:34:24 -0400655 if (uevent.action == "add" || uevent.action == "change" || uevent.action == "bind" ||
656 uevent.action == "online") {
657 FixupSysPermissions(uevent.path, uevent.subsystem);
658 }
Colin Crosseb5ba832011-03-30 17:37:17 -0700659
Tom Cherry3fa46732017-04-11 14:19:50 -0700660 // if it's not a /dev device, nothing to do
Tom Cherryed506f72017-05-25 15:58:59 -0700661 if (uevent.major < 0 || uevent.minor < 0) return;
Greg Hackmann3312aa82013-11-18 15:24:40 -0800662
Tom Cherry3fa46732017-04-11 14:19:50 -0700663 std::string devpath;
Tom Cherryb4dd8812017-06-23 12:43:48 -0700664 std::vector<std::string> links;
665 bool block = false;
Greg Hackmann3312aa82013-11-18 15:24:40 -0800666
Tom Cherryb4dd8812017-06-23 12:43:48 -0700667 if (uevent.subsystem == "block") {
668 block = true;
669 devpath = "/dev/block/" + Basename(uevent.path);
670
671 if (StartsWith(uevent.path, "/devices")) {
672 links = GetBlockDeviceSymlinks(uevent);
673 }
Tom Cherryed506f72017-05-25 15:58:59 -0700674 } else if (const auto subsystem =
675 std::find(subsystems_.cbegin(), subsystems_.cend(), uevent.subsystem);
676 subsystem != subsystems_.cend()) {
Tom Cherryfe062052017-04-24 16:59:05 -0700677 devpath = subsystem->ParseDevPath(uevent);
Tom Cherry9c8d6dd2017-08-17 09:38:01 -0700678 } else if (uevent.subsystem == "usb") {
679 if (!uevent.device_name.empty()) {
680 devpath = "/dev/" + uevent.device_name;
681 } else {
682 // This imitates the file system that would be created
683 // if we were using devfs instead.
684 // Minors are broken up into groups of 128, starting at "001"
685 int bus_id = uevent.minor / 128 + 1;
686 int device_id = uevent.minor % 128 + 1;
687 devpath = StringPrintf("/dev/bus/usb/%03d/%03d", bus_id, device_id);
688 }
689 } else if (StartsWith(uevent.subsystem, "usb")) {
690 // ignore other USB events
691 return;
David Anderson515a5bd2020-10-19 19:54:18 -0700692 } else if (uevent.subsystem == "misc" && StartsWith(uevent.device_name, "dm-user/")) {
693 devpath = "/dev/dm-user/" + uevent.device_name.substr(8);
Jakob Vukalovice3774322023-07-11 10:28:53 +0100694 } else if (uevent.subsystem == "misc" && uevent.device_name == "vfio/vfio") {
695 devpath = "/dev/" + uevent.device_name;
Tom Cherry780a71e2017-04-04 16:30:40 -0700696 } else {
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700697 devpath = "/dev/" + Basename(uevent.path);
Tom Cherry780a71e2017-04-04 16:30:40 -0700698 }
Colin Crosseb5ba832011-03-30 17:37:17 -0700699
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700700 mkdir_recursive(Dirname(devpath), 0755);
Tom Cherryfe062052017-04-24 16:59:05 -0700701
Tom Cherryb4dd8812017-06-23 12:43:48 -0700702 HandleDevice(uevent.action, devpath, block, uevent.major, uevent.minor, links);
Tri Voff89b8d2019-09-24 13:00:43 -0700703
704 // Duplicate /dev/ashmem device and name it /dev/ashmem<boot_id>.
705 // TODO(b/111903542): remove once all users of /dev/ashmem are migrated to libcutils API.
706 HandleAshmemUevent(uevent);
Colin Crosseb5ba832011-03-30 17:37:17 -0700707}
708
Tom Cherry457e28f2018-08-01 13:12:20 -0700709void DeviceHandler::ColdbootDone() {
Oleksiy Avramchenkodd5802a2018-11-02 10:06:47 +0100710 skip_restorecon_ = false;
Tom Cherry457e28f2018-08-01 13:12:20 -0700711}
712
Tom Cherryed506f72017-05-25 15:58:59 -0700713DeviceHandler::DeviceHandler(std::vector<Permissions> dev_permissions,
714 std::vector<SysfsPermissions> sysfs_permissions,
Bowgo Tsai8eec38f2018-05-16 18:33:44 +0800715 std::vector<Subsystem> subsystems, std::set<std::string> boot_devices,
Douglas Andersone9de3102024-10-22 14:34:30 -0700716 std::string boot_part_uuid, bool skip_restorecon)
Tom Cherryed506f72017-05-25 15:58:59 -0700717 : dev_permissions_(std::move(dev_permissions)),
718 sysfs_permissions_(std::move(sysfs_permissions)),
719 subsystems_(std::move(subsystems)),
Bowgo Tsai8eec38f2018-05-16 18:33:44 +0800720 boot_devices_(std::move(boot_devices)),
Douglas Andersone9de3102024-10-22 14:34:30 -0700721 boot_part_uuid_(boot_part_uuid),
Sandeep Patilcd2ba0d2017-06-21 12:46:41 -0700722 skip_restorecon_(skip_restorecon),
Douglas Andersone9de3102024-10-22 14:34:30 -0700723 sysfs_mount_point_("/sys") {
724 // If both a boot partition UUID and a list of boot devices are
725 // specified then we ignore the boot_devices in favor of boot_part_uuid.
726 if (boot_devices_.size() && !boot_part_uuid.empty()) {
727 LOG(WARNING) << "Both boot_devices and boot_part_uuid provided; ignoring bootdevices";
728 boot_devices_.clear();
729 }
730}
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700731
Tom Cherryed506f72017-05-25 15:58:59 -0700732DeviceHandler::DeviceHandler()
733 : DeviceHandler(std::vector<Permissions>{}, std::vector<SysfsPermissions>{},
Douglas Andersone9de3102024-10-22 14:34:30 -0700734 std::vector<Subsystem>{}, std::set<std::string>{}, "", false) {}
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700735
736} // namespace init
737} // namespace android