xref: /freebsd/stand/lua/config.lua (revision 76238846ad3e9e271a3d1f792f72beab727fd153)
1--
2-- SPDX-License-Identifier: BSD-2-Clause
3--
4-- Copyright (c) 2015 Pedro Souza <pedrosouza@freebsd.org>
5-- Copyright (c) 2018 Kyle Evans <kevans@FreeBSD.org>
6-- All rights reserved.
7--
8-- Redistribution and use in source and binary forms, with or without
9-- modification, are permitted provided that the following conditions
10-- are met:
11-- 1. Redistributions of source code must retain the above copyright
12--    notice, this list of conditions and the following disclaimer.
13-- 2. Redistributions in binary form must reproduce the above copyright
14--    notice, this list of conditions and the following disclaimer in the
15--    documentation and/or other materials provided with the distribution.
16--
17-- THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18-- ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19-- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20-- ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21-- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22-- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23-- OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24-- HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25-- LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26-- OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27-- SUCH DAMAGE.
28--
29-- $FreeBSD$
30--
31
32local hook = require("hook")
33
34local config = {}
35local modules = {}
36local carousel_choices = {}
37-- Which variables we changed
38local env_changed = {}
39-- Values to restore env to (nil to unset)
40local env_restore = {}
41
42local MSG_FAILDIR = "Failed to load conf dir '%s': not a directory"
43local MSG_FAILEXEC = "Failed to exec '%s'"
44local MSG_FAILSETENV = "Failed to '%s' with value: %s"
45local MSG_FAILOPENCFG = "Failed to open config: '%s'"
46local MSG_FAILREADCFG = "Failed to read config: '%s'"
47local MSG_FAILPARSECFG = "Failed to parse config: '%s'"
48local MSG_FAILEXECLUA = "Failed to execute lua conf '%s': '%s'"
49local MSG_FAILPARSEVAR = "Failed to parse variable '%s': %s"
50local MSG_FAILEXBEF = "Failed to execute '%s' before loading '%s'"
51local MSG_FAILEXAF = "Failed to execute '%s' after loading '%s'"
52local MSG_MALFORMED = "Malformed line (%d):\n\t'%s'"
53local MSG_DEFAULTKERNFAIL = "No kernel set, failed to load from module_path"
54local MSG_KERNFAIL = "Failed to load kernel '%s'"
55local MSG_XENKERNFAIL = "Failed to load Xen kernel '%s'"
56local MSG_XENKERNLOADING = "Loading Xen kernel..."
57local MSG_KERNLOADING = "Loading kernel..."
58local MSG_MODLOADING = "Loading configured modules..."
59local MSG_MODBLACKLIST = "Not loading blacklisted module '%s'"
60
61local MSG_FAILSYN_QUOTE = "Stray quote at position '%d'"
62local MSG_FAILSYN_EOLESC = "Stray escape at end of line"
63local MSG_FAILSYN_EOLVAR = "Unescaped $ at end of line"
64local MSG_FAILSYN_BADVAR = "Malformed variable expression at position '%d'"
65
66local MODULEEXPR = '([-%w_]+)'
67local QVALEXPR = '"(.*)"'
68local QVALREPL = QVALEXPR:gsub('%%', '%%%%')
69local WORDEXPR = "([-%w%d][-%w%d_.]*)"
70local WORDREPL = WORDEXPR:gsub('%%', '%%%%')
71
72-- Entries that should never make it into the environment; each one should have
73-- a documented reason for its existence, and these should all be implementation
74-- details of the config module.
75local loader_env_restricted_table = {
76	-- loader_conf_files should be considered write-only, and consumers
77	-- should not rely on any particular value; it's a loader implementation
78	-- detail.  Moreover, it's not a particularly useful variable to have in
79	-- the kenv.  Save the overhead, let it get fetched other ways.
80	loader_conf_files = true,
81}
82
83local function restoreEnv()
84	-- Examine changed environment variables
85	for k, v in pairs(env_changed) do
86		local restore_value = env_restore[k]
87		if restore_value == nil then
88			-- This one doesn't need restored for some reason
89			goto continue
90		end
91		local current_value = loader.getenv(k)
92		if current_value ~= v then
93			-- This was overwritten by some action taken on the menu
94			-- most likely; we'll leave it be.
95			goto continue
96		end
97		restore_value = restore_value.value
98		if restore_value ~= nil then
99			loader.setenv(k, restore_value)
100		else
101			loader.unsetenv(k)
102		end
103		::continue::
104	end
105
106	env_changed = {}
107	env_restore = {}
108end
109
110-- XXX This getEnv/setEnv should likely be exported at some point.  We can save
111-- the call back into loader.getenv for any variable that's been set or
112-- overridden by any loader.conf using this implementation with little overhead
113-- since we're already tracking the values.
114local function getEnv(key)
115	if loader_env_restricted_table[key] ~= nil or
116	    env_changed[key] ~= nil then
117		return env_changed[key]
118	end
119
120	return loader.getenv(key)
121end
122
123local function setEnv(key, value)
124	env_changed[key] = value
125
126	if loader_env_restricted_table[key] ~= nil then
127		return 0
128	end
129
130	-- Track the original value for this if we haven't already
131	if env_restore[key] == nil then
132		env_restore[key] = {value = loader.getenv(key)}
133	end
134
135	return loader.setenv(key, value)
136end
137
138-- name here is one of 'name', 'type', flags', 'before', 'after', or 'error.'
139-- These are set from lines in loader.conf(5): ${key}_${name}="${value}" where
140-- ${key} is a module name.
141local function setKey(key, name, value)
142	if modules[key] == nil then
143		modules[key] = {}
144	end
145	modules[key][name] = value
146end
147
148-- Escapes the named value for use as a literal in a replacement pattern.
149-- e.g. dhcp.host-name gets turned into dhcp%.host%-name to remove the special
150-- meaning.
151local function escapeName(name)
152	return name:gsub("([%p])", "%%%1")
153end
154
155local function processEnvVar(value)
156	local pval, vlen = '', #value
157	local nextpos, vdelim, vinit = 1
158	local vpat
159	for i = 1, vlen do
160		if i < nextpos then
161			goto nextc
162		end
163
164		local c = value:sub(i, i)
165		if c == '\\' then
166			if i == vlen then
167				return nil, MSG_FAILSYN_EOLESC
168			end
169			nextpos = i + 2
170			pval = pval .. value:sub(i + 1, i + 1)
171		elseif c == '"' then
172			return nil, MSG_FAILSYN_QUOTE:format(i)
173		elseif c == "$" then
174			if i == vlen then
175				return nil, MSG_FAILSYN_EOLVAR
176			else
177				if value:sub(i + 1, i + 1) == "{" then
178					-- Skip ${
179					vinit = i + 2
180					vdelim = '}'
181					vpat = "^([^}]+)}"
182				else
183					-- Skip the $
184					vinit = i + 1
185					vdelim = nil
186					vpat = "^([%w][-%w%d_.]*)"
187				end
188
189				local name = value:match(vpat, vinit)
190				if not name then
191					return nil, MSG_FAILSYN_BADVAR:format(i)
192				else
193					nextpos = vinit + #name
194					if vdelim then
195						nextpos = nextpos + 1
196					end
197
198					local repl = loader.getenv(name) or ""
199					pval = pval .. repl
200				end
201			end
202		else
203			pval = pval .. c
204		end
205		::nextc::
206	end
207
208	return pval
209end
210
211local function checkPattern(line, pattern)
212	local function _realCheck(_line, _pattern)
213		return _line:match(_pattern)
214	end
215
216	if pattern:find('$VALUE') then
217		local k, v, c
218		k, v, c = _realCheck(line, pattern:gsub('$VALUE', QVALREPL))
219		if k ~= nil then
220			return k,v, c
221		end
222		return _realCheck(line, pattern:gsub('$VALUE', WORDREPL))
223	else
224		return _realCheck(line, pattern)
225	end
226end
227
228-- str in this table is a regex pattern.  It will automatically be anchored to
229-- the beginning of a line and any preceding whitespace will be skipped.  The
230-- pattern should have no more than two captures patterns, which correspond to
231-- the two parameters (usually 'key' and 'value') that are passed to the
232-- process function.  All trailing characters will be validated.  Any $VALUE
233-- token included in a pattern will be tried first with a quoted value capture
234-- group, then a single-word value capture group.  This is our kludge for Lua
235-- regex not supporting branching.
236--
237-- We have two special entries in this table: the first is the first entry,
238-- a full-line comment.  The second is for 'exec' handling.  Both have a single
239-- capture group, but the difference is that the full-line comment pattern will
240-- match the entire line.  This does not run afoul of the later end of line
241-- validation that we'll do after a match.  However, the 'exec' pattern will.
242-- We document the exceptions with a special 'groups' index that indicates
243-- the number of capture groups, if not two.  We'll use this later to do
244-- validation on the proper entry.
245--
246local pattern_table = {
247	{
248		luaexempt = true,
249		str = "(#.*)",
250		process = function(_, _)  end,
251		groups = 1,
252	},
253	--  module_load="value"
254	{
255		name = MODULEEXPR .. "_load%s*",
256		val = "%s*$VALUE",
257		process = function(k, v)
258			if modules[k] == nil then
259				modules[k] = {}
260			end
261			modules[k].load = v:upper()
262			setEnv(k .. "_load", v:upper())
263		end,
264	},
265	--  module_name="value"
266	{
267		name = MODULEEXPR .. "_name%s*",
268		val = "%s*$VALUE",
269		process = function(k, v)
270			setKey(k, "name", v)
271			setEnv(k .. "_name", v)
272		end,
273	},
274	--  module_type="value"
275	{
276		name = MODULEEXPR .. "_type%s*",
277		val = "%s*$VALUE",
278		process = function(k, v)
279			setKey(k, "type", v)
280			setEnv(k .. "_type", v)
281		end,
282	},
283	--  module_flags="value"
284	{
285		name = MODULEEXPR .. "_flags%s*",
286		val = "%s*$VALUE",
287		process = function(k, v)
288			setKey(k, "flags", v)
289			setEnv(k .. "_flags", v)
290		end,
291	},
292	--  module_before="value"
293	{
294		name = MODULEEXPR .. "_before%s*",
295		val = "%s*$VALUE",
296		process = function(k, v)
297			setKey(k, "before", v)
298			setEnv(k .. "_before", v)
299		end,
300	},
301	--  module_after="value"
302	{
303		name = MODULEEXPR .. "_after%s*",
304		val = "%s*$VALUE",
305		process = function(k, v)
306			setKey(k, "after", v)
307			setEnv(k .. "_after", v)
308		end,
309	},
310	--  module_error="value"
311	{
312		name = MODULEEXPR .. "_error%s*",
313		val = "%s*$VALUE",
314		process = function(k, v)
315			setKey(k, "error", v)
316			setEnv(k .. "_error", v)
317		end,
318	},
319	--  exec="command"
320	{
321		luaexempt = true,
322		name = "exec%s*",
323		val = "%s*" .. QVALEXPR,
324		process = function(k, _)
325			if cli_execute_unparsed(k) ~= 0 then
326				print(MSG_FAILEXEC:format(k))
327			end
328		end,
329		groups = 1,
330	},
331	--  env_var="value" or env_var=[word|num]
332	{
333		name = "([%w][%w%d-_.]*)%s*",
334		val = "%s*$VALUE",
335		process = function(k, v)
336			local pv, msg = processEnvVar(v)
337			if not pv then
338				print(MSG_FAILPARSEVAR:format(k, msg))
339				return
340			end
341			if setEnv(k, pv) ~= 0 then
342				print(MSG_FAILSETENV:format(k, v))
343			else
344				return pv
345			end
346		end,
347	},
348}
349
350local function isValidComment(line)
351	if line ~= nil then
352		local s = line:match("^%s*#.*")
353		if s == nil then
354			s = line:match("^%s*$")
355		end
356		if s == nil then
357			return false
358		end
359	end
360	return true
361end
362
363local function getBlacklist()
364	local blacklist = {}
365	local blacklist_str = loader.getenv('module_blacklist')
366	if blacklist_str == nil then
367		return blacklist
368	end
369
370	for mod in blacklist_str:gmatch("[;, ]?([-%w_]+)[;, ]?") do
371		blacklist[mod] = true
372	end
373	return blacklist
374end
375
376local function loadModule(mod, silent)
377	local status = true
378	local blacklist = getBlacklist()
379	local pstatus
380	for k, v in pairs(mod) do
381		if v.load ~= nil and v.load:lower() == "yes" then
382			local module_name = v.name or k
383			if not v.force and blacklist[module_name] ~= nil then
384				if not silent then
385					print(MSG_MODBLACKLIST:format(module_name))
386				end
387				goto continue
388			end
389			if not silent then
390				loader.printc(module_name .. "...")
391			end
392			local str = "load "
393			if v.type ~= nil then
394				str = str .. "-t " .. v.type .. " "
395			end
396			str = str .. module_name
397			if v.flags ~= nil then
398				str = str .. " " .. v.flags
399			end
400			if v.before ~= nil then
401				pstatus = cli_execute_unparsed(v.before) == 0
402				if not pstatus and not silent then
403					print(MSG_FAILEXBEF:format(v.before, k))
404				end
405				status = status and pstatus
406			end
407
408			if cli_execute_unparsed(str) ~= 0 then
409				-- XXX Temporary shim: don't break the boot if
410				-- loader hadn't been recompiled with this
411				-- function exposed.
412				if loader.command_error then
413					print(loader.command_error())
414				end
415				if not silent then
416					print("failed!")
417				end
418				if v.error ~= nil then
419					cli_execute_unparsed(v.error)
420				end
421				status = false
422			elseif v.after ~= nil then
423				pstatus = cli_execute_unparsed(v.after) == 0
424				if not pstatus and not silent then
425					print(MSG_FAILEXAF:format(v.after, k))
426				end
427				if not silent then
428					print("ok")
429				end
430				status = status and pstatus
431			end
432		end
433		::continue::
434	end
435
436	return status
437end
438
439local function readFile(name, silent)
440	local f = io.open(name)
441	if f == nil then
442		if not silent then
443			print(MSG_FAILOPENCFG:format(name))
444		end
445		return nil
446	end
447
448	local text, _ = io.read(f)
449	-- We might have read in the whole file, this won't be needed any more.
450	io.close(f)
451
452	if text == nil and not silent then
453		print(MSG_FAILREADCFG:format(name))
454	end
455	return text
456end
457
458local function checkNextboot()
459	local nextboot_file = loader.getenv("nextboot_conf")
460	local nextboot_enable = loader.getenv("nextboot_enable")
461
462	if nextboot_file == nil then
463		return
464	end
465
466	-- is nextboot_enable set in nvstore?
467	if nextboot_enable == "NO" then
468		return
469	end
470
471	local text = readFile(nextboot_file, true)
472	if text == nil then
473		return
474	end
475
476	if nextboot_enable == nil and
477	    text:match("^nextboot_enable=\"NO\"") ~= nil then
478		-- We're done; nextboot is not enabled
479		return
480	end
481
482	if not config.parse(text) then
483		print(MSG_FAILPARSECFG:format(nextboot_file))
484	end
485
486	-- Attempt to rewrite the first line and only the first line of the
487	-- nextboot_file. We overwrite it with nextboot_enable="NO", then
488	-- check for that on load.
489	-- It's worth noting that this won't work on every filesystem, so we
490	-- won't do anything notable if we have any errors in this process.
491	local nfile = io.open(nextboot_file, 'w')
492	if nfile ~= nil then
493		-- We need the trailing space here to account for the extra
494		-- character taken up by the string nextboot_enable="YES"
495		-- Or new end quotation mark lands on the S, and we want to
496		-- rewrite the entirety of the first line.
497		io.write(nfile, "nextboot_enable=\"NO\" ")
498		io.close(nfile)
499	end
500	loader.setenv("nextboot_enable", "NO")
501end
502
503local function processEnv(k, v)
504	for _, val in ipairs(pattern_table) do
505		if not val.luaexempt and val.name then
506			local matched = k:match(val.name)
507
508			if matched then
509				return val.process(matched, v)
510			end
511		end
512	end
513end
514
515-- Module exports
516config.verbose = false
517
518-- The first item in every carousel is always the default item.
519function config.getCarouselIndex(id)
520	return carousel_choices[id] or 1
521end
522
523function config.setCarouselIndex(id, idx)
524	carousel_choices[id] = idx
525end
526
527-- Returns true if we processed the file successfully, false if we did not.
528-- If 'silent' is true, being unable to read the file is not considered a
529-- failure.
530function config.processFile(name, silent)
531	if silent == nil then
532		silent = false
533	end
534
535	local text = readFile(name, silent)
536	if text == nil then
537		return silent
538	end
539
540	if name:match(".lua$") then
541		local cfg_env = setmetatable({}, {
542			indices = {},
543			__index = function(env, key)
544				if getmetatable(env).indices[key] then
545					return rawget(env, key)
546				end
547
548				return loader.getenv(key)
549			end,
550			__newindex = function(env, key, val)
551				getmetatable(env).indices[key] = true
552				rawset(env, key, val)
553			end,
554		})
555
556		-- Give local modules a chance to populate the config
557		-- environment.
558		hook.runAll("config.buildenv", cfg_env)
559		local res, err = pcall(load(text, name, "t", cfg_env))
560		if res then
561			for k, v in pairs(cfg_env) do
562				local t = type(v)
563				if t ~= "function" and t ~= "table" then
564					if t ~= "string" then
565						v = tostring(v)
566					end
567					local pval = processEnv(k, v)
568					if pval then
569						setEnv(k, pval)
570					end
571				end
572			end
573		else
574			print(MSG_FAILEXECLUA:format(name, err))
575		end
576
577		return res
578	else
579		return config.parse(text)
580	end
581end
582
583-- silent runs will not return false if we fail to open the file
584function config.parse(text)
585	local n = 1
586	local status = true
587
588	for line in text:gmatch("([^\n]+)") do
589		if line:match("^%s*$") == nil then
590			for _, val in ipairs(pattern_table) do
591				if val.str == nil then
592					val.str = val.name .. "=" .. val.val
593				end
594				local pattern = '^%s*' .. val.str .. '%s*(.*)';
595				local cgroups = val.groups or 2
596				local k, v, c = checkPattern(line, pattern)
597				if k ~= nil then
598					-- Offset by one, drats
599					if cgroups == 1 then
600						c = v
601						v = nil
602					end
603
604					if isValidComment(c) then
605						val.process(k, v)
606						goto nextline
607					end
608
609					break
610				end
611			end
612
613			print(MSG_MALFORMED:format(n, line))
614			status = false
615		end
616		::nextline::
617		n = n + 1
618	end
619
620	return status
621end
622
623function config.readConf(file, loaded_files)
624	if loaded_files == nil then
625		loaded_files = {}
626	end
627
628	if loaded_files[file] ~= nil then
629		return
630	end
631
632	-- We'll process loader_conf_dirs at the top-level readConf
633	local load_conf_dirs = next(loaded_files) == nil
634	print("Loading " .. file)
635
636	-- The final value of loader_conf_files is not important, so just
637	-- clobber it here.  We'll later check if it's no longer nil and process
638	-- the new value for files to read.
639	setEnv("loader_conf_files", nil)
640
641	-- These may or may not exist, and that's ok. Do a
642	-- silent parse so that we complain on parse errors but
643	-- not for them simply not existing.
644	if not config.processFile(file, true) then
645		print(MSG_FAILPARSECFG:format(file))
646	end
647
648	loaded_files[file] = true
649
650	-- Going to process "loader_conf_files" extra-files
651	local loader_conf_files = getEnv("loader_conf_files")
652	if loader_conf_files ~= nil then
653		for name in loader_conf_files:gmatch("[%w%p]+") do
654			config.readConf(name, loaded_files)
655		end
656	end
657
658	if load_conf_dirs then
659		local loader_conf_dirs = getEnv("loader_conf_dirs")
660		if loader_conf_dirs ~= nil then
661			for name in loader_conf_dirs:gmatch("[%w%p]+") do
662				if lfs.attributes(name, "mode") ~= "directory" then
663					print(MSG_FAILDIR:format(name))
664					goto nextdir
665				end
666				for cfile in lfs.dir(name) do
667					if cfile:match(".conf$") then
668						local fpath = name .. "/" .. cfile
669						if lfs.attributes(fpath, "mode") == "file" then
670							config.readConf(fpath, loaded_files)
671						end
672					end
673				end
674				::nextdir::
675			end
676		end
677	end
678end
679
680-- other_kernel is optionally the name of a kernel to load, if not the default
681-- or autoloaded default from the module_path
682function config.loadKernel(other_kernel)
683	local flags = loader.getenv("kernel_options") or ""
684	local kernel = other_kernel or loader.getenv("kernel")
685
686	local function tryLoad(names)
687		for name in names:gmatch("([^;]+)%s*;?") do
688			local r = loader.perform("load " .. name ..
689			     " " .. flags)
690			if r == 0 then
691				return name
692			end
693		end
694		return nil
695	end
696
697	local function getModulePath()
698		local module_path = loader.getenv("module_path")
699		local kernel_path = loader.getenv("kernel_path")
700
701		if kernel_path == nil then
702			return module_path
703		end
704
705		-- Strip the loaded kernel path from module_path. This currently assumes
706		-- that the kernel path will be prepended to the module_path when it's
707		-- found.
708		kernel_path = escapeName(kernel_path .. ';')
709		return module_path:gsub(kernel_path, '')
710	end
711
712	local function loadBootfile()
713		local bootfile = loader.getenv("bootfile")
714
715		-- append default kernel name
716		if bootfile == nil then
717			bootfile = "kernel"
718		else
719			bootfile = bootfile .. ";kernel"
720		end
721
722		return tryLoad(bootfile)
723	end
724
725	-- kernel not set, try load from default module_path
726	if kernel == nil then
727		local res = loadBootfile()
728
729		if res ~= nil then
730			-- Default kernel is loaded
731			config.kernel_loaded = nil
732			return true
733		else
734			print(MSG_DEFAULTKERNFAIL)
735			return false
736		end
737	else
738		-- Use our cached module_path, so we don't end up with multiple
739		-- automatically added kernel paths to our final module_path
740		local module_path = getModulePath()
741		local res
742
743		if other_kernel ~= nil then
744			kernel = other_kernel
745		end
746		-- first try load kernel with module_path = /boot/${kernel}
747		-- then try load with module_path=${kernel}
748		local paths = {"/boot/" .. kernel, kernel}
749
750		for _, v in pairs(paths) do
751			loader.setenv("module_path", v)
752			res = loadBootfile()
753
754			-- succeeded, add path to module_path
755			if res ~= nil then
756				config.kernel_loaded = kernel
757				if module_path ~= nil then
758					loader.setenv("module_path", v .. ";" ..
759					    module_path)
760					loader.setenv("kernel_path", v)
761				end
762				return true
763			end
764		end
765
766		-- failed to load with ${kernel} as a directory
767		-- try as a file
768		res = tryLoad(kernel)
769		if res ~= nil then
770			config.kernel_loaded = kernel
771			return true
772		else
773			print(MSG_KERNFAIL:format(kernel))
774			return false
775		end
776	end
777end
778
779function config.selectKernel(kernel)
780	config.kernel_selected = kernel
781end
782
783function config.load(file, reloading)
784	if not file then
785		file = "/boot/defaults/loader.conf"
786	end
787
788	config.readConf(file)
789
790	checkNextboot()
791
792	local verbose = loader.getenv("verbose_loading") or "no"
793	config.verbose = verbose:lower() == "yes"
794	if not reloading then
795		hook.runAll("config.loaded")
796	end
797end
798
799-- Reload configuration
800function config.reload(file)
801	modules = {}
802	restoreEnv()
803	config.load(file, true)
804	hook.runAll("config.reloaded")
805end
806
807function config.loadelf()
808	local xen_kernel = loader.getenv('xen_kernel')
809	local kernel = config.kernel_selected or config.kernel_loaded
810	local status
811
812	if xen_kernel ~= nil then
813		print(MSG_XENKERNLOADING)
814		if cli_execute_unparsed('load ' .. xen_kernel) ~= 0 then
815			print(MSG_XENKERNFAIL:format(xen_kernel))
816			return false
817		end
818	end
819	print(MSG_KERNLOADING)
820	if not config.loadKernel(kernel) then
821		return false
822	end
823	hook.runAll("kernel.loaded")
824
825	print(MSG_MODLOADING)
826	status = loadModule(modules, not config.verbose)
827	hook.runAll("modules.loaded")
828	return status
829end
830
831function config.enableModule(modname)
832	if modules[modname] == nil then
833		modules[modname] = {}
834	elseif modules[modname].load == "YES" then
835		modules[modname].force = true
836		return true
837	end
838
839	modules[modname].load = "YES"
840	modules[modname].force = true
841	return true
842end
843
844function config.disableModule(modname)
845	if modules[modname] == nil then
846		return false
847	elseif modules[modname].load ~= "YES" then
848		return true
849	end
850
851	modules[modname].load = "NO"
852	modules[modname].force = nil
853	return true
854end
855
856function config.isModuleEnabled(modname)
857	local mod = modules[modname]
858	if not mod or mod.load ~= "YES" then
859		return false
860	end
861
862	if mod.force then
863		return true
864	end
865
866	local blacklist = getBlacklist()
867	return not blacklist[modname]
868end
869
870function config.getModuleInfo()
871	return {
872		modules = modules,
873		blacklist = getBlacklist()
874	}
875end
876
877hook.registerType("config.buildenv")
878hook.registerType("config.loaded")
879hook.registerType("config.reloaded")
880hook.registerType("kernel.loaded")
881hook.registerType("modules.loaded")
882return config
883