blob: 792d8c843ea5dd030686814849b5de7aebcd2340 [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;
48using android::base::Dirname;
Mark Salyzyne419a792019-03-06 15:18:46 -080049using android::base::ReadFileToString;
Tom Cherry81f5d3e2017-06-22 12:53:17 -070050using android::base::Readlink;
51using android::base::Realpath;
Tom Cherry96e5f9b2021-07-30 09:54:36 -070052using android::base::Split;
Tom Cherry81f5d3e2017-06-22 12:53:17 -070053using android::base::StartsWith;
54using android::base::StringPrintf;
Mark Salyzyne419a792019-03-06 15:18:46 -080055using android::base::Trim;
Tom Cherry81f5d3e2017-06-22 12:53:17 -070056
57namespace android {
58namespace init {
59
Andrew Boiea885d042013-09-13 17:41:20 -070060/* Given a path that may start with a PCI device, populate the supplied buffer
61 * with the PCI domain/bus number and the peripheral ID and return 0.
62 * If it doesn't start with a PCI device, or there is some error, return -1 */
Tom Cherryed506f72017-05-25 15:58:59 -070063static bool FindPciDevicePrefix(const std::string& path, std::string* result) {
Tom Cherry2e344f92017-04-04 17:53:45 -070064 result->clear();
Andrew Boiea885d042013-09-13 17:41:20 -070065
Tom Cherry81f5d3e2017-06-22 12:53:17 -070066 if (!StartsWith(path, "/devices/pci")) return false;
Andrew Boiea885d042013-09-13 17:41:20 -070067
68 /* Beginning of the prefix is the initial "pci" after "/devices/" */
Tom Cherry2e344f92017-04-04 17:53:45 -070069 std::string::size_type start = 9;
Andrew Boiea885d042013-09-13 17:41:20 -070070
71 /* End of the prefix is two path '/' later, capturing the domain/bus number
72 * and the peripheral ID. Example: pci0000:00/0000:00:1f.2 */
Tom Cherry2e344f92017-04-04 17:53:45 -070073 auto end = path.find('/', start);
74 if (end == std::string::npos) return false;
Andrew Boiea885d042013-09-13 17:41:20 -070075
Tom Cherry2e344f92017-04-04 17:53:45 -070076 end = path.find('/', end + 1);
77 if (end == std::string::npos) return false;
Andrew Boiea885d042013-09-13 17:41:20 -070078
Tom Cherry2e344f92017-04-04 17:53:45 -070079 auto length = end - start;
80 if (length <= 4) {
81 // The minimum string that will get to this check is 'pci/', which is malformed,
82 // so return false
83 return false;
84 }
85
86 *result = path.substr(start, length);
87 return true;
Andrew Boiea885d042013-09-13 17:41:20 -070088}
89
Jeremy Compostella937309d2017-03-03 16:27:29 +010090/* Given a path that may start with a virtual block device, populate
91 * the supplied buffer with the virtual block device ID and return 0.
92 * If it doesn't start with a virtual block device, or there is some
93 * error, return -1 */
Tom Cherryed506f72017-05-25 15:58:59 -070094static bool FindVbdDevicePrefix(const std::string& path, std::string* result) {
Tom Cherry2e344f92017-04-04 17:53:45 -070095 result->clear();
96
Tom Cherry81f5d3e2017-06-22 12:53:17 -070097 if (!StartsWith(path, "/devices/vbd-")) return false;
Jeremy Compostella937309d2017-03-03 16:27:29 +010098
99 /* Beginning of the prefix is the initial "vbd-" after "/devices/" */
Tom Cherry2e344f92017-04-04 17:53:45 -0700100 std::string::size_type start = 13;
Jeremy Compostella937309d2017-03-03 16:27:29 +0100101
102 /* End of the prefix is one path '/' later, capturing the
103 virtual block device ID. Example: 768 */
Tom Cherry2e344f92017-04-04 17:53:45 -0700104 auto end = path.find('/', start);
105 if (end == std::string::npos) return false;
Jeremy Compostella937309d2017-03-03 16:27:29 +0100106
Tom Cherry2e344f92017-04-04 17:53:45 -0700107 auto length = end - start;
108 if (length == 0) return false;
Jeremy Compostella937309d2017-03-03 16:27:29 +0100109
Tom Cherry2e344f92017-04-04 17:53:45 -0700110 *result = path.substr(start, length);
111 return true;
Jeremy Compostella937309d2017-03-03 16:27:29 +0100112}
113
Mark Salyzyne419a792019-03-06 15:18:46 -0800114// Given a path that may start with a virtual dm block device, populate
115// the supplied buffer with the dm module's instantiated name.
116// If it doesn't start with a virtual block device, or there is some
117// error, return false.
David Anderson59abbfe2023-05-16 15:53:57 -0700118static bool FindDmDevice(const Uevent& uevent, std::string* name, std::string* uuid) {
119 if (!StartsWith(uevent.path, "/devices/virtual/block/dm-")) return false;
120 if (uevent.action == "remove") return false; // Avoid error spam from ioctl
Mark Salyzyne419a792019-03-06 15:18:46 -0800121
David Anderson59abbfe2023-05-16 15:53:57 -0700122 dev_t dev = makedev(uevent.major, uevent.minor);
David Anderson924858c2019-06-26 17:00:00 -0700123
David Anderson59abbfe2023-05-16 15:53:57 -0700124 auto& dm = android::dm::DeviceMapper::Instance();
125 return dm.GetDeviceNameAndUuid(dev, name, uuid);
Mark Salyzyne419a792019-03-06 15:18:46 -0800126}
127
Tom Cherry47031c82020-12-07 13:33:46 -0800128Permissions::Permissions(const std::string& name, mode_t perm, uid_t uid, gid_t gid,
129 bool no_fnm_pathname)
130 : name_(name),
131 perm_(perm),
132 uid_(uid),
133 gid_(gid),
134 prefix_(false),
135 wildcard_(false),
136 no_fnm_pathname_(no_fnm_pathname) {
Tom Cherryed506f72017-05-25 15:58:59 -0700137 // Set 'prefix_' or 'wildcard_' based on the below cases:
138 //
139 // 1) No '*' in 'name' -> Neither are set and Match() checks a given path for strict
140 // equality with 'name'
141 //
142 // 2) '*' only appears as the last character in 'name' -> 'prefix'_ is set to true and
143 // Match() checks if 'name' is a prefix of a given path.
144 //
145 // 3) '*' appears elsewhere -> 'wildcard_' is set to true and Match() uses fnmatch()
146 // with FNM_PATHNAME to compare 'name' to a given path.
Tom Cherryed506f72017-05-25 15:58:59 -0700147 auto wildcard_position = name_.find('*');
148 if (wildcard_position != std::string::npos) {
149 if (wildcard_position == name_.length() - 1) {
150 prefix_ = true;
151 name_.pop_back();
152 } else {
153 wildcard_ = true;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700154 }
Elliott Hughesc0e919c2015-02-04 14:46:36 -0800155 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700156}
157
Tom Cherryed506f72017-05-25 15:58:59 -0700158bool Permissions::Match(const std::string& path) const {
Elliott Hughes579e6822017-12-20 09:41:00 -0800159 if (prefix_) return StartsWith(path, name_);
Tom Cherry47031c82020-12-07 13:33:46 -0800160 if (wildcard_)
161 return fnmatch(name_.c_str(), path.c_str(), no_fnm_pathname_ ? 0 : FNM_PATHNAME) == 0;
Tom Cherryed506f72017-05-25 15:58:59 -0700162 return path == name_;
163}
164
165bool SysfsPermissions::MatchWithSubsystem(const std::string& path,
166 const std::string& subsystem) const {
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700167 std::string path_basename = Basename(path);
Tom Cherryed506f72017-05-25 15:58:59 -0700168 if (name().find(subsystem) != std::string::npos) {
169 if (Match("/sys/class/" + subsystem + "/" + path_basename)) return true;
170 if (Match("/sys/bus/" + subsystem + "/devices/" + path_basename)) return true;
171 }
172 return Match(path);
173}
174
175void SysfsPermissions::SetPermissions(const std::string& path) const {
176 std::string attribute_file = path + "/" + attribute_;
177 LOG(VERBOSE) << "fixup " << attribute_file << " " << uid() << " " << gid() << " " << std::oct
178 << perm();
179
180 if (access(attribute_file.c_str(), F_OK) == 0) {
181 if (chown(attribute_file.c_str(), uid(), gid()) != 0) {
182 PLOG(ERROR) << "chown(" << attribute_file << ", " << uid() << ", " << gid()
183 << ") failed";
184 }
185 if (chmod(attribute_file.c_str(), perm()) != 0) {
186 PLOG(ERROR) << "chmod(" << attribute_file << ", " << perm() << ") failed";
187 }
188 }
189}
190
Tom Cherry96e5f9b2021-07-30 09:54:36 -0700191std::string DeviceHandler::GetPartitionNameForDevice(const std::string& query_device) {
192 static const auto partition_map = [] {
193 std::vector<std::pair<std::string, std::string>> partition_map;
194 auto parser = [&partition_map](const std::string& key, const std::string& value) {
195 if (key != "androidboot.partition_map") {
196 return;
197 }
198 for (const auto& map : Split(value, ";")) {
199 auto map_pieces = Split(map, ",");
200 if (map_pieces.size() != 2) {
201 LOG(ERROR) << "Expected a comma separated device,partition mapping, but found '"
202 << map << "'";
203 continue;
204 }
205 partition_map.emplace_back(map_pieces[0], map_pieces[1]);
206 }
207 };
Yi-Yo Chiangda5323e2023-08-02 01:08:23 +0800208 android::fs_mgr::ImportKernelCmdline(parser);
Yi-Yo Chiang79ad1e22023-07-29 17:37:23 +0800209 android::fs_mgr::ImportBootconfig(parser);
Tom Cherry96e5f9b2021-07-30 09:54:36 -0700210 return partition_map;
211 }();
212
213 for (const auto& [device, partition] : partition_map) {
214 if (query_device == device) {
215 return partition;
216 }
217 }
218 return {};
219}
220
Sandeep Patilcd2ba0d2017-06-21 12:46:41 -0700221// Given a path that may start with a platform device, find the parent platform device by finding a
222// parent directory with a 'subsystem' symlink that points to the platform bus.
223// If it doesn't start with a platform device, return false
224bool DeviceHandler::FindPlatformDevice(std::string path, std::string* platform_device_path) const {
225 platform_device_path->clear();
226
227 // Uevents don't contain the mount point, so we need to add it here.
228 path.insert(0, sysfs_mount_point_);
229
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700230 std::string directory = Dirname(path);
Sandeep Patilcd2ba0d2017-06-21 12:46:41 -0700231
232 while (directory != "/" && directory != ".") {
233 std::string subsystem_link_path;
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700234 if (Realpath(directory + "/subsystem", &subsystem_link_path) &&
Usama Arifd86300c2020-06-12 13:45:11 +0100235 (subsystem_link_path == sysfs_mount_point_ + "/bus/platform" ||
236 subsystem_link_path == sysfs_mount_point_ + "/bus/amba")) {
Sandeep Patilcd2ba0d2017-06-21 12:46:41 -0700237 // We need to remove the mount point that we added above before returning.
238 directory.erase(0, sysfs_mount_point_.size());
239 *platform_device_path = directory;
Tom Cherryed506f72017-05-25 15:58:59 -0700240 return true;
241 }
Sandeep Patilcd2ba0d2017-06-21 12:46:41 -0700242
243 auto last_slash = path.rfind('/');
244 if (last_slash == std::string::npos) return false;
245
246 path.erase(last_slash);
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700247 directory = Dirname(path);
Tom Cherryed506f72017-05-25 15:58:59 -0700248 }
Sandeep Patilcd2ba0d2017-06-21 12:46:41 -0700249
Tom Cherryed506f72017-05-25 15:58:59 -0700250 return false;
251}
252
253void DeviceHandler::FixupSysPermissions(const std::string& upath,
254 const std::string& subsystem) const {
255 // upaths omit the "/sys" that paths in this list
256 // contain, so we prepend it...
257 std::string path = "/sys" + upath;
258
259 for (const auto& s : sysfs_permissions_) {
260 if (s.MatchWithSubsystem(path, subsystem)) s.SetPermissions(path);
261 }
262
Tom Cherryc5833052017-05-16 15:35:41 -0700263 if (!skip_restorecon_ && access(path.c_str(), F_OK) == 0) {
Tom Cherryed506f72017-05-25 15:58:59 -0700264 LOG(VERBOSE) << "restorecon_recursive: " << path;
265 if (selinux_android_restorecon(path.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE) != 0) {
266 PLOG(ERROR) << "selinux_android_restorecon(" << path << ") failed";
267 }
268 }
269}
270
271std::tuple<mode_t, uid_t, gid_t> DeviceHandler::GetDevicePermissions(
272 const std::string& path, const std::vector<std::string>& links) const {
273 // Search the perms list in reverse so that ueventd.$hardware can override ueventd.rc.
274 for (auto it = dev_permissions_.crbegin(); it != dev_permissions_.crend(); ++it) {
275 if (it->Match(path) || std::any_of(links.cbegin(), links.cend(),
276 [it](const auto& link) { return it->Match(link); })) {
277 return {it->perm(), it->uid(), it->gid()};
278 }
279 }
280 /* Default if nothing found. */
281 return {0600, 0, 0};
282}
283
Tom Cherryb4dd8812017-06-23 12:43:48 -0700284void DeviceHandler::MakeDevice(const std::string& path, bool block, int major, int minor,
Tom Cherryed506f72017-05-25 15:58:59 -0700285 const std::vector<std::string>& links) const {
286 auto[mode, uid, gid] = GetDevicePermissions(path, links);
287 mode |= (block ? S_IFBLK : S_IFCHR);
288
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700289 std::string secontext;
290 if (!SelabelLookupFileContextBestMatch(path, links, mode, &secontext)) {
291 PLOG(ERROR) << "Device '" << path << "' not created; cannot find SELinux label";
292 return;
293 }
294 if (!secontext.empty()) {
295 setfscreatecon(secontext.c_str());
Tom Cherryed506f72017-05-25 15:58:59 -0700296 }
297
David Andersonf8825fa2021-07-02 20:47:27 -0700298 gid_t new_group = -1;
299
Tom Cherryed506f72017-05-25 15:58:59 -0700300 dev_t dev = makedev(major, minor);
301 /* Temporarily change egid to avoid race condition setting the gid of the
302 * device node. Unforunately changing the euid would prevent creation of
303 * some device nodes, so the uid has to be set with chown() and is still
304 * racy. Fixing the gid race at least fixed the issue with system_server
305 * opening dynamic input devices under the AID_INPUT gid. */
306 if (setegid(gid)) {
307 PLOG(ERROR) << "setegid(" << gid << ") for " << path << " device failed";
308 goto out;
309 }
zexin.hou76cba8a2022-04-14 16:08:17 +0800310 /* If the node already exists update its SELinux label and the file mode to handle cases when
311 * it was created with the wrong context and file mode during coldboot procedure. */
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700312 if (mknod(path.c_str(), mode, dev) && (errno == EEXIST) && !secontext.empty()) {
Tom Cherryed506f72017-05-25 15:58:59 -0700313 char* fcon = nullptr;
314 int rc = lgetfilecon(path.c_str(), &fcon);
315 if (rc < 0) {
316 PLOG(ERROR) << "Cannot get SELinux label on '" << path << "' device";
317 goto out;
318 }
319
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700320 bool different = fcon != secontext;
Tom Cherryed506f72017-05-25 15:58:59 -0700321 freecon(fcon);
322
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700323 if (different && lsetfilecon(path.c_str(), secontext.c_str())) {
Tom Cherryed506f72017-05-25 15:58:59 -0700324 PLOG(ERROR) << "Cannot set '" << secontext << "' SELinux label on '" << path
325 << "' device";
326 }
David Andersonf8825fa2021-07-02 20:47:27 -0700327
328 struct stat s;
329 if (stat(path.c_str(), &s) == 0) {
330 if (gid != s.st_gid) {
331 new_group = gid;
332 }
zexin.hou76cba8a2022-04-14 16:08:17 +0800333 if (mode != s.st_mode) {
334 if (chmod(path.c_str(), mode) != 0) {
335 PLOG(ERROR) << "Cannot chmod " << path << " to " << mode;
336 }
337 }
David Andersonf8825fa2021-07-02 20:47:27 -0700338 } else {
339 PLOG(ERROR) << "Cannot stat " << path;
340 }
Tom Cherryed506f72017-05-25 15:58:59 -0700341 }
342
343out:
David Andersonf8825fa2021-07-02 20:47:27 -0700344 if (chown(path.c_str(), uid, new_group) < 0) {
345 PLOG(ERROR) << "Cannot chown " << path << " " << uid << " " << new_group;
346 }
Tom Cherryed506f72017-05-25 15:58:59 -0700347 if (setegid(AID_ROOT)) {
348 PLOG(FATAL) << "setegid(AID_ROOT) failed";
349 }
350
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700351 if (!secontext.empty()) {
Tom Cherryed506f72017-05-25 15:58:59 -0700352 setfscreatecon(nullptr);
353 }
354}
355
Tom Cherryc44f6a42017-04-05 15:58:31 -0700356// replaces any unacceptable characters with '_', the
357// length of the resulting string is equal to the input string
Tom Cherryed506f72017-05-25 15:58:59 -0700358void SanitizePartitionName(std::string* string) {
Tom Cherryc44f6a42017-04-05 15:58:31 -0700359 const char* accept =
360 "abcdefghijklmnopqrstuvwxyz"
361 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
362 "0123456789"
363 "_-.";
364
Tom Cherry2e344f92017-04-04 17:53:45 -0700365 if (!string) return;
Tom Cherryc44f6a42017-04-05 15:58:31 -0700366
Tom Cherry2e344f92017-04-04 17:53:45 -0700367 std::string::size_type pos = 0;
368 while ((pos = string->find_first_not_of(accept, pos)) != std::string::npos) {
369 (*string)[pos] = '_';
Tom Cherryc44f6a42017-04-05 15:58:31 -0700370 }
371}
372
Tom Cherryed506f72017-05-25 15:58:59 -0700373std::vector<std::string> DeviceHandler::GetBlockDeviceSymlinks(const Uevent& uevent) const {
Tom Cherry2e344f92017-04-04 17:53:45 -0700374 std::string device;
Tom Cherry2e344f92017-04-04 17:53:45 -0700375 std::string type;
Mark Salyzyne419a792019-03-06 15:18:46 -0800376 std::string partition;
David Anderson924858c2019-06-26 17:00:00 -0700377 std::string uuid;
Colin Crossb0ab94b2010-04-08 16:16:20 -0700378
Sandeep Patilcd2ba0d2017-06-21 12:46:41 -0700379 if (FindPlatformDevice(uevent.path, &device)) {
Tom Cherry1ab8f552017-04-06 14:41:30 -0700380 // Skip /devices/platform or /devices/ if present
Bart Van Assche564d9702024-05-22 13:07:13 -0700381 static constexpr std::string_view devices_platform_prefix = "/devices/platform/";
382 static constexpr std::string_view devices_prefix = "/devices/";
Tom Cherry1ab8f552017-04-06 14:41:30 -0700383
Elliott Hughes579e6822017-12-20 09:41:00 -0800384 if (StartsWith(device, devices_platform_prefix)) {
Tom Cherry1ab8f552017-04-06 14:41:30 -0700385 device = device.substr(devices_platform_prefix.length());
Elliott Hughes579e6822017-12-20 09:41:00 -0800386 } else if (StartsWith(device, devices_prefix)) {
Tom Cherry1ab8f552017-04-06 14:41:30 -0700387 device = device.substr(devices_prefix.length());
388 }
389
Andrew Boiea885d042013-09-13 17:41:20 -0700390 type = "platform";
Tom Cherryed506f72017-05-25 15:58:59 -0700391 } else if (FindPciDevicePrefix(uevent.path, &device)) {
Andrew Boiea885d042013-09-13 17:41:20 -0700392 type = "pci";
Tom Cherryed506f72017-05-25 15:58:59 -0700393 } else if (FindVbdDevicePrefix(uevent.path, &device)) {
Jeremy Compostella937309d2017-03-03 16:27:29 +0100394 type = "vbd";
David Anderson59abbfe2023-05-16 15:53:57 -0700395 } else if (FindDmDevice(uevent, &partition, &uuid)) {
David Anderson924858c2019-06-26 17:00:00 -0700396 std::vector<std::string> symlinks = {"/dev/block/mapper/" + partition};
397 if (!uuid.empty()) {
398 symlinks.emplace_back("/dev/block/mapper/by-uuid/" + uuid);
399 }
400 return symlinks;
Andrew Boiea885d042013-09-13 17:41:20 -0700401 } else {
Tom Cherry2e344f92017-04-04 17:53:45 -0700402 return {};
Andrew Boiea885d042013-09-13 17:41:20 -0700403 }
Dima Zavinf395c922013-03-06 16:23:57 -0800404
Tom Cherry2e344f92017-04-04 17:53:45 -0700405 std::vector<std::string> links;
Colin Crossb0ab94b2010-04-08 16:16:20 -0700406
Sandeep Patil35403eb2017-02-08 20:27:12 -0800407 LOG(VERBOSE) << "found " << type << " device " << device;
Colin Crossfadb85e2011-03-30 18:32:12 -0700408
Tom Cherry2e344f92017-04-04 17:53:45 -0700409 auto link_path = "/dev/block/" + type + "/" + device;
Colin Crossb0ab94b2010-04-08 16:16:20 -0700410
Tom Cherry2c56d7c2018-12-20 14:36:49 -0800411 bool is_boot_device = boot_devices_.find(device) != boot_devices_.end();
Tom Cherryed506f72017-05-25 15:58:59 -0700412 if (!uevent.partition_name.empty()) {
413 std::string partition_name_sanitized(uevent.partition_name);
414 SanitizePartitionName(&partition_name_sanitized);
415 if (partition_name_sanitized != uevent.partition_name) {
416 LOG(VERBOSE) << "Linking partition '" << uevent.partition_name << "' as '"
Tom Cherry2e344f92017-04-04 17:53:45 -0700417 << partition_name_sanitized << "'";
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700418 }
Tom Cherry2e344f92017-04-04 17:53:45 -0700419 links.emplace_back(link_path + "/by-name/" + partition_name_sanitized);
Bowgo Tsai8eec38f2018-05-16 18:33:44 +0800420 // Adds symlink: /dev/block/by-name/<partition_name>.
Tom Cherry2c56d7c2018-12-20 14:36:49 -0800421 if (is_boot_device) {
Bowgo Tsai8eec38f2018-05-16 18:33:44 +0800422 links.emplace_back("/dev/block/by-name/" + partition_name_sanitized);
423 }
Tom Cherry2c56d7c2018-12-20 14:36:49 -0800424 } else if (is_boot_device) {
425 // If we don't have a partition name but we are a partition on a boot device, create a
426 // symlink of /dev/block/by-name/<device_name> for symmetry.
427 links.emplace_back("/dev/block/by-name/" + uevent.device_name);
Tom Cherry96e5f9b2021-07-30 09:54:36 -0700428 auto partition_name = GetPartitionNameForDevice(uevent.device_name);
429 if (!partition_name.empty()) {
430 links.emplace_back("/dev/block/by-name/" + partition_name);
431 }
Colin Crossb0ab94b2010-04-08 16:16:20 -0700432 }
433
Jaegeuk Kimb92e5b52023-01-12 13:08:15 -0800434 std::string model;
435 if (ReadFileToString("/sys/class/block/" + uevent.device_name + "/queue/zoned", &model) &&
436 !StartsWith(model, "none")) {
437 links.emplace_back("/dev/block/by-name/zoned_device");
438 }
439
Tom Cherryed506f72017-05-25 15:58:59 -0700440 auto last_slash = uevent.path.rfind('/');
441 links.emplace_back(link_path + "/" + uevent.path.substr(last_slash + 1));
Colin Crossb0ab94b2010-04-08 16:16:20 -0700442
443 return links;
Colin Crossb0ab94b2010-04-08 16:16:20 -0700444}
445
David Anderson924858c2019-06-26 17:00:00 -0700446static void RemoveDeviceMapperLinks(const std::string& devpath) {
447 std::vector<std::string> dirs = {
448 "/dev/block/mapper",
449 "/dev/block/mapper/by-uuid",
450 };
451 for (const auto& dir : dirs) {
452 if (access(dir.c_str(), F_OK) != 0) continue;
453
454 std::unique_ptr<DIR, decltype(&closedir)> dh(opendir(dir.c_str()), closedir);
455 if (!dh) {
456 PLOG(ERROR) << "Failed to open directory " << dir;
457 continue;
458 }
459
460 struct dirent* dp;
461 std::string link_path;
462 while ((dp = readdir(dh.get())) != nullptr) {
463 if (dp->d_type != DT_LNK) continue;
464
465 auto path = dir + "/" + dp->d_name;
466 if (Readlink(path, &link_path) && link_path == devpath) {
467 unlink(path.c_str());
468 }
469 }
470 }
471}
472
Tom Cherryb4dd8812017-06-23 12:43:48 -0700473void DeviceHandler::HandleDevice(const std::string& action, const std::string& devpath, bool block,
Tom Cherryed506f72017-05-25 15:58:59 -0700474 int major, int minor, const std::vector<std::string>& links) const {
Tom Cherrye3e48212017-04-11 13:53:37 -0700475 if (action == "add") {
Tom Cherryed506f72017-05-25 15:58:59 -0700476 MakeDevice(devpath, block, major, minor, links);
David Anderson924858c2019-06-26 17:00:00 -0700477 }
478
David Andersond6bf86b2022-12-08 09:53:03 -0800479 // Handle device-mapper nodes.
480 // On kernels <= 5.10, the "add" event is fired on DM_DEV_CREATE, but does not contain name
481 // information until DM_TABLE_LOAD - thus, we wait for a "change" event.
482 // On kernels >= 5.15, the "add" event is fired on DM_TABLE_LOAD, followed by a "change"
483 // event.
David Anderson924858c2019-06-26 17:00:00 -0700484 if (action == "add" || (action == "change" && StartsWith(devpath, "/dev/block/dm-"))) {
Tom Cherry2e344f92017-04-04 17:53:45 -0700485 for (const auto& link : links) {
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700486 if (!mkdir_recursive(Dirname(link), 0755)) {
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700487 PLOG(ERROR) << "Failed to create directory " << Dirname(link);
Tom Cherryed506f72017-05-25 15:58:59 -0700488 }
489
Bowgo Tsai8eec38f2018-05-16 18:33:44 +0800490 if (symlink(devpath.c_str(), link.c_str())) {
491 if (errno != EEXIST) {
492 PLOG(ERROR) << "Failed to symlink " << devpath << " to " << link;
493 } else if (std::string link_path;
494 Readlink(link, &link_path) && link_path != devpath) {
495 PLOG(ERROR) << "Failed to symlink " << devpath << " to " << link
496 << ", which already links to: " << link_path;
497 }
Tom Cherryed506f72017-05-25 15:58:59 -0700498 }
Colin Crossb0ab94b2010-04-08 16:16:20 -0700499 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700500 }
501
Tom Cherrye3e48212017-04-11 13:53:37 -0700502 if (action == "remove") {
David Anderson924858c2019-06-26 17:00:00 -0700503 if (StartsWith(devpath, "/dev/block/dm-")) {
504 RemoveDeviceMapperLinks(devpath);
505 }
Tom Cherry2e344f92017-04-04 17:53:45 -0700506 for (const auto& link : links) {
Tom Cherryed506f72017-05-25 15:58:59 -0700507 std::string link_path;
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700508 if (Readlink(link, &link_path) && link_path == devpath) {
Tom Cherryed506f72017-05-25 15:58:59 -0700509 unlink(link.c_str());
510 }
Colin Crossb0ab94b2010-04-08 16:16:20 -0700511 }
Tom Cherrye3e48212017-04-11 13:53:37 -0700512 unlink(devpath.c_str());
Colin Crossb0ab94b2010-04-08 16:16:20 -0700513 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700514}
515
Tri Voff89b8d2019-09-24 13:00:43 -0700516void DeviceHandler::HandleAshmemUevent(const Uevent& uevent) {
517 if (uevent.device_name == "ashmem") {
518 static const std::string boot_id_path = "/proc/sys/kernel/random/boot_id";
519 std::string boot_id;
520 if (!ReadFileToString(boot_id_path, &boot_id)) {
521 PLOG(ERROR) << "Cannot duplicate ashmem device node. Failed to read " << boot_id_path;
522 return;
523 };
524 boot_id = Trim(boot_id);
525
526 Uevent dup_ashmem_uevent = uevent;
527 dup_ashmem_uevent.device_name += boot_id;
528 dup_ashmem_uevent.path += boot_id;
529 HandleUevent(dup_ashmem_uevent);
530 }
531}
532
Tom Cherry457e28f2018-08-01 13:12:20 -0700533void DeviceHandler::HandleUevent(const Uevent& uevent) {
Sriharsha Allenkie6094782020-11-10 11:44:59 +0530534 if (uevent.action == "add" || uevent.action == "change" ||
535 uevent.action == "bind" || uevent.action == "online") {
536 FixupSysPermissions(uevent.path, uevent.subsystem);
537 }
Colin Crosseb5ba832011-03-30 17:37:17 -0700538
Tom Cherry3fa46732017-04-11 14:19:50 -0700539 // if it's not a /dev device, nothing to do
Tom Cherryed506f72017-05-25 15:58:59 -0700540 if (uevent.major < 0 || uevent.minor < 0) return;
Greg Hackmann3312aa82013-11-18 15:24:40 -0800541
Tom Cherry3fa46732017-04-11 14:19:50 -0700542 std::string devpath;
Tom Cherryb4dd8812017-06-23 12:43:48 -0700543 std::vector<std::string> links;
544 bool block = false;
Greg Hackmann3312aa82013-11-18 15:24:40 -0800545
Tom Cherryb4dd8812017-06-23 12:43:48 -0700546 if (uevent.subsystem == "block") {
547 block = true;
548 devpath = "/dev/block/" + Basename(uevent.path);
549
550 if (StartsWith(uevent.path, "/devices")) {
551 links = GetBlockDeviceSymlinks(uevent);
552 }
Tom Cherryed506f72017-05-25 15:58:59 -0700553 } else if (const auto subsystem =
554 std::find(subsystems_.cbegin(), subsystems_.cend(), uevent.subsystem);
555 subsystem != subsystems_.cend()) {
Tom Cherryfe062052017-04-24 16:59:05 -0700556 devpath = subsystem->ParseDevPath(uevent);
Tom Cherry9c8d6dd2017-08-17 09:38:01 -0700557 } else if (uevent.subsystem == "usb") {
558 if (!uevent.device_name.empty()) {
559 devpath = "/dev/" + uevent.device_name;
560 } else {
561 // This imitates the file system that would be created
562 // if we were using devfs instead.
563 // Minors are broken up into groups of 128, starting at "001"
564 int bus_id = uevent.minor / 128 + 1;
565 int device_id = uevent.minor % 128 + 1;
566 devpath = StringPrintf("/dev/bus/usb/%03d/%03d", bus_id, device_id);
567 }
568 } else if (StartsWith(uevent.subsystem, "usb")) {
569 // ignore other USB events
570 return;
David Anderson515a5bd2020-10-19 19:54:18 -0700571 } else if (uevent.subsystem == "misc" && StartsWith(uevent.device_name, "dm-user/")) {
572 devpath = "/dev/dm-user/" + uevent.device_name.substr(8);
Jakob Vukalovice3774322023-07-11 10:28:53 +0100573 } else if (uevent.subsystem == "misc" && uevent.device_name == "vfio/vfio") {
574 devpath = "/dev/" + uevent.device_name;
Tom Cherry780a71e2017-04-04 16:30:40 -0700575 } else {
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700576 devpath = "/dev/" + Basename(uevent.path);
Tom Cherry780a71e2017-04-04 16:30:40 -0700577 }
Colin Crosseb5ba832011-03-30 17:37:17 -0700578
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700579 mkdir_recursive(Dirname(devpath), 0755);
Tom Cherryfe062052017-04-24 16:59:05 -0700580
Tom Cherryb4dd8812017-06-23 12:43:48 -0700581 HandleDevice(uevent.action, devpath, block, uevent.major, uevent.minor, links);
Tri Voff89b8d2019-09-24 13:00:43 -0700582
583 // Duplicate /dev/ashmem device and name it /dev/ashmem<boot_id>.
584 // TODO(b/111903542): remove once all users of /dev/ashmem are migrated to libcutils API.
585 HandleAshmemUevent(uevent);
Colin Crosseb5ba832011-03-30 17:37:17 -0700586}
587
Tom Cherry457e28f2018-08-01 13:12:20 -0700588void DeviceHandler::ColdbootDone() {
Oleksiy Avramchenkodd5802a2018-11-02 10:06:47 +0100589 skip_restorecon_ = false;
Tom Cherry457e28f2018-08-01 13:12:20 -0700590}
591
Tom Cherryed506f72017-05-25 15:58:59 -0700592DeviceHandler::DeviceHandler(std::vector<Permissions> dev_permissions,
593 std::vector<SysfsPermissions> sysfs_permissions,
Bowgo Tsai8eec38f2018-05-16 18:33:44 +0800594 std::vector<Subsystem> subsystems, std::set<std::string> boot_devices,
595 bool skip_restorecon)
Tom Cherryed506f72017-05-25 15:58:59 -0700596 : dev_permissions_(std::move(dev_permissions)),
597 sysfs_permissions_(std::move(sysfs_permissions)),
598 subsystems_(std::move(subsystems)),
Bowgo Tsai8eec38f2018-05-16 18:33:44 +0800599 boot_devices_(std::move(boot_devices)),
Sandeep Patilcd2ba0d2017-06-21 12:46:41 -0700600 skip_restorecon_(skip_restorecon),
601 sysfs_mount_point_("/sys") {}
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700602
Tom Cherryed506f72017-05-25 15:58:59 -0700603DeviceHandler::DeviceHandler()
604 : DeviceHandler(std::vector<Permissions>{}, std::vector<SysfsPermissions>{},
Bowgo Tsai8eec38f2018-05-16 18:33:44 +0800605 std::vector<Subsystem>{}, std::set<std::string>{}, false) {}
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700606
607} // namespace init
608} // namespace android