blob: 01957eff06f80dc4367f266d5e9096162b44a5bb [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>
Suchang Woo7d8c25b2021-12-20 13:23:28 +090036#include <android-base/properties.h>
Jooyung Han21cad322020-09-18 14:41:22 +090037#include <android-base/scopeguard.h>
Tom Cherrydcb3d152019-08-07 16:02:28 -070038#include <android-base/strings.h>
Tom Cherryed506f72017-05-25 15:58:59 -070039#include <android-base/unique_fd.h>
40
Tom Cherrydcb3d152019-08-07 16:02:28 -070041using android::base::ReadFdToString;
42using android::base::Socketpair;
43using android::base::Split;
Tom Cherryede0d532017-07-06 14:20:11 -070044using android::base::Timer;
Tom Cherrydcb3d152019-08-07 16:02:28 -070045using android::base::Trim;
Tom Cherry81f5d3e2017-06-22 12:53:17 -070046using android::base::unique_fd;
Suchang Woo7d8c25b2021-12-20 13:23:28 +090047using android::base::WaitForProperty;
Tom Cherry81f5d3e2017-06-22 12:53:17 -070048using android::base::WriteFully;
49
50namespace android {
51namespace init {
52
Suchang Woo22fdd0a2021-04-06 11:22:49 +090053namespace {
54bool PrefixMatch(const std::string& pattern, const std::string& path) {
55 return android::base::StartsWith(path, pattern);
56}
57
58bool FnMatch(const std::string& pattern, const std::string& path) {
59 return fnmatch(pattern.c_str(), path.c_str(), 0) == 0;
60}
61
62bool EqualMatch(const std::string& pattern, const std::string& path) {
63 return pattern == path;
64}
65} // namespace
66
Tom Cherrydcb3d152019-08-07 16:02:28 -070067static void LoadFirmware(const std::string& firmware, const std::string& root, int fw_fd,
68 size_t fw_size, int loading_fd, int data_fd) {
Tom Cherryed506f72017-05-25 15:58:59 -070069 // Start transfer.
Tom Cherry81f5d3e2017-06-22 12:53:17 -070070 WriteFully(loading_fd, "1", 1);
Tom Cherryed506f72017-05-25 15:58:59 -070071
72 // Copy the firmware.
73 int rc = sendfile(data_fd, fw_fd, nullptr, fw_size);
74 if (rc == -1) {
Tom Cherrydcb3d152019-08-07 16:02:28 -070075 PLOG(ERROR) << "firmware: sendfile failed { '" << root << "', '" << firmware << "' }";
Tom Cherryed506f72017-05-25 15:58:59 -070076 }
77
78 // Tell the firmware whether to abort or commit.
79 const char* response = (rc != -1) ? "0" : "-1";
Tom Cherry81f5d3e2017-06-22 12:53:17 -070080 WriteFully(loading_fd, response, strlen(response));
Tom Cherryed506f72017-05-25 15:58:59 -070081}
82
83static bool IsBooting() {
84 return access("/dev/.booting", F_OK) == 0;
85}
86
Suchang Woo7d8c25b2021-12-20 13:23:28 +090087static bool IsApexActivated() {
88 static bool apex_activated = []() {
89 // Wait for com.android.runtime.apex activation
90 // Property name and value must be kept in sync with system/apexd/apex/apex_constants.h
91 // 60s is the default firmware sysfs fallback timeout. (/sys/class/firmware/timeout)
92 if (!WaitForProperty("apexd.status", "activated", 60s)) {
93 LOG(ERROR) << "Apexd activation wait timeout";
94 return false;
95 }
96 return true;
97 }();
98
99 return apex_activated;
100}
101
102static bool NeedsRerunExternalHandler() {
103 static bool first = true;
104
105 // Rerun external handler only on the first try and when apex is activated
106 if (first) {
107 first = false;
108 return IsApexActivated();
109 }
110
111 return first;
112}
113
Suchang Woo10c63742021-05-13 18:56:31 +0900114ExternalFirmwareHandler::ExternalFirmwareHandler(std::string devpath, uid_t uid, gid_t gid,
Suchang Woo22fdd0a2021-04-06 11:22:49 +0900115 std::string handler_path)
Suchang Woo10c63742021-05-13 18:56:31 +0900116 : devpath(std::move(devpath)), uid(uid), gid(gid), handler_path(std::move(handler_path)) {
Suchang Woo22fdd0a2021-04-06 11:22:49 +0900117 auto wildcard_position = this->devpath.find('*');
118 if (wildcard_position != std::string::npos) {
119 if (wildcard_position == this->devpath.length() - 1) {
120 this->devpath.pop_back();
121 match = std::bind(PrefixMatch, this->devpath, std::placeholders::_1);
122 } else {
123 match = std::bind(FnMatch, this->devpath, std::placeholders::_1);
124 }
125 } else {
126 match = std::bind(EqualMatch, this->devpath, std::placeholders::_1);
127 }
128}
129
Suchang Woo10c63742021-05-13 18:56:31 +0900130ExternalFirmwareHandler::ExternalFirmwareHandler(std::string devpath, uid_t uid,
131 std::string handler_path)
132 : ExternalFirmwareHandler(devpath, uid, 0, handler_path) {}
133
Tom Cherrydcb3d152019-08-07 16:02:28 -0700134FirmwareHandler::FirmwareHandler(std::vector<std::string> firmware_directories,
135 std::vector<ExternalFirmwareHandler> external_firmware_handlers)
136 : firmware_directories_(std::move(firmware_directories)),
137 external_firmware_handlers_(std::move(external_firmware_handlers)) {}
Tom Cherry457e28f2018-08-01 13:12:20 -0700138
Tom Cherrydcb3d152019-08-07 16:02:28 -0700139Result<std::string> FirmwareHandler::RunExternalHandler(const std::string& handler, uid_t uid,
Suchang Woo10c63742021-05-13 18:56:31 +0900140 gid_t gid, const Uevent& uevent) const {
Tom Cherrydcb3d152019-08-07 16:02:28 -0700141 unique_fd child_stdout;
142 unique_fd parent_stdout;
143 if (!Socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, &child_stdout, &parent_stdout)) {
144 return ErrnoError() << "Socketpair() for stdout failed";
145 }
Tom Cherryed506f72017-05-25 15:58:59 -0700146
Tom Cherrydcb3d152019-08-07 16:02:28 -0700147 unique_fd child_stderr;
148 unique_fd parent_stderr;
149 if (!Socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, &child_stderr, &parent_stderr)) {
150 return ErrnoError() << "Socketpair() for stderr failed";
151 }
152
153 signal(SIGCHLD, SIG_DFL);
154
155 auto pid = fork();
156 if (pid < 0) {
157 return ErrnoError() << "fork() failed";
158 }
159
160 if (pid == 0) {
161 setenv("FIRMWARE", uevent.firmware.c_str(), 1);
162 setenv("DEVPATH", uevent.path.c_str(), 1);
163 parent_stdout.reset();
164 parent_stderr.reset();
165 close(STDOUT_FILENO);
166 close(STDERR_FILENO);
167 dup2(child_stdout.get(), STDOUT_FILENO);
168 dup2(child_stderr.get(), STDERR_FILENO);
169
170 auto args = Split(handler, " ");
171 std::vector<char*> c_args;
172 for (auto& arg : args) {
173 c_args.emplace_back(arg.data());
174 }
175 c_args.emplace_back(nullptr);
176
Suchang Woo10c63742021-05-13 18:56:31 +0900177 if (gid != 0) {
178 if (setgid(gid) != 0) {
179 fprintf(stderr, "setgid() failed: %s", strerror(errno));
180 _exit(EXIT_FAILURE);
181 }
182 }
183
Tom Cherrydcb3d152019-08-07 16:02:28 -0700184 if (setuid(uid) != 0) {
185 fprintf(stderr, "setuid() failed: %s", strerror(errno));
186 _exit(EXIT_FAILURE);
187 }
188
189 execv(c_args[0], c_args.data());
190 fprintf(stderr, "exec() failed: %s", strerror(errno));
191 _exit(EXIT_FAILURE);
192 }
193
194 child_stdout.reset();
195 child_stderr.reset();
196
197 int status;
198 pid_t waited_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
199 if (waited_pid == -1) {
200 return ErrnoError() << "waitpid() failed";
201 }
202
203 std::string stdout_content;
204 if (!ReadFdToString(parent_stdout.get(), &stdout_content)) {
205 return ErrnoError() << "ReadFdToString() for stdout failed";
206 }
207
208 std::string stderr_content;
209 if (ReadFdToString(parent_stderr.get(), &stderr_content)) {
210 auto messages = Split(stderr_content, "\n");
211 for (const auto& message : messages) {
212 if (!message.empty()) {
213 LOG(ERROR) << "External Firmware Handler: " << message;
214 }
215 }
216 } else {
217 LOG(ERROR) << "ReadFdToString() for stderr failed";
218 }
219
220 if (WIFEXITED(status)) {
221 if (WEXITSTATUS(status) == EXIT_SUCCESS) {
222 return Trim(stdout_content);
223 } else {
224 return Error() << "exited with status " << WEXITSTATUS(status);
225 }
226 } else if (WIFSIGNALED(status)) {
227 return Error() << "killed by signal " << WTERMSIG(status);
228 }
229
230 return Error() << "unexpected exit status " << status;
231}
232
233std::string FirmwareHandler::GetFirmwarePath(const Uevent& uevent) const {
234 for (const auto& external_handler : external_firmware_handlers_) {
Suchang Woo22fdd0a2021-04-06 11:22:49 +0900235 if (external_handler.match(uevent.path)) {
Tom Cherrydcb3d152019-08-07 16:02:28 -0700236 LOG(INFO) << "Launching external firmware handler '" << external_handler.handler_path
237 << "' for devpath: '" << uevent.path << "' firmware: '" << uevent.firmware
238 << "'";
239
Suchang Woo10c63742021-05-13 18:56:31 +0900240 auto result = RunExternalHandler(external_handler.handler_path, external_handler.uid,
241 external_handler.gid, uevent);
Suchang Woo7d8c25b2021-12-20 13:23:28 +0900242 if (!result.ok() && NeedsRerunExternalHandler()) {
243 auto res = RunExternalHandler(external_handler.handler_path, external_handler.uid,
244 external_handler.gid, uevent);
245 result = std::move(res);
246 }
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900247 if (!result.ok()) {
Tom Cherrydcb3d152019-08-07 16:02:28 -0700248 LOG(ERROR) << "Using default firmware; External firmware handler failed: "
249 << result.error();
250 return uevent.firmware;
251 }
252 if (result->find("..") != std::string::npos) {
253 LOG(ERROR) << "Using default firmware; External firmware handler provided an "
254 "invalid path, '"
255 << *result << "'";
256 return uevent.firmware;
257 }
258 LOG(INFO) << "Loading firmware '" << *result << "' in place of '" << uevent.firmware
259 << "'";
260 return *result;
261 }
262 }
Tom Cherryed506f72017-05-25 15:58:59 -0700263 LOG(INFO) << "firmware: loading '" << uevent.firmware << "' for '" << uevent.path << "'";
Tom Cherrydcb3d152019-08-07 16:02:28 -0700264 return uevent.firmware;
265}
Tom Cherryed506f72017-05-25 15:58:59 -0700266
Luca Stefani3e4159a2024-04-05 10:22:34 +0200267void FirmwareHandler::ProcessFirmwareEvent(const std::string& path,
Tom Cherrydcb3d152019-08-07 16:02:28 -0700268 const std::string& firmware) const {
Luca Stefani3e4159a2024-04-05 10:22:34 +0200269 std::string root = "/sys" + path;
Tom Cherryed506f72017-05-25 15:58:59 -0700270 std::string loading = root + "/loading";
271 std::string data = root + "/data";
272
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700273 unique_fd loading_fd(open(loading.c_str(), O_WRONLY | O_CLOEXEC));
Tom Cherryed506f72017-05-25 15:58:59 -0700274 if (loading_fd == -1) {
Tom Cherrydcb3d152019-08-07 16:02:28 -0700275 PLOG(ERROR) << "couldn't open firmware loading fd for " << firmware;
Tom Cherryed506f72017-05-25 15:58:59 -0700276 return;
277 }
278
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700279 unique_fd data_fd(open(data.c_str(), O_WRONLY | O_CLOEXEC));
Tom Cherryed506f72017-05-25 15:58:59 -0700280 if (data_fd == -1) {
Tom Cherrydcb3d152019-08-07 16:02:28 -0700281 PLOG(ERROR) << "couldn't open firmware data fd for " << firmware;
Tom Cherryed506f72017-05-25 15:58:59 -0700282 return;
283 }
284
Tom Cherryd38aafd2019-05-23 16:26:57 -0700285 std::vector<std::string> attempted_paths_and_errors;
Jooyung Han21cad322020-09-18 14:41:22 +0900286 auto TryLoadFirmware = [&](const std::string& firmware_directory) {
Tom Cherrydcb3d152019-08-07 16:02:28 -0700287 std::string file = firmware_directory + firmware;
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700288 unique_fd fw_fd(open(file.c_str(), O_RDONLY | O_CLOEXEC));
Tom Cherryd38aafd2019-05-23 16:26:57 -0700289 if (fw_fd == -1) {
290 attempted_paths_and_errors.emplace_back("firmware: attempted " + file +
291 ", open failed: " + strerror(errno));
Jooyung Han21cad322020-09-18 14:41:22 +0900292 return false;
Tom Cherryed506f72017-05-25 15:58:59 -0700293 }
Tom Cherryd38aafd2019-05-23 16:26:57 -0700294 struct stat sb;
Bart Van Asscheaee2ec82022-12-02 18:48:15 -0800295 if (fstat(fw_fd.get(), &sb) == -1) {
Tom Cherryd38aafd2019-05-23 16:26:57 -0700296 attempted_paths_and_errors.emplace_back("firmware: attempted " + file +
297 ", fstat failed: " + strerror(errno));
Jooyung Han21cad322020-09-18 14:41:22 +0900298 return false;
Tom Cherryd38aafd2019-05-23 16:26:57 -0700299 }
Luca Stefani3e4159a2024-04-05 10:22:34 +0200300 LOG(INFO) << "found " << file << " for " << path;
Bart Van Asscheaee2ec82022-12-02 18:48:15 -0800301 LoadFirmware(firmware, root, fw_fd.get(), sb.st_size, loading_fd.get(), data_fd.get());
Jooyung Han21cad322020-09-18 14:41:22 +0900302 return true;
303 };
304
305 int booting = IsBooting();
306try_loading_again:
307 attempted_paths_and_errors.clear();
308 if (ForEachFirmwareDirectory(TryLoadFirmware)) {
Tom Cherryd38aafd2019-05-23 16:26:57 -0700309 return;
Tom Cherryed506f72017-05-25 15:58:59 -0700310 }
311
312 if (booting) {
313 // If we're not fully booted, we may be missing
314 // filesystems needed for firmware, wait and retry.
315 std::this_thread::sleep_for(100ms);
316 booting = IsBooting();
317 goto try_loading_again;
318 }
319
Tom Cherrydcb3d152019-08-07 16:02:28 -0700320 LOG(ERROR) << "firmware: could not find firmware for " << firmware;
Tom Cherryd38aafd2019-05-23 16:26:57 -0700321 for (const auto& message : attempted_paths_and_errors) {
322 LOG(ERROR) << message;
323 }
Tom Cherryed506f72017-05-25 15:58:59 -0700324
325 // Write "-1" as our response to the kernel's firmware request, since we have nothing for it.
Bart Van Asscheaee2ec82022-12-02 18:48:15 -0800326 write(loading_fd.get(), "-1", 2);
Tom Cherryed506f72017-05-25 15:58:59 -0700327}
328
Jooyung Han21cad322020-09-18 14:41:22 +0900329bool FirmwareHandler::ForEachFirmwareDirectory(
330 std::function<bool(const std::string&)> handler) const {
331 for (const std::string& firmware_directory : firmware_directories_) {
332 if (std::invoke(handler, firmware_directory)) {
333 return true;
334 }
335 }
336
337 glob_t glob_result;
Jooyung Han2833e5d2020-09-21 10:56:10 +0900338 glob("/apex/*/etc/firmware/", GLOB_MARK, nullptr, &glob_result);
Jooyung Han21cad322020-09-18 14:41:22 +0900339 auto free_glob = android::base::make_scope_guard(std::bind(&globfree, &glob_result));
340 for (size_t i = 0; i < glob_result.gl_pathc; i++) {
341 char* apex_firmware_directory = glob_result.gl_pathv[i];
342 // Filter-out /apex/<name>@<ver> paths. The paths are bind-mounted to
343 // /apex/<name> paths, so unless we filter them out, we will look into the
344 // same apex twice.
345 if (strchr(apex_firmware_directory, '@')) {
346 continue;
347 }
348 if (std::invoke(handler, apex_firmware_directory)) {
349 return true;
350 }
351 }
352
353 return false;
354}
355
Tom Cherry457e28f2018-08-01 13:12:20 -0700356void FirmwareHandler::HandleUevent(const Uevent& uevent) {
Tom Cherryed506f72017-05-25 15:58:59 -0700357 if (uevent.subsystem != "firmware" || uevent.action != "add") return;
358
359 // Loading the firmware in a child means we can do that in parallel...
Tom Cherry0f296e02017-06-30 12:58:39 -0700360 auto pid = fork();
Tom Cherryc5833052017-05-16 15:35:41 -0700361 if (pid == -1) {
Tom Cherryed506f72017-05-25 15:58:59 -0700362 PLOG(ERROR) << "could not fork to process firmware event for " << uevent.firmware;
363 }
Tom Cherryc5833052017-05-16 15:35:41 -0700364 if (pid == 0) {
Tom Cherry0f296e02017-06-30 12:58:39 -0700365 Timer t;
Tom Cherrydcb3d152019-08-07 16:02:28 -0700366 auto firmware = GetFirmwarePath(uevent);
Luca Stefani3e4159a2024-04-05 10:22:34 +0200367 ProcessFirmwareEvent(uevent.path, firmware);
Tom Cherry0f296e02017-06-30 12:58:39 -0700368 LOG(INFO) << "loading " << uevent.path << " took " << t;
Tom Cherryc5833052017-05-16 15:35:41 -0700369 _exit(EXIT_SUCCESS);
370 }
Tom Cherryed506f72017-05-25 15:58:59 -0700371}
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700372
373} // namespace init
374} // namespace android