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