xref: /freebsd/stand/lua/config.lua (revision 7ec2f6bce5d28e6662c29e63f6ab6b7ef57d98b2)
1--
2-- SPDX-License-Identifier: BSD-2-Clause-FreeBSD
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_FAILEXEC = "Failed to exec '%s'"
43local MSG_FAILSETENV = "Failed to '%s' with value: %s"
44local MSG_FAILOPENCFG = "Failed to open config: '%s'"
45local MSG_FAILREADCFG = "Failed to read config: '%s'"
46local MSG_FAILPARSECFG = "Failed to parse config: '%s'"
47local MSG_FAILEXBEF = "Failed to execute '%s' before loading '%s'"
48local MSG_FAILEXAF = "Failed to execute '%s' after loading '%s'"
49local MSG_MALFORMED = "Malformed line (%d):\n\t'%s'"
50local MSG_DEFAULTKERNFAIL = "No kernel set, failed to load from module_path"
51local MSG_KERNFAIL = "Failed to load kernel '%s'"
52local MSG_XENKERNFAIL = "Failed to load Xen kernel '%s'"
53local MSG_XENKERNLOADING = "Loading Xen kernel..."
54local MSG_KERNLOADING = "Loading kernel..."
55local MSG_MODLOADING = "Loading configured modules..."
56local MSG_MODBLACKLIST = "Not loading blacklisted module '%s'"
57
58local MODULEEXPR = '([%w-_]+)'
59local QVALEXPR = "\"([%w%s%p]-)\""
60local QVALREPL = QVALEXPR:gsub('%%', '%%%%')
61local WORDEXPR = "([%w]+)"
62local WORDREPL = WORDEXPR:gsub('%%', '%%%%')
63
64-- Entries that should never make it into the environment; each one should have
65-- a documented reason for its existence, and these should all be implementation
66-- details of the config module.
67local loader_env_restricted_table = {
68	-- loader_conf_files should be considered write-only, and consumers
69	-- should not rely on any particular value; it's a loader implementation
70	-- detail.  Moreover, it's not a particularly useful variable to have in
71	-- the kenv.  Save the overhead, let it get fetched other ways.
72	loader_conf_files = true,
73}
74
75local function restoreEnv()
76	-- Examine changed environment variables
77	for k, v in pairs(env_changed) do
78		local restore_value = env_restore[k]
79		if restore_value == nil then
80			-- This one doesn't need restored for some reason
81			goto continue
82		end
83		local current_value = loader.getenv(k)
84		if current_value ~= v then
85			-- This was overwritten by some action taken on the menu
86			-- most likely; we'll leave it be.
87			goto continue
88		end
89		restore_value = restore_value.value
90		if restore_value ~= nil then
91			loader.setenv(k, restore_value)
92		else
93			loader.unsetenv(k)
94		end
95		::continue::
96	end
97
98	env_changed = {}
99	env_restore = {}
100end
101
102-- XXX This getEnv/setEnv should likely be exported at some point.  We can save
103-- the call back into loader.getenv for any variable that's been set or
104-- overridden by any loader.conf using this implementation with little overhead
105-- since we're already tracking the values.
106local function getEnv(key)
107	if loader_env_restricted_table[key] ~= nil or
108	    env_changed[key] ~= nil then
109		return env_changed[key]
110	end
111
112	return loader.getenv(key)
113end
114
115local function setEnv(key, value)
116	env_changed[key] = value
117
118	if loader_env_restricted_table[key] ~= nil then
119		return 0
120	end
121
122	-- Track the original value for this if we haven't already
123	if env_restore[key] == nil then
124		env_restore[key] = {value = loader.getenv(key)}
125	end
126
127	return loader.setenv(key, value)
128end
129
130-- name here is one of 'name', 'type', flags', 'before', 'after', or 'error.'
131-- These are set from lines in loader.conf(5): ${key}_${name}="${value}" where
132-- ${key} is a module name.
133local function setKey(key, name, value)
134	if modules[key] == nil then
135		modules[key] = {}
136	end
137	modules[key][name] = value
138end
139
140-- Escapes the named value for use as a literal in a replacement pattern.
141-- e.g. dhcp.host-name gets turned into dhcp%.host%-name to remove the special
142-- meaning.
143local function escapeName(name)
144	return name:gsub("([%p])", "%%%1")
145end
146
147local function processEnvVar(value)
148	for name in value:gmatch("${([^}]+)}") do
149		local replacement = loader.getenv(name) or ""
150		value = value:gsub("${" .. escapeName(name) .. "}", replacement)
151	end
152	for name in value:gmatch("$([%w%p]+)%s*") do
153		local replacement = loader.getenv(name) or ""
154		value = value:gsub("$" .. escapeName(name), replacement)
155	end
156	return value
157end
158
159local function checkPattern(line, pattern)
160	local function _realCheck(_line, _pattern)
161		return _line:match(_pattern)
162	end
163
164	if pattern:find('$VALUE') then
165		local k, v, c
166		k, v, c = _realCheck(line, pattern:gsub('$VALUE', QVALREPL))
167		if k ~= nil then
168			return k,v, c
169		end
170		return _realCheck(line, pattern:gsub('$VALUE', WORDREPL))
171	else
172		return _realCheck(line, pattern)
173	end
174end
175
176-- str in this table is a regex pattern.  It will automatically be anchored to
177-- the beginning of a line and any preceding whitespace will be skipped.  The
178-- pattern should have no more than two captures patterns, which correspond to
179-- the two parameters (usually 'key' and 'value') that are passed to the
180-- process function.  All trailing characters will be validated.  Any $VALUE
181-- token included in a pattern will be tried first with a quoted value capture
182-- group, then a single-word value capture group.  This is our kludge for Lua
183-- regex not supporting branching.
184--
185-- We have two special entries in this table: the first is the first entry,
186-- a full-line comment.  The second is for 'exec' handling.  Both have a single
187-- capture group, but the difference is that the full-line comment pattern will
188-- match the entire line.  This does not run afoul of the later end of line
189-- validation that we'll do after a match.  However, the 'exec' pattern will.
190-- We document the exceptions with a special 'groups' index that indicates
191-- the number of capture groups, if not two.  We'll use this later to do
192-- validation on the proper entry.
193--
194local pattern_table = {
195	{
196		str = "(#.*)",
197		process = function(_, _)  end,
198		groups = 1,
199	},
200	--  module_load="value"
201	{
202		str = MODULEEXPR .. "_load%s*=%s*$VALUE",
203		process = function(k, v)
204			if modules[k] == nil then
205				modules[k] = {}
206			end
207			modules[k].load = v:upper()
208		end,
209	},
210	--  module_name="value"
211	{
212		str = MODULEEXPR .. "_name%s*=%s*$VALUE",
213		process = function(k, v)
214			setKey(k, "name", v)
215		end,
216	},
217	--  module_type="value"
218	{
219		str = MODULEEXPR .. "_type%s*=%s*$VALUE",
220		process = function(k, v)
221			setKey(k, "type", v)
222		end,
223	},
224	--  module_flags="value"
225	{
226		str = MODULEEXPR .. "_flags%s*=%s*$VALUE",
227		process = function(k, v)
228			setKey(k, "flags", v)
229		end,
230	},
231	--  module_before="value"
232	{
233		str = MODULEEXPR .. "_before%s*=%s*$VALUE",
234		process = function(k, v)
235			setKey(k, "before", v)
236		end,
237	},
238	--  module_after="value"
239	{
240		str = MODULEEXPR .. "_after%s*=%s*$VALUE",
241		process = function(k, v)
242			setKey(k, "after", v)
243		end,
244	},
245	--  module_error="value"
246	{
247		str = MODULEEXPR .. "_error%s*=%s*$VALUE",
248		process = function(k, v)
249			setKey(k, "error", v)
250		end,
251	},
252	--  exec="command"
253	{
254		str = "exec%s*=%s*" .. QVALEXPR,
255		process = function(k, _)
256			if cli_execute_unparsed(k) ~= 0 then
257				print(MSG_FAILEXEC:format(k))
258			end
259		end,
260		groups = 1,
261	},
262	--  env_var="value"
263	{
264		str = "([%w%p]+)%s*=%s*$VALUE",
265		process = function(k, v)
266			if setEnv(k, processEnvVar(v)) ~= 0 then
267				print(MSG_FAILSETENV:format(k, v))
268			end
269		end,
270	},
271	--  env_var=num
272	{
273		str = "([%w%p]+)%s*=%s*(-?%d+)",
274		process = function(k, v)
275			if setEnv(k, processEnvVar(v)) ~= 0 then
276				print(MSG_FAILSETENV:format(k, tostring(v)))
277			end
278		end,
279	},
280}
281
282local function isValidComment(line)
283	if line ~= nil then
284		local s = line:match("^%s*#.*")
285		if s == nil then
286			s = line:match("^%s*$")
287		end
288		if s == nil then
289			return false
290		end
291	end
292	return true
293end
294
295local function getBlacklist()
296	local blacklist = {}
297	local blacklist_str = loader.getenv('module_blacklist')
298	if blacklist_str == nil then
299		return blacklist
300	end
301
302	for mod in blacklist_str:gmatch("[;, ]?([%w-_]+)[;, ]?") do
303		blacklist[mod] = true
304	end
305	return blacklist
306end
307
308local function loadModule(mod, silent)
309	local status = true
310	local blacklist = getBlacklist()
311	local pstatus
312	for k, v in pairs(mod) do
313		if v.load ~= nil and v.load:lower() == "yes" then
314			local module_name = v.name or k
315			if blacklist[module_name] ~= nil then
316				if not silent then
317					print(MSG_MODBLACKLIST:format(module_name))
318				end
319				goto continue
320			end
321			if not silent then
322				loader.printc(module_name .. "...")
323			end
324			local str = "load "
325			if v.type ~= nil then
326				str = str .. "-t " .. v.type .. " "
327			end
328			str = str .. module_name
329			if v.flags ~= nil then
330				str = str .. " " .. v.flags
331			end
332			if v.before ~= nil then
333				pstatus = cli_execute_unparsed(v.before) == 0
334				if not pstatus and not silent then
335					print(MSG_FAILEXBEF:format(v.before, k))
336				end
337				status = status and pstatus
338			end
339
340			if cli_execute_unparsed(str) ~= 0 then
341				-- XXX Temporary shim: don't break the boot if
342				-- loader hadn't been recompiled with this
343				-- function exposed.
344				if loader.command_error then
345					print(loader.command_error())
346				end
347				if not silent then
348					print("failed!")
349				end
350				if v.error ~= nil then
351					cli_execute_unparsed(v.error)
352				end
353				status = false
354			elseif v.after ~= nil then
355				pstatus = cli_execute_unparsed(v.after) == 0
356				if not pstatus and not silent then
357					print(MSG_FAILEXAF:format(v.after, k))
358				end
359				if not silent then
360					print("ok")
361				end
362				status = status and pstatus
363			end
364		end
365		::continue::
366	end
367
368	return status
369end
370
371local function readFile(name, silent)
372	local f = io.open(name)
373	if f == nil then
374		if not silent then
375			print(MSG_FAILOPENCFG:format(name))
376		end
377		return nil
378	end
379
380	local text, _ = io.read(f)
381	-- We might have read in the whole file, this won't be needed any more.
382	io.close(f)
383
384	if text == nil and not silent then
385		print(MSG_FAILREADCFG:format(name))
386	end
387	return text
388end
389
390local function checkNextboot()
391	local nextboot_file = loader.getenv("nextboot_conf")
392	local nextboot_enable = loader.getenv("nextboot_enable")
393
394	if nextboot_file == nil then
395		return
396	end
397
398	-- is nextboot_enable set in nvstore?
399	if nextboot_enable == "NO" then
400		return
401	end
402
403	local text = readFile(nextboot_file, true)
404	if text == nil then
405		return
406	end
407
408	if nextboot_enable == nil and
409	    text:match("^nextboot_enable=\"NO\"") ~= nil then
410		-- We're done; nextboot is not enabled
411		return
412	end
413
414	if not config.parse(text) then
415		print(MSG_FAILPARSECFG:format(nextboot_file))
416	end
417
418	-- Attempt to rewrite the first line and only the first line of the
419	-- nextboot_file. We overwrite it with nextboot_enable="NO", then
420	-- check for that on load.
421	-- It's worth noting that this won't work on every filesystem, so we
422	-- won't do anything notable if we have any errors in this process.
423	local nfile = io.open(nextboot_file, 'w')
424	if nfile ~= nil then
425		-- We need the trailing space here to account for the extra
426		-- character taken up by the string nextboot_enable="YES"
427		-- Or new end quotation mark lands on the S, and we want to
428		-- rewrite the entirety of the first line.
429		io.write(nfile, "nextboot_enable=\"NO\" ")
430		io.close(nfile)
431	end
432	loader.setenv("nextboot_enable", "NO")
433end
434
435-- Module exports
436config.verbose = false
437
438-- The first item in every carousel is always the default item.
439function config.getCarouselIndex(id)
440	return carousel_choices[id] or 1
441end
442
443function config.setCarouselIndex(id, idx)
444	carousel_choices[id] = idx
445end
446
447-- Returns true if we processed the file successfully, false if we did not.
448-- If 'silent' is true, being unable to read the file is not considered a
449-- failure.
450function config.processFile(name, silent)
451	if silent == nil then
452		silent = false
453	end
454
455	local text = readFile(name, silent)
456	if text == nil then
457		return silent
458	end
459
460	return config.parse(text)
461end
462
463-- silent runs will not return false if we fail to open the file
464function config.parse(text)
465	local n = 1
466	local status = true
467
468	for line in text:gmatch("([^\n]+)") do
469		if line:match("^%s*$") == nil then
470			for _, val in ipairs(pattern_table) do
471				local pattern = '^%s*' .. val.str .. '%s*(.*)';
472				local cgroups = val.groups or 2
473				local k, v, c = checkPattern(line, pattern)
474				if k ~= nil then
475					-- Offset by one, drats
476					if cgroups == 1 then
477						c = v
478						v = nil
479					end
480
481					if isValidComment(c) then
482						val.process(k, v)
483						goto nextline
484					end
485
486					break
487				end
488			end
489
490			print(MSG_MALFORMED:format(n, line))
491			status = false
492		end
493		::nextline::
494		n = n + 1
495	end
496
497	return status
498end
499
500function config.readConf(file, loaded_files)
501	if loaded_files == nil then
502		loaded_files = {}
503	end
504
505	if loaded_files[file] ~= nil then
506		return
507	end
508
509	print("Loading " .. file)
510
511	-- The final value of loader_conf_files is not important, so just
512	-- clobber it here.  We'll later check if it's no longer nil and process
513	-- the new value for files to read.
514	setEnv("loader_conf_files", nil)
515
516	-- These may or may not exist, and that's ok. Do a
517	-- silent parse so that we complain on parse errors but
518	-- not for them simply not existing.
519	if not config.processFile(file, true) then
520		print(MSG_FAILPARSECFG:format(file))
521	end
522
523	loaded_files[file] = true
524
525	-- Going to process "loader_conf_files" extra-files
526	local loader_conf_files = getEnv("loader_conf_files")
527	if loader_conf_files ~= nil then
528		for name in loader_conf_files:gmatch("[%w%p]+") do
529			config.readConf(name, loaded_files)
530		end
531	end
532end
533
534-- other_kernel is optionally the name of a kernel to load, if not the default
535-- or autoloaded default from the module_path
536function config.loadKernel(other_kernel)
537	local flags = loader.getenv("kernel_options") or ""
538	local kernel = other_kernel or loader.getenv("kernel")
539
540	local function tryLoad(names)
541		for name in names:gmatch("([^;]+)%s*;?") do
542			local r = loader.perform("load " .. name ..
543			     " " .. flags)
544			if r == 0 then
545				return name
546			end
547		end
548		return nil
549	end
550
551	local function getModulePath()
552		local module_path = loader.getenv("module_path")
553		local kernel_path = loader.getenv("kernel_path")
554
555		if kernel_path == nil then
556			return module_path
557		end
558
559		-- Strip the loaded kernel path from module_path. This currently assumes
560		-- that the kernel path will be prepended to the module_path when it's
561		-- found.
562		kernel_path = escapeName(kernel_path .. ';')
563		return module_path:gsub(kernel_path, '')
564	end
565
566	local function loadBootfile()
567		local bootfile = loader.getenv("bootfile")
568
569		-- append default kernel name
570		if bootfile == nil then
571			bootfile = "kernel"
572		else
573			bootfile = bootfile .. ";kernel"
574		end
575
576		return tryLoad(bootfile)
577	end
578
579	-- kernel not set, try load from default module_path
580	if kernel == nil then
581		local res = loadBootfile()
582
583		if res ~= nil then
584			-- Default kernel is loaded
585			config.kernel_loaded = nil
586			return true
587		else
588			print(MSG_DEFAULTKERNFAIL)
589			return false
590		end
591	else
592		-- Use our cached module_path, so we don't end up with multiple
593		-- automatically added kernel paths to our final module_path
594		local module_path = getModulePath()
595		local res
596
597		if other_kernel ~= nil then
598			kernel = other_kernel
599		end
600		-- first try load kernel with module_path = /boot/${kernel}
601		-- then try load with module_path=${kernel}
602		local paths = {"/boot/" .. kernel, kernel}
603
604		for _, v in pairs(paths) do
605			loader.setenv("module_path", v)
606			res = loadBootfile()
607
608			-- succeeded, add path to module_path
609			if res ~= nil then
610				config.kernel_loaded = kernel
611				if module_path ~= nil then
612					loader.setenv("module_path", v .. ";" ..
613					    module_path)
614					loader.setenv("kernel_path", v)
615				end
616				return true
617			end
618		end
619
620		-- failed to load with ${kernel} as a directory
621		-- try as a file
622		res = tryLoad(kernel)
623		if res ~= nil then
624			config.kernel_loaded = kernel
625			return true
626		else
627			print(MSG_KERNFAIL:format(kernel))
628			return false
629		end
630	end
631end
632
633function config.selectKernel(kernel)
634	config.kernel_selected = kernel
635end
636
637function config.load(file, reloading)
638	if not file then
639		file = "/boot/defaults/loader.conf"
640	end
641
642	config.readConf(file)
643
644	checkNextboot()
645
646	local verbose = loader.getenv("verbose_loading") or "no"
647	config.verbose = verbose:lower() == "yes"
648	if not reloading then
649		hook.runAll("config.loaded")
650	end
651end
652
653-- Reload configuration
654function config.reload(file)
655	modules = {}
656	restoreEnv()
657	config.load(file, true)
658	hook.runAll("config.reloaded")
659end
660
661function config.loadelf()
662	local xen_kernel = loader.getenv('xen_kernel')
663	local kernel = config.kernel_selected or config.kernel_loaded
664	local status
665
666	if xen_kernel ~= nil then
667		print(MSG_XENKERNLOADING)
668		if cli_execute_unparsed('load ' .. xen_kernel) ~= 0 then
669			print(MSG_XENKERNFAIL:format(xen_kernel))
670			return false
671		end
672	end
673	print(MSG_KERNLOADING)
674	if not config.loadKernel(kernel) then
675		return false
676	end
677	hook.runAll("kernel.loaded")
678
679	print(MSG_MODLOADING)
680	status = loadModule(modules, not config.verbose)
681	hook.runAll("modules.loaded")
682	return status
683end
684
685hook.registerType("config.loaded")
686hook.registerType("config.reloaded")
687hook.registerType("kernel.loaded")
688hook.registerType("modules.loaded")
689return config
690