1 /*
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>
20 #include <fnmatch.h>
21 #include <glob.h>
22 #include <pwd.h>
23 #include <signal.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <sys/sendfile.h>
27 #include <sys/wait.h>
28 #include <unistd.h>
29
30 #include <thread>
31
32 #include <android-base/chrono_utils.h>
33 #include <android-base/file.h>
34 #include <android-base/logging.h>
35 #include <android-base/scopeguard.h>
36 #include <android-base/strings.h>
37 #include <android-base/unique_fd.h>
38
39 using android::base::ReadFdToString;
40 using android::base::Socketpair;
41 using android::base::Split;
42 using android::base::Timer;
43 using android::base::Trim;
44 using android::base::unique_fd;
45 using android::base::WriteFully;
46
47 namespace android {
48 namespace init {
49
50 namespace {
PrefixMatch(const std::string & pattern,const std::string & path)51 bool PrefixMatch(const std::string& pattern, const std::string& path) {
52 return android::base::StartsWith(path, pattern);
53 }
54
FnMatch(const std::string & pattern,const std::string & path)55 bool FnMatch(const std::string& pattern, const std::string& path) {
56 return fnmatch(pattern.c_str(), path.c_str(), 0) == 0;
57 }
58
EqualMatch(const std::string & pattern,const std::string & path)59 bool EqualMatch(const std::string& pattern, const std::string& path) {
60 return pattern == path;
61 }
62 } // namespace
63
LoadFirmware(const std::string & firmware,const std::string & root,int fw_fd,size_t fw_size,int loading_fd,int data_fd)64 static void LoadFirmware(const std::string& firmware, const std::string& root, int fw_fd,
65 size_t fw_size, int loading_fd, int data_fd) {
66 // Start transfer.
67 WriteFully(loading_fd, "1", 1);
68
69 // Copy the firmware.
70 int rc = sendfile(data_fd, fw_fd, nullptr, fw_size);
71 if (rc == -1) {
72 PLOG(ERROR) << "firmware: sendfile failed { '" << root << "', '" << firmware << "' }";
73 }
74
75 // Tell the firmware whether to abort or commit.
76 const char* response = (rc != -1) ? "0" : "-1";
77 WriteFully(loading_fd, response, strlen(response));
78 }
79
IsBooting()80 static bool IsBooting() {
81 return access("/dev/.booting", F_OK) == 0;
82 }
83
ExternalFirmwareHandler(std::string devpath,uid_t uid,std::string handler_path)84 ExternalFirmwareHandler::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
FirmwareHandler(std::vector<std::string> firmware_directories,std::vector<ExternalFirmwareHandler> external_firmware_handlers)100 FirmwareHandler::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)) {}
104
RunExternalHandler(const std::string & handler,uid_t uid,const Uevent & uevent) const105 Result<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 }
112
113 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
GetFirmwarePath(const Uevent & uevent) const192 std::string FirmwareHandler::GetFirmwarePath(const Uevent& uevent) const {
193 for (const auto& external_handler : external_firmware_handlers_) {
194 if (external_handler.match(uevent.path)) {
195 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);
201 if (!result.ok()) {
202 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 }
217 LOG(INFO) << "firmware: loading '" << uevent.firmware << "' for '" << uevent.path << "'";
218 return uevent.firmware;
219 }
220
ProcessFirmwareEvent(const std::string & root,const std::string & firmware) const221 void FirmwareHandler::ProcessFirmwareEvent(const std::string& root,
222 const std::string& firmware) const {
223 std::string loading = root + "/loading";
224 std::string data = root + "/data";
225
226 unique_fd loading_fd(open(loading.c_str(), O_WRONLY | O_CLOEXEC));
227 if (loading_fd == -1) {
228 PLOG(ERROR) << "couldn't open firmware loading fd for " << firmware;
229 return;
230 }
231
232 unique_fd data_fd(open(data.c_str(), O_WRONLY | O_CLOEXEC));
233 if (data_fd == -1) {
234 PLOG(ERROR) << "couldn't open firmware data fd for " << firmware;
235 return;
236 }
237
238 std::vector<std::string> attempted_paths_and_errors;
239 auto TryLoadFirmware = [&](const std::string& firmware_directory) {
240 std::string file = firmware_directory + firmware;
241 unique_fd fw_fd(open(file.c_str(), O_RDONLY | O_CLOEXEC));
242 if (fw_fd == -1) {
243 attempted_paths_and_errors.emplace_back("firmware: attempted " + file +
244 ", open failed: " + strerror(errno));
245 return false;
246 }
247 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));
251 return false;
252 }
253 LoadFirmware(firmware, root, fw_fd, sb.st_size, loading_fd, data_fd);
254 return true;
255 };
256
257 int booting = IsBooting();
258 try_loading_again:
259 attempted_paths_and_errors.clear();
260 if (ForEachFirmwareDirectory(TryLoadFirmware)) {
261 return;
262 }
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
272 LOG(ERROR) << "firmware: could not find firmware for " << firmware;
273 for (const auto& message : attempted_paths_and_errors) {
274 LOG(ERROR) << message;
275 }
276
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
ForEachFirmwareDirectory(std::function<bool (const std::string &)> handler) const281 bool 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;
290 glob("/apex/*/etc/firmware/", GLOB_MARK, nullptr, &glob_result);
291 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
HandleUevent(const Uevent & uevent)308 void FirmwareHandler::HandleUevent(const Uevent& uevent) {
309 if (uevent.subsystem != "firmware" || uevent.action != "add") return;
310
311 // Loading the firmware in a child means we can do that in parallel...
312 auto pid = fork();
313 if (pid == -1) {
314 PLOG(ERROR) << "could not fork to process firmware event for " << uevent.firmware;
315 }
316 if (pid == 0) {
317 Timer t;
318 auto firmware = GetFirmwarePath(uevent);
319 ProcessFirmwareEvent("/sys" + uevent.path, firmware);
320 LOG(INFO) << "loading " << uevent.path << " took " << t;
321 _exit(EXIT_SUCCESS);
322 }
323 }
324
325 } // namespace init
326 } // namespace android
327