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