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 <grp.h>
23 #include <pwd.h>
24 #include <signal.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <sys/sendfile.h>
28 #include <sys/wait.h>
29 #include <unistd.h>
30
31 #include <thread>
32
33 #include <android-base/chrono_utils.h>
34 #include <android-base/file.h>
35 #include <android-base/logging.h>
36 #include <android-base/scopeguard.h>
37 #include <android-base/strings.h>
38 #include <android-base/unique_fd.h>
39
40 using android::base::ReadFdToString;
41 using android::base::Socketpair;
42 using android::base::Split;
43 using android::base::Timer;
44 using android::base::Trim;
45 using android::base::unique_fd;
46 using android::base::WriteFully;
47
48 namespace android {
49 namespace init {
50
51 namespace {
PrefixMatch(const std::string & pattern,const std::string & path)52 bool PrefixMatch(const std::string& pattern, const std::string& path) {
53 return android::base::StartsWith(path, pattern);
54 }
55
FnMatch(const std::string & pattern,const std::string & path)56 bool FnMatch(const std::string& pattern, const std::string& path) {
57 return fnmatch(pattern.c_str(), path.c_str(), 0) == 0;
58 }
59
EqualMatch(const std::string & pattern,const std::string & path)60 bool EqualMatch(const std::string& pattern, const std::string& path) {
61 return pattern == path;
62 }
63 } // namespace
64
LoadFirmware(const std::string & firmware,const std::string & root,int fw_fd,size_t fw_size,int loading_fd,int data_fd)65 static void LoadFirmware(const std::string& firmware, const std::string& root, int fw_fd,
66 size_t fw_size, int loading_fd, int data_fd) {
67 // Start transfer.
68 WriteFully(loading_fd, "1", 1);
69
70 // Copy the firmware.
71 int rc = sendfile(data_fd, fw_fd, nullptr, fw_size);
72 if (rc == -1) {
73 PLOG(ERROR) << "firmware: sendfile failed { '" << root << "', '" << firmware << "' }";
74 }
75
76 // Tell the firmware whether to abort or commit.
77 const char* response = (rc != -1) ? "0" : "-1";
78 WriteFully(loading_fd, response, strlen(response));
79 }
80
IsBooting()81 static bool IsBooting() {
82 return access("/dev/.booting", F_OK) == 0;
83 }
84
ExternalFirmwareHandler(std::string devpath,uid_t uid,gid_t gid,std::string handler_path)85 ExternalFirmwareHandler::ExternalFirmwareHandler(std::string devpath, uid_t uid, gid_t gid,
86 std::string handler_path)
87 : devpath(std::move(devpath)), uid(uid), gid(gid), handler_path(std::move(handler_path)) {
88 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
ExternalFirmwareHandler(std::string devpath,uid_t uid,std::string handler_path)101 ExternalFirmwareHandler::ExternalFirmwareHandler(std::string devpath, uid_t uid,
102 std::string handler_path)
103 : ExternalFirmwareHandler(devpath, uid, 0, handler_path) {}
104
FirmwareHandler(std::vector<std::string> firmware_directories,std::vector<ExternalFirmwareHandler> external_firmware_handlers)105 FirmwareHandler::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)) {}
109
RunExternalHandler(const std::string & handler,uid_t uid,gid_t gid,const Uevent & uevent) const110 Result<std::string> FirmwareHandler::RunExternalHandler(const std::string& handler, uid_t uid,
111 gid_t gid, const Uevent& uevent) const {
112 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 }
117
118 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
148 if (gid != 0) {
149 if (setgid(gid) != 0) {
150 fprintf(stderr, "setgid() failed: %s", strerror(errno));
151 _exit(EXIT_FAILURE);
152 }
153 }
154
155 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
GetFirmwarePath(const Uevent & uevent) const204 std::string FirmwareHandler::GetFirmwarePath(const Uevent& uevent) const {
205 for (const auto& external_handler : external_firmware_handlers_) {
206 if (external_handler.match(uevent.path)) {
207 LOG(INFO) << "Launching external firmware handler '" << external_handler.handler_path
208 << "' for devpath: '" << uevent.path << "' firmware: '" << uevent.firmware
209 << "'";
210
211 auto result = RunExternalHandler(external_handler.handler_path, external_handler.uid,
212 external_handler.gid, uevent);
213 if (!result.ok()) {
214 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 }
229 LOG(INFO) << "firmware: loading '" << uevent.firmware << "' for '" << uevent.path << "'";
230 return uevent.firmware;
231 }
232
ProcessFirmwareEvent(const std::string & root,const std::string & firmware) const233 void FirmwareHandler::ProcessFirmwareEvent(const std::string& root,
234 const std::string& firmware) const {
235 std::string loading = root + "/loading";
236 std::string data = root + "/data";
237
238 unique_fd loading_fd(open(loading.c_str(), O_WRONLY | O_CLOEXEC));
239 if (loading_fd == -1) {
240 PLOG(ERROR) << "couldn't open firmware loading fd for " << firmware;
241 return;
242 }
243
244 unique_fd data_fd(open(data.c_str(), O_WRONLY | O_CLOEXEC));
245 if (data_fd == -1) {
246 PLOG(ERROR) << "couldn't open firmware data fd for " << firmware;
247 return;
248 }
249
250 std::vector<std::string> attempted_paths_and_errors;
251 auto TryLoadFirmware = [&](const std::string& firmware_directory) {
252 std::string file = firmware_directory + firmware;
253 unique_fd fw_fd(open(file.c_str(), O_RDONLY | O_CLOEXEC));
254 if (fw_fd == -1) {
255 attempted_paths_and_errors.emplace_back("firmware: attempted " + file +
256 ", open failed: " + strerror(errno));
257 return false;
258 }
259 struct stat sb;
260 if (fstat(fw_fd.get(), &sb) == -1) {
261 attempted_paths_and_errors.emplace_back("firmware: attempted " + file +
262 ", fstat failed: " + strerror(errno));
263 return false;
264 }
265 LoadFirmware(firmware, root, fw_fd.get(), sb.st_size, loading_fd.get(), data_fd.get());
266 return true;
267 };
268
269 int booting = IsBooting();
270 try_loading_again:
271 attempted_paths_and_errors.clear();
272 if (ForEachFirmwareDirectory(TryLoadFirmware)) {
273 return;
274 }
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
284 LOG(ERROR) << "firmware: could not find firmware for " << firmware;
285 for (const auto& message : attempted_paths_and_errors) {
286 LOG(ERROR) << message;
287 }
288
289 // Write "-1" as our response to the kernel's firmware request, since we have nothing for it.
290 write(loading_fd.get(), "-1", 2);
291 }
292
ForEachFirmwareDirectory(std::function<bool (const std::string &)> handler) const293 bool 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;
302 glob("/apex/*/etc/firmware/", GLOB_MARK, nullptr, &glob_result);
303 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
HandleUevent(const Uevent & uevent)320 void FirmwareHandler::HandleUevent(const Uevent& uevent) {
321 if (uevent.subsystem != "firmware" || uevent.action != "add") return;
322
323 // Loading the firmware in a child means we can do that in parallel...
324 auto pid = fork();
325 if (pid == -1) {
326 PLOG(ERROR) << "could not fork to process firmware event for " << uevent.firmware;
327 }
328 if (pid == 0) {
329 Timer t;
330 auto firmware = GetFirmwarePath(uevent);
331 ProcessFirmwareEvent("/sys" + uevent.path, firmware);
332 LOG(INFO) << "loading " << uevent.path << " took " << t;
333 _exit(EXIT_SUCCESS);
334 }
335 }
336
337 } // namespace init
338 } // namespace android
339