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