blob: bdc2922752ef8e2804bd00ae2a2e1385aacc8053 [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>
Tom Cherrydcb3d152019-08-07 16:02:28 -070022#include <pwd.h>
23#include <signal.h>
24#include <stdlib.h>
25#include <string.h>
Tom Cherryed506f72017-05-25 15:58:59 -070026#include <sys/sendfile.h>
Tom Cherryc5833052017-05-16 15:35:41 -070027#include <sys/wait.h>
Tom Cherryed506f72017-05-25 15:58:59 -070028#include <unistd.h>
29
Tom Cherryed506f72017-05-25 15:58:59 -070030#include <thread>
31
Tom Cherryede0d532017-07-06 14:20:11 -070032#include <android-base/chrono_utils.h>
Tom Cherryed506f72017-05-25 15:58:59 -070033#include <android-base/file.h>
34#include <android-base/logging.h>
Jooyung Han21cad322020-09-18 14:41:22 +090035#include <android-base/scopeguard.h>
Tom Cherrydcb3d152019-08-07 16:02:28 -070036#include <android-base/strings.h>
Tom Cherryed506f72017-05-25 15:58:59 -070037#include <android-base/unique_fd.h>
38
Tom Cherrydcb3d152019-08-07 16:02:28 -070039using android::base::ReadFdToString;
40using android::base::Socketpair;
41using android::base::Split;
Tom Cherryede0d532017-07-06 14:20:11 -070042using android::base::Timer;
Tom Cherrydcb3d152019-08-07 16:02:28 -070043using android::base::Trim;
Tom Cherry81f5d3e2017-06-22 12:53:17 -070044using android::base::unique_fd;
45using android::base::WriteFully;
46
47namespace android {
48namespace init {
49
Suchang Woo22fdd0a2021-04-06 11:22:49 +090050namespace {
51bool PrefixMatch(const std::string& pattern, const std::string& path) {
52 return android::base::StartsWith(path, pattern);
53}
54
55bool FnMatch(const std::string& pattern, const std::string& path) {
56 return fnmatch(pattern.c_str(), path.c_str(), 0) == 0;
57}
58
59bool EqualMatch(const std::string& pattern, const std::string& path) {
60 return pattern == path;
61}
62} // namespace
63
Tom Cherrydcb3d152019-08-07 16:02:28 -070064static void LoadFirmware(const std::string& firmware, const std::string& root, int fw_fd,
65 size_t fw_size, int loading_fd, int data_fd) {
Tom Cherryed506f72017-05-25 15:58:59 -070066 // Start transfer.
Tom Cherry81f5d3e2017-06-22 12:53:17 -070067 WriteFully(loading_fd, "1", 1);
Tom Cherryed506f72017-05-25 15:58:59 -070068
69 // Copy the firmware.
70 int rc = sendfile(data_fd, fw_fd, nullptr, fw_size);
71 if (rc == -1) {
Tom Cherrydcb3d152019-08-07 16:02:28 -070072 PLOG(ERROR) << "firmware: sendfile failed { '" << root << "', '" << firmware << "' }";
Tom Cherryed506f72017-05-25 15:58:59 -070073 }
74
75 // Tell the firmware whether to abort or commit.
76 const char* response = (rc != -1) ? "0" : "-1";
Tom Cherry81f5d3e2017-06-22 12:53:17 -070077 WriteFully(loading_fd, response, strlen(response));
Tom Cherryed506f72017-05-25 15:58:59 -070078}
79
80static bool IsBooting() {
81 return access("/dev/.booting", F_OK) == 0;
82}
83
Suchang Woo22fdd0a2021-04-06 11:22:49 +090084ExternalFirmwareHandler::ExternalFirmwareHandler(std::string devpath, uid_t uid,
85 std::string handler_path)
86 : devpath(std::move(devpath)), uid(uid), handler_path(std::move(handler_path)) {
87 auto wildcard_position = this->devpath.find('*');
88 if (wildcard_position != std::string::npos) {
89 if (wildcard_position == this->devpath.length() - 1) {
90 this->devpath.pop_back();
91 match = std::bind(PrefixMatch, this->devpath, std::placeholders::_1);
92 } else {
93 match = std::bind(FnMatch, this->devpath, std::placeholders::_1);
94 }
95 } else {
96 match = std::bind(EqualMatch, this->devpath, std::placeholders::_1);
97 }
98}
99
Tom Cherrydcb3d152019-08-07 16:02:28 -0700100FirmwareHandler::FirmwareHandler(std::vector<std::string> firmware_directories,
101 std::vector<ExternalFirmwareHandler> external_firmware_handlers)
102 : firmware_directories_(std::move(firmware_directories)),
103 external_firmware_handlers_(std::move(external_firmware_handlers)) {}
Tom Cherry457e28f2018-08-01 13:12:20 -0700104
Tom Cherrydcb3d152019-08-07 16:02:28 -0700105Result<std::string> FirmwareHandler::RunExternalHandler(const std::string& handler, uid_t uid,
106 const Uevent& uevent) const {
107 unique_fd child_stdout;
108 unique_fd parent_stdout;
109 if (!Socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, &child_stdout, &parent_stdout)) {
110 return ErrnoError() << "Socketpair() for stdout failed";
111 }
Tom Cherryed506f72017-05-25 15:58:59 -0700112
Tom Cherrydcb3d152019-08-07 16:02:28 -0700113 unique_fd child_stderr;
114 unique_fd parent_stderr;
115 if (!Socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, &child_stderr, &parent_stderr)) {
116 return ErrnoError() << "Socketpair() for stderr failed";
117 }
118
119 signal(SIGCHLD, SIG_DFL);
120
121 auto pid = fork();
122 if (pid < 0) {
123 return ErrnoError() << "fork() failed";
124 }
125
126 if (pid == 0) {
127 setenv("FIRMWARE", uevent.firmware.c_str(), 1);
128 setenv("DEVPATH", uevent.path.c_str(), 1);
129 parent_stdout.reset();
130 parent_stderr.reset();
131 close(STDOUT_FILENO);
132 close(STDERR_FILENO);
133 dup2(child_stdout.get(), STDOUT_FILENO);
134 dup2(child_stderr.get(), STDERR_FILENO);
135
136 auto args = Split(handler, " ");
137 std::vector<char*> c_args;
138 for (auto& arg : args) {
139 c_args.emplace_back(arg.data());
140 }
141 c_args.emplace_back(nullptr);
142
143 if (setuid(uid) != 0) {
144 fprintf(stderr, "setuid() failed: %s", strerror(errno));
145 _exit(EXIT_FAILURE);
146 }
147
148 execv(c_args[0], c_args.data());
149 fprintf(stderr, "exec() failed: %s", strerror(errno));
150 _exit(EXIT_FAILURE);
151 }
152
153 child_stdout.reset();
154 child_stderr.reset();
155
156 int status;
157 pid_t waited_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
158 if (waited_pid == -1) {
159 return ErrnoError() << "waitpid() failed";
160 }
161
162 std::string stdout_content;
163 if (!ReadFdToString(parent_stdout.get(), &stdout_content)) {
164 return ErrnoError() << "ReadFdToString() for stdout failed";
165 }
166
167 std::string stderr_content;
168 if (ReadFdToString(parent_stderr.get(), &stderr_content)) {
169 auto messages = Split(stderr_content, "\n");
170 for (const auto& message : messages) {
171 if (!message.empty()) {
172 LOG(ERROR) << "External Firmware Handler: " << message;
173 }
174 }
175 } else {
176 LOG(ERROR) << "ReadFdToString() for stderr failed";
177 }
178
179 if (WIFEXITED(status)) {
180 if (WEXITSTATUS(status) == EXIT_SUCCESS) {
181 return Trim(stdout_content);
182 } else {
183 return Error() << "exited with status " << WEXITSTATUS(status);
184 }
185 } else if (WIFSIGNALED(status)) {
186 return Error() << "killed by signal " << WTERMSIG(status);
187 }
188
189 return Error() << "unexpected exit status " << status;
190}
191
192std::string FirmwareHandler::GetFirmwarePath(const Uevent& uevent) const {
193 for (const auto& external_handler : external_firmware_handlers_) {
Suchang Woo22fdd0a2021-04-06 11:22:49 +0900194 if (external_handler.match(uevent.path)) {
Tom Cherrydcb3d152019-08-07 16:02:28 -0700195 LOG(INFO) << "Launching external firmware handler '" << external_handler.handler_path
196 << "' for devpath: '" << uevent.path << "' firmware: '" << uevent.firmware
197 << "'";
198
199 auto result =
200 RunExternalHandler(external_handler.handler_path, external_handler.uid, uevent);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900201 if (!result.ok()) {
Tom Cherrydcb3d152019-08-07 16:02:28 -0700202 LOG(ERROR) << "Using default firmware; External firmware handler failed: "
203 << result.error();
204 return uevent.firmware;
205 }
206 if (result->find("..") != std::string::npos) {
207 LOG(ERROR) << "Using default firmware; External firmware handler provided an "
208 "invalid path, '"
209 << *result << "'";
210 return uevent.firmware;
211 }
212 LOG(INFO) << "Loading firmware '" << *result << "' in place of '" << uevent.firmware
213 << "'";
214 return *result;
215 }
216 }
Tom Cherryed506f72017-05-25 15:58:59 -0700217 LOG(INFO) << "firmware: loading '" << uevent.firmware << "' for '" << uevent.path << "'";
Tom Cherrydcb3d152019-08-07 16:02:28 -0700218 return uevent.firmware;
219}
Tom Cherryed506f72017-05-25 15:58:59 -0700220
Tom Cherrydcb3d152019-08-07 16:02:28 -0700221void FirmwareHandler::ProcessFirmwareEvent(const std::string& root,
222 const std::string& firmware) const {
Tom Cherryed506f72017-05-25 15:58:59 -0700223 std::string loading = root + "/loading";
224 std::string data = root + "/data";
225
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700226 unique_fd loading_fd(open(loading.c_str(), O_WRONLY | O_CLOEXEC));
Tom Cherryed506f72017-05-25 15:58:59 -0700227 if (loading_fd == -1) {
Tom Cherrydcb3d152019-08-07 16:02:28 -0700228 PLOG(ERROR) << "couldn't open firmware loading fd for " << firmware;
Tom Cherryed506f72017-05-25 15:58:59 -0700229 return;
230 }
231
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700232 unique_fd data_fd(open(data.c_str(), O_WRONLY | O_CLOEXEC));
Tom Cherryed506f72017-05-25 15:58:59 -0700233 if (data_fd == -1) {
Tom Cherrydcb3d152019-08-07 16:02:28 -0700234 PLOG(ERROR) << "couldn't open firmware data fd for " << firmware;
Tom Cherryed506f72017-05-25 15:58:59 -0700235 return;
236 }
237
Tom Cherryd38aafd2019-05-23 16:26:57 -0700238 std::vector<std::string> attempted_paths_and_errors;
Jooyung Han21cad322020-09-18 14:41:22 +0900239 auto TryLoadFirmware = [&](const std::string& firmware_directory) {
Tom Cherrydcb3d152019-08-07 16:02:28 -0700240 std::string file = firmware_directory + firmware;
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700241 unique_fd fw_fd(open(file.c_str(), O_RDONLY | O_CLOEXEC));
Tom Cherryd38aafd2019-05-23 16:26:57 -0700242 if (fw_fd == -1) {
243 attempted_paths_and_errors.emplace_back("firmware: attempted " + file +
244 ", open failed: " + strerror(errno));
Jooyung Han21cad322020-09-18 14:41:22 +0900245 return false;
Tom Cherryed506f72017-05-25 15:58:59 -0700246 }
Tom Cherryd38aafd2019-05-23 16:26:57 -0700247 struct stat sb;
248 if (fstat(fw_fd, &sb) == -1) {
249 attempted_paths_and_errors.emplace_back("firmware: attempted " + file +
250 ", fstat failed: " + strerror(errno));
Jooyung Han21cad322020-09-18 14:41:22 +0900251 return false;
Tom Cherryd38aafd2019-05-23 16:26:57 -0700252 }
Tom Cherrydcb3d152019-08-07 16:02:28 -0700253 LoadFirmware(firmware, root, fw_fd, sb.st_size, loading_fd, data_fd);
Jooyung Han21cad322020-09-18 14:41:22 +0900254 return true;
255 };
256
257 int booting = IsBooting();
258try_loading_again:
259 attempted_paths_and_errors.clear();
260 if (ForEachFirmwareDirectory(TryLoadFirmware)) {
Tom Cherryd38aafd2019-05-23 16:26:57 -0700261 return;
Tom Cherryed506f72017-05-25 15:58:59 -0700262 }
263
264 if (booting) {
265 // If we're not fully booted, we may be missing
266 // filesystems needed for firmware, wait and retry.
267 std::this_thread::sleep_for(100ms);
268 booting = IsBooting();
269 goto try_loading_again;
270 }
271
Tom Cherrydcb3d152019-08-07 16:02:28 -0700272 LOG(ERROR) << "firmware: could not find firmware for " << firmware;
Tom Cherryd38aafd2019-05-23 16:26:57 -0700273 for (const auto& message : attempted_paths_and_errors) {
274 LOG(ERROR) << message;
275 }
Tom Cherryed506f72017-05-25 15:58:59 -0700276
277 // Write "-1" as our response to the kernel's firmware request, since we have nothing for it.
278 write(loading_fd, "-1", 2);
279}
280
Jooyung Han21cad322020-09-18 14:41:22 +0900281bool FirmwareHandler::ForEachFirmwareDirectory(
282 std::function<bool(const std::string&)> handler) const {
283 for (const std::string& firmware_directory : firmware_directories_) {
284 if (std::invoke(handler, firmware_directory)) {
285 return true;
286 }
287 }
288
289 glob_t glob_result;
Jooyung Han2833e5d2020-09-21 10:56:10 +0900290 glob("/apex/*/etc/firmware/", GLOB_MARK, nullptr, &glob_result);
Jooyung Han21cad322020-09-18 14:41:22 +0900291 auto free_glob = android::base::make_scope_guard(std::bind(&globfree, &glob_result));
292 for (size_t i = 0; i < glob_result.gl_pathc; i++) {
293 char* apex_firmware_directory = glob_result.gl_pathv[i];
294 // Filter-out /apex/<name>@<ver> paths. The paths are bind-mounted to
295 // /apex/<name> paths, so unless we filter them out, we will look into the
296 // same apex twice.
297 if (strchr(apex_firmware_directory, '@')) {
298 continue;
299 }
300 if (std::invoke(handler, apex_firmware_directory)) {
301 return true;
302 }
303 }
304
305 return false;
306}
307
Tom Cherry457e28f2018-08-01 13:12:20 -0700308void FirmwareHandler::HandleUevent(const Uevent& uevent) {
Tom Cherryed506f72017-05-25 15:58:59 -0700309 if (uevent.subsystem != "firmware" || uevent.action != "add") return;
310
311 // Loading the firmware in a child means we can do that in parallel...
Tom Cherry0f296e02017-06-30 12:58:39 -0700312 auto pid = fork();
Tom Cherryc5833052017-05-16 15:35:41 -0700313 if (pid == -1) {
Tom Cherryed506f72017-05-25 15:58:59 -0700314 PLOG(ERROR) << "could not fork to process firmware event for " << uevent.firmware;
315 }
Tom Cherryc5833052017-05-16 15:35:41 -0700316 if (pid == 0) {
Tom Cherry0f296e02017-06-30 12:58:39 -0700317 Timer t;
Tom Cherrydcb3d152019-08-07 16:02:28 -0700318 auto firmware = GetFirmwarePath(uevent);
319 ProcessFirmwareEvent("/sys" + uevent.path, firmware);
Tom Cherry0f296e02017-06-30 12:58:39 -0700320 LOG(INFO) << "loading " << uevent.path << " took " << t;
Tom Cherryc5833052017-05-16 15:35:41 -0700321 _exit(EXIT_SUCCESS);
322 }
Tom Cherryed506f72017-05-25 15:58:59 -0700323}
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700324
325} // namespace init
326} // namespace android