1 /*
2 * Copyright (C) 2018 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 <modprobe/modprobe.h>
18
19 #include <fnmatch.h>
20 #include <grp.h>
21 #include <pwd.h>
22 #include <sys/stat.h>
23 #include <sys/syscall.h>
24 #include <sys/wait.h>
25
26 #include <algorithm>
27 #include <map>
28 #include <set>
29 #include <string>
30 #include <thread>
31 #include <vector>
32
33 #include <android-base/chrono_utils.h>
34 #include <android-base/file.h>
35 #include <android-base/logging.h>
36 #include <android-base/parseint.h>
37 #include <android-base/strings.h>
38 #include <android-base/unique_fd.h>
39
40 #include "exthandler/exthandler.h"
41
MakeCanonical(const std::string & module_path)42 std::string Modprobe::MakeCanonical(const std::string& module_path) {
43 auto start = module_path.find_last_of('/');
44 if (start == std::string::npos) {
45 start = 0;
46 } else {
47 start += 1;
48 }
49 auto end = module_path.size();
50 if (android::base::EndsWith(module_path, ".ko")) {
51 end -= 3;
52 }
53 if ((end - start) <= 1) {
54 LOG(ERROR) << "malformed module name: " << module_path;
55 return "";
56 }
57 std::string module_name = module_path.substr(start, end - start);
58 // module names can have '-', but their file names will have '_'
59 std::replace(module_name.begin(), module_name.end(), '-', '_');
60 return module_name;
61 }
62
ParseDepCallback(const std::string & base_path,const std::vector<std::string> & args)63 bool Modprobe::ParseDepCallback(const std::string& base_path,
64 const std::vector<std::string>& args) {
65 std::vector<std::string> deps;
66 std::string prefix = "";
67
68 // Set first item as our modules path
69 std::string::size_type pos = args[0].find(':');
70 if (args[0][0] != '/') {
71 prefix = base_path + "/";
72 }
73 if (pos != std::string::npos) {
74 deps.emplace_back(prefix + args[0].substr(0, pos));
75 } else {
76 LOG(ERROR) << "dependency lines must start with name followed by ':'";
77 return false;
78 }
79
80 // Remaining items are dependencies of our module
81 for (auto arg = args.begin() + 1; arg != args.end(); ++arg) {
82 if ((*arg)[0] != '/') {
83 prefix = base_path + "/";
84 } else {
85 prefix = "";
86 }
87 deps.push_back(prefix + *arg);
88 }
89
90 std::string canonical_name = MakeCanonical(args[0].substr(0, pos));
91 if (canonical_name.empty()) {
92 return false;
93 }
94 this->module_deps_[canonical_name] = deps;
95
96 return true;
97 }
98
ParseAliasCallback(const std::vector<std::string> & args)99 bool Modprobe::ParseAliasCallback(const std::vector<std::string>& args) {
100 auto it = args.begin();
101 const std::string& type = *it++;
102
103 if (type != "alias") {
104 LOG(ERROR) << "non-alias line encountered in modules.alias, found " << type;
105 return false;
106 }
107
108 if (args.size() != 3) {
109 LOG(ERROR) << "alias lines in modules.alias must have 3 entries, not " << args.size();
110 return false;
111 }
112
113 const std::string& alias = *it++;
114 const std::string& module_name = *it++;
115 this->module_aliases_.emplace_back(alias, module_name);
116
117 return true;
118 }
119
ParseSoftdepCallback(const std::vector<std::string> & args)120 bool Modprobe::ParseSoftdepCallback(const std::vector<std::string>& args) {
121 auto it = args.begin();
122 const std::string& type = *it++;
123 std::string state = "";
124
125 if (type != "softdep") {
126 LOG(ERROR) << "non-softdep line encountered in modules.softdep, found " << type;
127 return false;
128 }
129
130 if (args.size() < 4) {
131 LOG(ERROR) << "softdep lines in modules.softdep must have at least 4 entries";
132 return false;
133 }
134
135 const std::string& module = *it++;
136 while (it != args.end()) {
137 const std::string& token = *it++;
138 if (token == "pre:" || token == "post:") {
139 state = token;
140 continue;
141 }
142 if (state == "") {
143 LOG(ERROR) << "malformed modules.softdep at token " << token;
144 return false;
145 }
146 if (state == "pre:") {
147 this->module_pre_softdep_.emplace_back(module, token);
148 } else {
149 this->module_post_softdep_.emplace_back(module, token);
150 }
151 }
152
153 return true;
154 }
155
ParseLoadCallback(const std::vector<std::string> & args)156 bool Modprobe::ParseLoadCallback(const std::vector<std::string>& args) {
157 auto it = args.begin();
158 const std::string& module = *it++;
159
160 const std::string& canonical_name = MakeCanonical(module);
161 if (canonical_name.empty()) {
162 return false;
163 }
164 this->module_load_.emplace_back(canonical_name);
165
166 return true;
167 }
168
ParseOptionsCallback(const std::vector<std::string> & args)169 bool Modprobe::ParseOptionsCallback(const std::vector<std::string>& args) {
170 auto it = args.begin();
171 const std::string& type = *it++;
172
173 if (type == "dyn_options") {
174 return ParseDynOptionsCallback(std::vector<std::string>(it, args.end()));
175 }
176
177 if (type != "options") {
178 LOG(ERROR) << "non-options line encountered in modules.options";
179 return false;
180 }
181
182 if (args.size() < 2) {
183 LOG(ERROR) << "lines in modules.options must have at least 2 entries, not " << args.size();
184 return false;
185 }
186
187 const std::string& module = *it++;
188 std::string options = "";
189
190 const std::string& canonical_name = MakeCanonical(module);
191 if (canonical_name.empty()) {
192 return false;
193 }
194
195 while (it != args.end()) {
196 options += *it++;
197 if (it != args.end()) {
198 options += " ";
199 }
200 }
201
202 auto [unused, inserted] = this->module_options_.emplace(canonical_name, options);
203 if (!inserted) {
204 LOG(ERROR) << "multiple options lines present for module " << module;
205 return false;
206 }
207 return true;
208 }
209
ParseDynOptionsCallback(const std::vector<std::string> & args)210 bool Modprobe::ParseDynOptionsCallback(const std::vector<std::string>& args) {
211 auto it = args.begin();
212 int arg_size = 3;
213
214 if (args.size() < arg_size) {
215 LOG(ERROR) << "dyn_options lines in modules.options must have at least" << arg_size
216 << " entries, not " << args.size();
217 return false;
218 }
219
220 const std::string& module = *it++;
221
222 const std::string& canonical_name = MakeCanonical(module);
223 if (canonical_name.empty()) {
224 return false;
225 }
226
227 const std::string& pwnam = *it++;
228 passwd* pwd = getpwnam(pwnam.c_str());
229 if (!pwd) {
230 LOG(ERROR) << "invalid handler uid'" << pwnam << "'";
231 return false;
232 }
233
234 std::string handler_with_args =
235 android::base::Join(std::vector<std::string>(it, args.end()), ' ');
236 handler_with_args.erase(std::remove(handler_with_args.begin(), handler_with_args.end(), '\"'),
237 handler_with_args.end());
238
239 LOG(DEBUG) << "Launching external module options handler: '" << handler_with_args
240 << " for module: " << module;
241
242 // There is no need to set envs for external module options handler - pass
243 // empty map.
244 std::unordered_map<std::string, std::string> envs_map;
245 auto result = RunExternalHandler(handler_with_args, pwd->pw_uid, 0, envs_map);
246 if (!result.ok()) {
247 LOG(ERROR) << "External module handler failed: " << result.error();
248 return false;
249 }
250
251 LOG(INFO) << "Dynamic options for module: " << module << " are '" << *result << "'";
252
253 auto [unused, inserted] = this->module_options_.emplace(canonical_name, *result);
254 if (!inserted) {
255 LOG(ERROR) << "multiple options lines present for module " << module;
256 return false;
257 }
258 return true;
259 }
260
ParseBlocklistCallback(const std::vector<std::string> & args)261 bool Modprobe::ParseBlocklistCallback(const std::vector<std::string>& args) {
262 auto it = args.begin();
263 const std::string& type = *it++;
264
265 if (type != "blocklist") {
266 LOG(ERROR) << "non-blocklist line encountered in modules.blocklist";
267 return false;
268 }
269
270 if (args.size() != 2) {
271 LOG(ERROR) << "lines in modules.blocklist must have exactly 2 entries, not " << args.size();
272 return false;
273 }
274
275 const std::string& module = *it++;
276
277 const std::string& canonical_name = MakeCanonical(module);
278 if (canonical_name.empty()) {
279 return false;
280 }
281 this->module_blocklist_.emplace(canonical_name);
282
283 return true;
284 }
285
ParseCfg(const std::string & cfg,std::function<bool (const std::vector<std::string> &)> f)286 void Modprobe::ParseCfg(const std::string& cfg,
287 std::function<bool(const std::vector<std::string>&)> f) {
288 std::string cfg_contents;
289 if (!android::base::ReadFileToString(cfg, &cfg_contents, false)) {
290 return;
291 }
292
293 std::vector<std::string> lines = android::base::Split(cfg_contents, "\n");
294 for (const auto& line : lines) {
295 if (line.empty() || line[0] == '#') {
296 continue;
297 }
298 const std::vector<std::string> args = android::base::Split(line, " ");
299 if (args.empty()) continue;
300 f(args);
301 }
302 return;
303 }
304
AddOption(const std::string & module_name,const std::string & option_name,const std::string & value)305 void Modprobe::AddOption(const std::string& module_name, const std::string& option_name,
306 const std::string& value) {
307 auto canonical_name = MakeCanonical(module_name);
308 auto options_iter = module_options_.find(canonical_name);
309 auto option_str = option_name + "=" + value;
310 if (options_iter != module_options_.end()) {
311 options_iter->second = options_iter->second + " " + option_str;
312 } else {
313 module_options_.emplace(canonical_name, option_str);
314 }
315 }
316
ParseKernelCmdlineOptions(void)317 void Modprobe::ParseKernelCmdlineOptions(void) {
318 std::string cmdline = GetKernelCmdline();
319 std::string module_name = "";
320 std::string option_name = "";
321 std::string value = "";
322 bool in_module = true;
323 bool in_option = false;
324 bool in_value = false;
325 bool in_quotes = false;
326 int start = 0;
327
328 for (int i = 0; i < cmdline.size(); i++) {
329 if (cmdline[i] == '"') {
330 in_quotes = !in_quotes;
331 }
332
333 if (in_quotes) continue;
334
335 if (cmdline[i] == ' ') {
336 if (in_value) {
337 value = cmdline.substr(start, i - start);
338 if (!module_name.empty() && !option_name.empty()) {
339 AddOption(module_name, option_name, value);
340 }
341 }
342 module_name = "";
343 option_name = "";
344 value = "";
345 in_value = false;
346 start = i + 1;
347 in_module = true;
348 continue;
349 }
350
351 if (cmdline[i] == '.') {
352 if (in_module) {
353 module_name = cmdline.substr(start, i - start);
354 start = i + 1;
355 in_module = false;
356 }
357 in_option = true;
358 continue;
359 }
360
361 if (cmdline[i] == '=') {
362 if (in_option) {
363 option_name = cmdline.substr(start, i - start);
364 start = i + 1;
365 in_option = false;
366 }
367 in_value = true;
368 continue;
369 }
370 }
371 if (in_value && !in_quotes) {
372 value = cmdline.substr(start, cmdline.size() - start);
373 if (!module_name.empty() && !option_name.empty()) {
374 AddOption(module_name, option_name, value);
375 }
376 }
377 }
378
Modprobe(const std::vector<std::string> & base_paths,const std::string load_file,bool use_blocklist)379 Modprobe::Modprobe(const std::vector<std::string>& base_paths, const std::string load_file,
380 bool use_blocklist)
381 : blocklist_enabled(use_blocklist) {
382 using namespace std::placeholders;
383
384 for (const auto& base_path : base_paths) {
385 auto alias_callback = std::bind(&Modprobe::ParseAliasCallback, this, _1);
386 ParseCfg(base_path + "/modules.alias", alias_callback);
387
388 auto dep_callback = std::bind(&Modprobe::ParseDepCallback, this, base_path, _1);
389 ParseCfg(base_path + "/modules.dep", dep_callback);
390
391 auto softdep_callback = std::bind(&Modprobe::ParseSoftdepCallback, this, _1);
392 ParseCfg(base_path + "/modules.softdep", softdep_callback);
393
394 auto load_callback = std::bind(&Modprobe::ParseLoadCallback, this, _1);
395 ParseCfg(base_path + "/" + load_file, load_callback);
396
397 auto options_callback = std::bind(&Modprobe::ParseOptionsCallback, this, _1);
398 ParseCfg(base_path + "/modules.options", options_callback);
399
400 auto blocklist_callback = std::bind(&Modprobe::ParseBlocklistCallback, this, _1);
401 ParseCfg(base_path + "/modules.blocklist", blocklist_callback);
402 }
403
404 ParseKernelCmdlineOptions();
405 }
406
GetDependencies(const std::string & module)407 std::vector<std::string> Modprobe::GetDependencies(const std::string& module) {
408 auto it = module_deps_.find(module);
409 if (it == module_deps_.end()) {
410 return {};
411 }
412 return it->second;
413 }
414
InsmodWithDeps(const std::string & module_name,const std::string & parameters)415 bool Modprobe::InsmodWithDeps(const std::string& module_name, const std::string& parameters) {
416 if (module_name.empty()) {
417 LOG(ERROR) << "Need valid module name, given: " << module_name;
418 return false;
419 }
420
421 auto dependencies = GetDependencies(module_name);
422 if (dependencies.empty()) {
423 LOG(ERROR) << "Module " << module_name << " not in dependency file";
424 return false;
425 }
426
427 // load module dependencies in reverse order
428 for (auto dep = dependencies.rbegin(); dep != dependencies.rend() - 1; ++dep) {
429 LOG(VERBOSE) << "Loading hard dep for '" << module_name << "': " << *dep;
430 if (!LoadWithAliases(*dep, true)) {
431 return false;
432 }
433 }
434
435 // try to load soft pre-dependencies
436 for (const auto& [module, softdep] : module_pre_softdep_) {
437 if (module_name == module) {
438 LOG(VERBOSE) << "Loading soft pre-dep for '" << module << "': " << softdep;
439 LoadWithAliases(softdep, false);
440 }
441 }
442
443 // load target module itself with args
444 if (!Insmod(dependencies[0], parameters)) {
445 return false;
446 }
447
448 // try to load soft post-dependencies
449 for (const auto& [module, softdep] : module_post_softdep_) {
450 if (module_name == module) {
451 LOG(VERBOSE) << "Loading soft post-dep for '" << module << "': " << softdep;
452 LoadWithAliases(softdep, false);
453 }
454 }
455
456 return true;
457 }
458
LoadWithAliases(const std::string & module_name,bool strict,const std::string & parameters)459 bool Modprobe::LoadWithAliases(const std::string& module_name, bool strict,
460 const std::string& parameters) {
461 auto canonical_name = MakeCanonical(module_name);
462 if (module_loaded_.count(canonical_name)) {
463 return true;
464 }
465
466 std::set<std::string> modules_to_load = {canonical_name};
467 bool module_loaded = false;
468
469 // use aliases to expand list of modules to load (multiple modules
470 // may alias themselves to the requested name)
471 for (const auto& [alias, aliased_module] : module_aliases_) {
472 if (fnmatch(alias.c_str(), module_name.c_str(), 0) != 0) continue;
473 LOG(VERBOSE) << "Found alias for '" << module_name << "': '" << aliased_module;
474 if (module_loaded_.count(MakeCanonical(aliased_module))) continue;
475 modules_to_load.emplace(aliased_module);
476 }
477
478 // attempt to load all modules aliased to this name
479 for (const auto& module : modules_to_load) {
480 if (!ModuleExists(module)) continue;
481 if (InsmodWithDeps(module, parameters)) module_loaded = true;
482 }
483
484 if (strict && !module_loaded) {
485 LOG(ERROR) << "LoadWithAliases was unable to load " << module_name
486 << ", tried: " << android::base::Join(modules_to_load, ", ");
487 return false;
488 }
489 return true;
490 }
491
IsBlocklisted(const std::string & module_name)492 bool Modprobe::IsBlocklisted(const std::string& module_name) {
493 if (!blocklist_enabled) return false;
494
495 auto canonical_name = MakeCanonical(module_name);
496 auto dependencies = GetDependencies(canonical_name);
497 for (auto dep = dependencies.begin(); dep != dependencies.end(); ++dep) {
498 if (module_blocklist_.count(MakeCanonical(*dep))) return true;
499 }
500
501 return module_blocklist_.count(canonical_name) > 0;
502 }
503
504 // Another option to load kernel modules. load independent modules dependencies
505 // in parallel and then update dependency list of other remaining modules,
506 // repeat these steps until all modules are loaded.
507 // Discard all blocklist.
508 // Softdeps are taken care in InsmodWithDeps().
LoadModulesParallel(int num_threads)509 bool Modprobe::LoadModulesParallel(int num_threads) {
510 bool ret = true;
511 std::map<std::string, std::vector<std::string>> mod_with_deps;
512
513 // Get dependencies
514 for (const auto& module : module_load_) {
515 // Skip blocklist modules
516 if (IsBlocklisted(module)) {
517 LOG(VERBOSE) << "LMP: Blocklist: Module " << module << " skipping...";
518 continue;
519 }
520 auto dependencies = GetDependencies(MakeCanonical(module));
521 if (dependencies.empty()) {
522 LOG(ERROR) << "LMP: Hard-dep: Module " << module
523 << " not in .dep file";
524 return false;
525 }
526 mod_with_deps[MakeCanonical(module)] = dependencies;
527 }
528
529 while (!mod_with_deps.empty()) {
530 std::vector<std::thread> threads;
531 std::vector<std::string> mods_path_to_load;
532 std::mutex vector_lock;
533
534 // Find independent modules
535 for (const auto& [it_mod, it_dep] : mod_with_deps) {
536 auto itd_last = it_dep.rbegin();
537 if (itd_last == it_dep.rend())
538 continue;
539
540 auto cnd_last = MakeCanonical(*itd_last);
541 // Hard-dependencies cannot be blocklisted
542 if (IsBlocklisted(cnd_last)) {
543 LOG(ERROR) << "LMP: Blocklist: Module-dep " << cnd_last
544 << " : failed to load module " << it_mod;
545 return false;
546 }
547
548 std::string str = "load_sequential=1";
549 auto it = module_options_[cnd_last].find(str);
550 if (it != std::string::npos) {
551 module_options_[cnd_last].erase(it, it + str.size());
552
553 if (!LoadWithAliases(cnd_last, true)) {
554 return false;
555 }
556 } else {
557 if (std::find(mods_path_to_load.begin(), mods_path_to_load.end(),
558 cnd_last) == mods_path_to_load.end()) {
559 mods_path_to_load.emplace_back(cnd_last);
560 }
561 }
562 }
563
564 // Load independent modules in parallel
565 auto thread_function = [&] {
566 std::unique_lock lk(vector_lock);
567 while (!mods_path_to_load.empty()) {
568 auto ret_load = true;
569 auto mod_to_load = std::move(mods_path_to_load.back());
570 mods_path_to_load.pop_back();
571
572 lk.unlock();
573 ret_load &= LoadWithAliases(mod_to_load, true);
574 lk.lock();
575 if (!ret_load) {
576 ret &= ret_load;
577 }
578 }
579 };
580
581 std::generate_n(std::back_inserter(threads), num_threads,
582 [&] { return std::thread(thread_function); });
583
584 // Wait for the threads.
585 for (auto& thread : threads) {
586 thread.join();
587 }
588
589 if (!ret) return ret;
590
591 std::lock_guard guard(module_loaded_lock_);
592 // Remove loaded module form mod_with_deps and soft dependencies of other modules
593 for (const auto& module_loaded : module_loaded_)
594 mod_with_deps.erase(module_loaded);
595
596 // Remove loaded module form dependencies of other modules which are not loaded yet
597 for (const auto& module_loaded_path : module_loaded_paths_) {
598 for (auto& [mod, deps] : mod_with_deps) {
599 auto it = std::find(deps.begin(), deps.end(), module_loaded_path);
600 if (it != deps.end()) {
601 deps.erase(it);
602 }
603 }
604 }
605 }
606
607 return ret;
608 }
609
LoadListedModules(bool strict)610 bool Modprobe::LoadListedModules(bool strict) {
611 auto ret = true;
612 for (const auto& module : module_load_) {
613 if (!LoadWithAliases(module, true)) {
614 if (IsBlocklisted(module)) continue;
615 ret = false;
616 if (strict) break;
617 }
618 }
619 return ret;
620 }
621
Remove(const std::string & module_name)622 bool Modprobe::Remove(const std::string& module_name) {
623 auto dependencies = GetDependencies(MakeCanonical(module_name));
624 for (auto dep = dependencies.begin(); dep != dependencies.end(); ++dep) {
625 Rmmod(*dep);
626 }
627 Rmmod(module_name);
628 return true;
629 }
630
ListModules(const std::string & pattern)631 std::vector<std::string> Modprobe::ListModules(const std::string& pattern) {
632 std::vector<std::string> rv;
633 for (const auto& [module, deps] : module_deps_) {
634 // Attempt to match both the canonical module name and the module filename.
635 if (!fnmatch(pattern.c_str(), module.c_str(), 0)) {
636 rv.emplace_back(module);
637 } else if (!fnmatch(pattern.c_str(), android::base::Basename(deps[0]).c_str(), 0)) {
638 rv.emplace_back(deps[0]);
639 }
640 }
641 return rv;
642 }
643
GetAllDependencies(const std::string & module,std::vector<std::string> * pre_dependencies,std::vector<std::string> * dependencies,std::vector<std::string> * post_dependencies)644 bool Modprobe::GetAllDependencies(const std::string& module,
645 std::vector<std::string>* pre_dependencies,
646 std::vector<std::string>* dependencies,
647 std::vector<std::string>* post_dependencies) {
648 std::string canonical_name = MakeCanonical(module);
649 if (pre_dependencies) {
650 pre_dependencies->clear();
651 for (const auto& [it_module, it_softdep] : module_pre_softdep_) {
652 if (canonical_name == it_module) {
653 pre_dependencies->emplace_back(it_softdep);
654 }
655 }
656 }
657 if (dependencies) {
658 dependencies->clear();
659 auto hard_deps = GetDependencies(canonical_name);
660 if (hard_deps.empty()) {
661 return false;
662 }
663 for (auto dep = hard_deps.rbegin(); dep != hard_deps.rend(); dep++) {
664 dependencies->emplace_back(*dep);
665 }
666 }
667 if (post_dependencies) {
668 for (const auto& [it_module, it_softdep] : module_post_softdep_) {
669 if (canonical_name == it_module) {
670 post_dependencies->emplace_back(it_softdep);
671 }
672 }
673 }
674 return true;
675 }
676