blob: 30e808d9fcd3f988a7b78c1dd6bbcda251e326fc [file] [log] [blame]
Tom Cherryed506f72017-05-25 15:58:59 -07001/*
2 * Copyright (C) 2017 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 "firmware_handler.h"
18
19#include <fcntl.h>
Suchang Woo22fdd0a2021-04-06 11:22:49 +090020#include <fnmatch.h>
Jooyung Han21cad322020-09-18 14:41:22 +090021#include <glob.h>
Suchang Woo10c63742021-05-13 18:56:31 +090022#include <grp.h>
Tom Cherrydcb3d152019-08-07 16:02:28 -070023#include <pwd.h>
24#include <signal.h>
25#include <stdlib.h>
26#include <string.h>
Tom Cherryed506f72017-05-25 15:58:59 -070027#include <sys/sendfile.h>
Tom Cherryc5833052017-05-16 15:35:41 -070028#include <sys/wait.h>
Tom Cherryed506f72017-05-25 15:58:59 -070029#include <unistd.h>
30
Tom Cherryed506f72017-05-25 15:58:59 -070031#include <thread>
32
Tom Cherryede0d532017-07-06 14:20:11 -070033#include <android-base/chrono_utils.h>
Tom Cherryed506f72017-05-25 15:58:59 -070034#include <android-base/file.h>
35#include <android-base/logging.h>
Jooyung Han21cad322020-09-18 14:41:22 +090036#include <android-base/scopeguard.h>
Tom Cherrydcb3d152019-08-07 16:02:28 -070037#include <android-base/strings.h>
Tom Cherryed506f72017-05-25 15:58:59 -070038#include <android-base/unique_fd.h>
39
Tom Cherrydcb3d152019-08-07 16:02:28 -070040using android::base::ReadFdToString;
41using android::base::Socketpair;
42using android::base::Split;
Tom Cherryede0d532017-07-06 14:20:11 -070043using android::base::Timer;
Tom Cherrydcb3d152019-08-07 16:02:28 -070044using android::base::Trim;
Tom Cherry81f5d3e2017-06-22 12:53:17 -070045using android::base::unique_fd;
46using android::base::WriteFully;
47
48namespace android {
49namespace init {
50
Suchang Woo22fdd0a2021-04-06 11:22:49 +090051namespace {
52bool PrefixMatch(const std::string& pattern, const std::string& path) {
53 return android::base::StartsWith(path, pattern);
54}
55
56bool FnMatch(const std::string& pattern, const std::string& path) {
57 return fnmatch(pattern.c_str(), path.c_str(), 0) == 0;
58}
59
60bool EqualMatch(const std::string& pattern, const std::string& path) {
61 return pattern == path;
62}
63} // namespace
64
Tom Cherrydcb3d152019-08-07 16:02:28 -070065static void LoadFirmware(const std::string& firmware, const std::string& root, int fw_fd,
66 size_t fw_size, int loading_fd, int data_fd) {
Tom Cherryed506f72017-05-25 15:58:59 -070067 // Start transfer.
Tom Cherry81f5d3e2017-06-22 12:53:17 -070068 WriteFully(loading_fd, "1", 1);
Tom Cherryed506f72017-05-25 15:58:59 -070069
70 // Copy the firmware.
71 int rc = sendfile(data_fd, fw_fd, nullptr, fw_size);
72 if (rc == -1) {
Tom Cherrydcb3d152019-08-07 16:02:28 -070073 PLOG(ERROR) << "firmware: sendfile failed { '" << root << "', '" << firmware << "' }";
Tom Cherryed506f72017-05-25 15:58:59 -070074 }
75
76 // Tell the firmware whether to abort or commit.
77 const char* response = (rc != -1) ? "0" : "-1";
Tom Cherry81f5d3e2017-06-22 12:53:17 -070078 WriteFully(loading_fd, response, strlen(response));
Tom Cherryed506f72017-05-25 15:58:59 -070079}
80
81static bool IsBooting() {
82 return access("/dev/.booting", F_OK) == 0;
83}
84
Suchang Woo10c63742021-05-13 18:56:31 +090085ExternalFirmwareHandler::ExternalFirmwareHandler(std::string devpath, uid_t uid, gid_t gid,
Suchang Woo22fdd0a2021-04-06 11:22:49 +090086 std::string handler_path)
Suchang Woo10c63742021-05-13 18:56:31 +090087 : devpath(std::move(devpath)), uid(uid), gid(gid), handler_path(std::move(handler_path)) {
Suchang Woo22fdd0a2021-04-06 11:22:49 +090088 auto wildcard_position = this->devpath.find('*');
89 if (wildcard_position != std::string::npos) {
90 if (wildcard_position == this->devpath.length() - 1) {
91 this->devpath.pop_back();
92 match = std::bind(PrefixMatch, this->devpath, std::placeholders::_1);
93 } else {
94 match = std::bind(FnMatch, this->devpath, std::placeholders::_1);
95 }
96 } else {
97 match = std::bind(EqualMatch, this->devpath, std::placeholders::_1);
98 }
99}
100
Suchang Woo10c63742021-05-13 18:56:31 +0900101ExternalFirmwareHandler::ExternalFirmwareHandler(std::string devpath, uid_t uid,
102 std::string handler_path)
103 : ExternalFirmwareHandler(devpath, uid, 0, handler_path) {}
104
Tom Cherrydcb3d152019-08-07 16:02:28 -0700105FirmwareHandler::FirmwareHandler(std::vector<std::string> firmware_directories,
106 std::vector<ExternalFirmwareHandler> external_firmware_handlers)
107 : firmware_directories_(std::move(firmware_directories)),
108 external_firmware_handlers_(std::move(external_firmware_handlers)) {}
Tom Cherry457e28f2018-08-01 13:12:20 -0700109
Tom Cherrydcb3d152019-08-07 16:02:28 -0700110Result<std::string> FirmwareHandler::RunExternalHandler(const std::string& handler, uid_t uid,
Suchang Woo10c63742021-05-13 18:56:31 +0900111 gid_t gid, const Uevent& uevent) const {
Tom Cherrydcb3d152019-08-07 16:02:28 -0700112 unique_fd child_stdout;
113 unique_fd parent_stdout;
114 if (!Socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, &child_stdout, &parent_stdout)) {
115 return ErrnoError() << "Socketpair() for stdout failed";
116 }
Tom Cherryed506f72017-05-25 15:58:59 -0700117
Tom Cherrydcb3d152019-08-07 16:02:28 -0700118 unique_fd child_stderr;
119 unique_fd parent_stderr;
120 if (!Socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, &child_stderr, &parent_stderr)) {
121 return ErrnoError() << "Socketpair() for stderr failed";
122 }
123
124 signal(SIGCHLD, SIG_DFL);
125
126 auto pid = fork();
127 if (pid < 0) {
128 return ErrnoError() << "fork() failed";
129 }
130
131 if (pid == 0) {
132 setenv("FIRMWARE", uevent.firmware.c_str(), 1);
133 setenv("DEVPATH", uevent.path.c_str(), 1);
134 parent_stdout.reset();
135 parent_stderr.reset();
136 close(STDOUT_FILENO);
137 close(STDERR_FILENO);
138 dup2(child_stdout.get(), STDOUT_FILENO);
139 dup2(child_stderr.get(), STDERR_FILENO);
140
141 auto args = Split(handler, " ");
142 std::vector<char*> c_args;
143 for (auto& arg : args) {
144 c_args.emplace_back(arg.data());
145 }
146 c_args.emplace_back(nullptr);
147
Suchang Woo10c63742021-05-13 18:56:31 +0900148 if (gid != 0) {
149 if (setgid(gid) != 0) {
150 fprintf(stderr, "setgid() failed: %s", strerror(errno));
151 _exit(EXIT_FAILURE);
152 }
153 }
154
Tom Cherrydcb3d152019-08-07 16:02:28 -0700155 if (setuid(uid) != 0) {
156 fprintf(stderr, "setuid() failed: %s", strerror(errno));
157 _exit(EXIT_FAILURE);
158 }
159
160 execv(c_args[0], c_args.data());
161 fprintf(stderr, "exec() failed: %s", strerror(errno));
162 _exit(EXIT_FAILURE);
163 }
164
165 child_stdout.reset();
166 child_stderr.reset();
167
168 int status;
169 pid_t waited_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
170 if (waited_pid == -1) {
171 return ErrnoError() << "waitpid() failed";
172 }
173
174 std::string stdout_content;
175 if (!ReadFdToString(parent_stdout.get(), &stdout_content)) {
176 return ErrnoError() << "ReadFdToString() for stdout failed";
177 }
178
179 std::string stderr_content;
180 if (ReadFdToString(parent_stderr.get(), &stderr_content)) {
181 auto messages = Split(stderr_content, "\n");
182 for (const auto& message : messages) {
183 if (!message.empty()) {
184 LOG(ERROR) << "External Firmware Handler: " << message;
185 }
186 }
187 } else {
188 LOG(ERROR) << "ReadFdToString() for stderr failed";
189 }
190
191 if (WIFEXITED(status)) {
192 if (WEXITSTATUS(status) == EXIT_SUCCESS) {
193 return Trim(stdout_content);
194 } else {
195 return Error() << "exited with status " << WEXITSTATUS(status);
196 }
197 } else if (WIFSIGNALED(status)) {
198 return Error() << "killed by signal " << WTERMSIG(status);
199 }
200
201 return Error() << "unexpected exit status " << status;
202}
203
204std::string FirmwareHandler::GetFirmwarePath(const Uevent& uevent) const {
205 for (const auto& external_handler : external_firmware_handlers_) {
Suchang Woo22fdd0a2021-04-06 11:22:49 +0900206 if (external_handler.match(uevent.path)) {
Tom Cherrydcb3d152019-08-07 16:02:28 -0700207 LOG(INFO) << "Launching external firmware handler '" << external_handler.handler_path
208 << "' for devpath: '" << uevent.path << "' firmware: '" << uevent.firmware
209 << "'";
210
Suchang Woo10c63742021-05-13 18:56:31 +0900211 auto result = RunExternalHandler(external_handler.handler_path, external_handler.uid,
212 external_handler.gid, uevent);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900213 if (!result.ok()) {
Tom Cherrydcb3d152019-08-07 16:02:28 -0700214 LOG(ERROR) << "Using default firmware; External firmware handler failed: "
215 << result.error();
216 return uevent.firmware;
217 }
218 if (result->find("..") != std::string::npos) {
219 LOG(ERROR) << "Using default firmware; External firmware handler provided an "
220 "invalid path, '"
221 << *result << "'";
222 return uevent.firmware;
223 }
224 LOG(INFO) << "Loading firmware '" << *result << "' in place of '" << uevent.firmware
225 << "'";
226 return *result;
227 }
228 }
Tom Cherryed506f72017-05-25 15:58:59 -0700229 LOG(INFO) << "firmware: loading '" << uevent.firmware << "' for '" << uevent.path << "'";
Tom Cherrydcb3d152019-08-07 16:02:28 -0700230 return uevent.firmware;
231}
Tom Cherryed506f72017-05-25 15:58:59 -0700232
Tom Cherrydcb3d152019-08-07 16:02:28 -0700233void FirmwareHandler::ProcessFirmwareEvent(const std::string& root,
234 const std::string& firmware) const {
Tom Cherryed506f72017-05-25 15:58:59 -0700235 std::string loading = root + "/loading";
236 std::string data = root + "/data";
237
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700238 unique_fd loading_fd(open(loading.c_str(), O_WRONLY | O_CLOEXEC));
Tom Cherryed506f72017-05-25 15:58:59 -0700239 if (loading_fd == -1) {
Tom Cherrydcb3d152019-08-07 16:02:28 -0700240 PLOG(ERROR) << "couldn't open firmware loading fd for " << firmware;
Tom Cherryed506f72017-05-25 15:58:59 -0700241 return;
242 }
243
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700244 unique_fd data_fd(open(data.c_str(), O_WRONLY | O_CLOEXEC));
Tom Cherryed506f72017-05-25 15:58:59 -0700245 if (data_fd == -1) {
Tom Cherrydcb3d152019-08-07 16:02:28 -0700246 PLOG(ERROR) << "couldn't open firmware data fd for " << firmware;
Tom Cherryed506f72017-05-25 15:58:59 -0700247 return;
248 }
249
Tom Cherryd38aafd2019-05-23 16:26:57 -0700250 std::vector<std::string> attempted_paths_and_errors;
Jooyung Han21cad322020-09-18 14:41:22 +0900251 auto TryLoadFirmware = [&](const std::string& firmware_directory) {
Tom Cherrydcb3d152019-08-07 16:02:28 -0700252 std::string file = firmware_directory + firmware;
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700253 unique_fd fw_fd(open(file.c_str(), O_RDONLY | O_CLOEXEC));
Tom Cherryd38aafd2019-05-23 16:26:57 -0700254 if (fw_fd == -1) {
255 attempted_paths_and_errors.emplace_back("firmware: attempted " + file +
256 ", open failed: " + strerror(errno));
Jooyung Han21cad322020-09-18 14:41:22 +0900257 return false;
Tom Cherryed506f72017-05-25 15:58:59 -0700258 }
Tom Cherryd38aafd2019-05-23 16:26:57 -0700259 struct stat sb;
260 if (fstat(fw_fd, &sb) == -1) {
261 attempted_paths_and_errors.emplace_back("firmware: attempted " + file +
262 ", fstat failed: " + strerror(errno));
Jooyung Han21cad322020-09-18 14:41:22 +0900263 return false;
Tom Cherryd38aafd2019-05-23 16:26:57 -0700264 }
Tom Cherrydcb3d152019-08-07 16:02:28 -0700265 LoadFirmware(firmware, root, fw_fd, sb.st_size, loading_fd, data_fd);
Jooyung Han21cad322020-09-18 14:41:22 +0900266 return true;
267 };
268
269 int booting = IsBooting();
270try_loading_again:
271 attempted_paths_and_errors.clear();
272 if (ForEachFirmwareDirectory(TryLoadFirmware)) {
Tom Cherryd38aafd2019-05-23 16:26:57 -0700273 return;
Tom Cherryed506f72017-05-25 15:58:59 -0700274 }
275
276 if (booting) {
277 // If we're not fully booted, we may be missing
278 // filesystems needed for firmware, wait and retry.
279 std::this_thread::sleep_for(100ms);
280 booting = IsBooting();
281 goto try_loading_again;
282 }
283
Tom Cherrydcb3d152019-08-07 16:02:28 -0700284 LOG(ERROR) << "firmware: could not find firmware for " << firmware;
Tom Cherryd38aafd2019-05-23 16:26:57 -0700285 for (const auto& message : attempted_paths_and_errors) {
286 LOG(ERROR) << message;
287 }
Tom Cherryed506f72017-05-25 15:58:59 -0700288
289 // Write "-1" as our response to the kernel's firmware request, since we have nothing for it.
290 write(loading_fd, "-1", 2);
291}
292
Jooyung Han21cad322020-09-18 14:41:22 +0900293bool FirmwareHandler::ForEachFirmwareDirectory(
294 std::function<bool(const std::string&)> handler) const {
295 for (const std::string& firmware_directory : firmware_directories_) {
296 if (std::invoke(handler, firmware_directory)) {
297 return true;
298 }
299 }
300
301 glob_t glob_result;
Jooyung Han2833e5d2020-09-21 10:56:10 +0900302 glob("/apex/*/etc/firmware/", GLOB_MARK, nullptr, &glob_result);
Jooyung Han21cad322020-09-18 14:41:22 +0900303 auto free_glob = android::base::make_scope_guard(std::bind(&globfree, &glob_result));
304 for (size_t i = 0; i < glob_result.gl_pathc; i++) {
305 char* apex_firmware_directory = glob_result.gl_pathv[i];
306 // Filter-out /apex/<name>@<ver> paths. The paths are bind-mounted to
307 // /apex/<name> paths, so unless we filter them out, we will look into the
308 // same apex twice.
309 if (strchr(apex_firmware_directory, '@')) {
310 continue;
311 }
312 if (std::invoke(handler, apex_firmware_directory)) {
313 return true;
314 }
315 }
316
317 return false;
318}
319
Tom Cherry457e28f2018-08-01 13:12:20 -0700320void FirmwareHandler::HandleUevent(const Uevent& uevent) {
Tom Cherryed506f72017-05-25 15:58:59 -0700321 if (uevent.subsystem != "firmware" || uevent.action != "add") return;
322
323 // Loading the firmware in a child means we can do that in parallel...
Tom Cherry0f296e02017-06-30 12:58:39 -0700324 auto pid = fork();
Tom Cherryc5833052017-05-16 15:35:41 -0700325 if (pid == -1) {
Tom Cherryed506f72017-05-25 15:58:59 -0700326 PLOG(ERROR) << "could not fork to process firmware event for " << uevent.firmware;
327 }
Tom Cherryc5833052017-05-16 15:35:41 -0700328 if (pid == 0) {
Tom Cherry0f296e02017-06-30 12:58:39 -0700329 Timer t;
Tom Cherrydcb3d152019-08-07 16:02:28 -0700330 auto firmware = GetFirmwarePath(uevent);
331 ProcessFirmwareEvent("/sys" + uevent.path, firmware);
Tom Cherry0f296e02017-06-30 12:58:39 -0700332 LOG(INFO) << "loading " << uevent.path << " took " << t;
Tom Cherryc5833052017-05-16 15:35:41 -0700333 _exit(EXIT_SUCCESS);
334 }
Tom Cherryed506f72017-05-25 15:58:59 -0700335}
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700336
337} // namespace init
338} // namespace android