xref: /freebsd/stand/lua/config.lua (revision 74fe6c29fb7eef3418d7919dcd41dc1a04a982a1)
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 config = {}
33local modules = {}
34local carousel_choices = {}
35
36local MSG_FAILEXEC = "Failed to exec '%s'"
37local MSG_FAILSETENV = "Failed to '%s' with value: %s"
38local MSG_FAILOPENCFG = "Failed to open config: '%s'"
39local MSG_FAILREADCFG = "Failed to read config: '%s'"
40local MSG_FAILPARSECFG = "Failed to parse config: '%s'"
41local MSG_FAILEXBEF = "Failed to execute '%s' before loading '%s'"
42local MSG_FAILEXMOD = "Failed to execute '%s'"
43local MSG_FAILEXAF = "Failed to execute '%s' after loading '%s'"
44local MSG_MALFORMED = "Malformed line (%d):\n\t'%s'"
45local MSG_DEFAULTKERNFAIL = "No kernel set, failed to load from module_path"
46local MSG_KERNFAIL = "Failed to load kernel '%s'"
47local MSG_KERNLOADING = "Loading kernel..."
48local MSG_MODLOADING = "Loading configured modules..."
49local MSG_MODLOADFAIL = "Could not load one or more modules!"
50
51local pattern_table = {
52	{
53		str = "^%s*(#.*)",
54		process = function(_, _)  end,
55	},
56	--  module_load="value"
57	{
58		str = "^%s*([%w_]+)_load%s*=%s*\"([%w%s%p]-)\"%s*(.*)",
59		process = function(k, v)
60			if modules[k] == nil then
61				modules[k] = {}
62			end
63			modules[k].load = v:upper()
64		end,
65	},
66	--  module_name="value"
67	{
68		str = "^%s*([%w_]+)_name%s*=%s*\"([%w%s%p]-)\"%s*(.*)",
69		process = function(k, v)
70			config.setKey(k, "name", v)
71		end,
72	},
73	--  module_type="value"
74	{
75		str = "^%s*([%w_]+)_type%s*=%s*\"([%w%s%p]-)\"%s*(.*)",
76		process = function(k, v)
77			config.setKey(k, "type", v)
78		end,
79	},
80	--  module_flags="value"
81	{
82		str = "^%s*([%w_]+)_flags%s*=%s*\"([%w%s%p]-)\"%s*(.*)",
83		process = function(k, v)
84			config.setKey(k, "flags", v)
85		end,
86	},
87	--  module_before="value"
88	{
89		str = "^%s*([%w_]+)_before%s*=%s*\"([%w%s%p]-)\"%s*(.*)",
90		process = function(k, v)
91			config.setKey(k, "before", v)
92		end,
93	},
94	--  module_after="value"
95	{
96		str = "^%s*([%w_]+)_after%s*=%s*\"([%w%s%p]-)\"%s*(.*)",
97		process = function(k, v)
98			config.setKey(k, "after", v)
99		end,
100	},
101	--  module_error="value"
102	{
103		str = "^%s*([%w_]+)_error%s*=%s*\"([%w%s%p]-)\"%s*(.*)",
104		process = function(k, v)
105			config.setKey(k, "error", v)
106		end,
107	},
108	--  exec="command"
109	{
110		str = "^%s*exec%s*=%s*\"([%w%s%p]-)\"%s*(.*)",
111		process = function(k, _)
112			if cli_execute_unparsed(k) ~= 0 then
113				print(MSG_FAILEXEC:format(k))
114			end
115		end,
116	},
117	--  env_var="value"
118	{
119		str = "^%s*([%w%p]+)%s*=%s*\"([%w%s%p]-)\"%s*(.*)",
120		process = function(k, v)
121			if config.setenv(k, v) ~= 0 then
122				print(MSG_FAILSETENV:format(k, v))
123			end
124		end,
125	},
126	--  env_var=num
127	{
128		str = "^%s*([%w%p]+)%s*=%s*(%d+)%s*(.*)",
129		process = function(k, v)
130			if config.setenv(k, v) ~= 0 then
131				print(MSG_FAILSETENV:format(k, tostring(v)))
132			end
133		end,
134	},
135}
136
137local function readFile(name, silent)
138	local f = io.open(name)
139	if f == nil then
140		if not silent then
141			print(MSG_FAILOPENCFG:format(name))
142		end
143		return nil
144	end
145
146	local text, _ = io.read(f)
147	-- We might have read in the whole file, this won't be needed any more.
148	io.close(f)
149
150	if text == nil then
151		if not silent then
152			print(MSG_FAILREADCFG:format(name))
153		end
154		return nil
155	end
156	return text
157end
158
159local function checkNextboot()
160	local nextboot_file = loader.getenv("nextboot_file")
161	if nextboot_file == nil then
162		return
163	end
164
165	local text = readFile(nextboot_file, true)
166	if text == nil then
167		return
168	end
169
170	if text:match("^nextboot_enable=\"NO\"") ~= nil then
171		-- We're done; nextboot is not enabled
172		return
173	end
174
175	if not config.parse(text) then
176		print(MSG_FAILPARSECFG:format(nextboot_file))
177	end
178
179	-- Attempt to rewrite the first line and only the first line of the
180	-- nextboot_file. We overwrite it with nextboot_enable="NO", then
181	-- check for that on load.
182	-- It's worth noting that this won't work on every filesystem, so we
183	-- won't do anything notable if we have any errors in this process.
184	local nfile = io.open(nextboot_file, 'w')
185	if nfile ~= nil then
186		-- We need the trailing space here to account for the extra
187		-- character taken up by the string nextboot_enable="YES"
188		-- Or new end quotation mark lands on the S, and we want to
189		-- rewrite the entirety of the first line.
190		io.write(nfile, "nextboot_enable=\"NO\" ")
191		io.close(nfile)
192	end
193end
194
195-- Module exports
196-- Which variables we changed
197config.env_changed = {}
198-- Values to restore env to (nil to unset)
199config.env_restore = {}
200config.verbose = false
201
202-- The first item in every carousel is always the default item.
203function config.getCarouselIndex(id)
204	local val = carousel_choices[id]
205	if val == nil then
206		return 1
207	end
208	return val
209end
210
211function config.setCarouselIndex(id, idx)
212	carousel_choices[id] = idx
213end
214
215function config.restoreEnv()
216	-- Examine changed environment variables
217	for k, v in pairs(config.env_changed) do
218		local restore_value = config.env_restore[k]
219		if restore_value == nil then
220			-- This one doesn't need restored for some reason
221			goto continue
222		end
223		local current_value = loader.getenv(k)
224		if current_value ~= v then
225			-- This was overwritten by some action taken on the menu
226			-- most likely; we'll leave it be.
227			goto continue
228		end
229		restore_value = restore_value.value
230		if restore_value ~= nil then
231			loader.setenv(k, restore_value)
232		else
233			loader.unsetenv(k)
234		end
235		::continue::
236	end
237
238	config.env_changed = {}
239	config.env_restore = {}
240end
241
242function config.setenv(key, value)
243	-- Track the original value for this if we haven't already
244	if config.env_restore[key] == nil then
245		config.env_restore[key] = {value = loader.getenv(key)}
246	end
247
248	config.env_changed[key] = value
249
250	return loader.setenv(key, value)
251end
252
253-- name here is one of 'name', 'type', flags', 'before', 'after', or 'error.'
254-- These are set from lines in loader.conf(5): ${key}_${name}="${value}" where
255-- ${key} is a module name.
256function config.setKey(key, name, value)
257	if modules[key] == nil then
258		modules[key] = {}
259	end
260	modules[key][name] = value
261end
262
263function config.isValidComment(line)
264	if line ~= nil then
265		local s = line:match("^%s*#.*")
266		if s == nil then
267			s = line:match("^%s*$")
268		end
269		if s == nil then
270			return false
271		end
272	end
273	return true
274end
275
276function config.loadmod(mod, silent)
277	local status = true
278	local pstatus
279	for k, v in pairs(mod) do
280		if v.load == "YES" then
281			local str = "load "
282			if v.flags ~= nil then
283				str = str .. v.flags .. " "
284			end
285			if v.type ~= nil then
286				str = str .. "-t " .. v.type .. " "
287			end
288			if v.name ~= nil then
289				str = str .. v.name
290			else
291				str = str .. k
292			end
293			if v.before ~= nil then
294				pstatus = cli_execute_unparsed(v.before) == 0
295				if not pstatus and not silent then
296					print(MSG_FAILEXBEF:format(v.before, k))
297				end
298				status = status and pstatus
299			end
300
301			if cli_execute_unparsed(str) ~= 0 then
302				if not silent then
303					print(MSG_FAILEXMOD:format(str))
304				end
305				if v.error ~= nil then
306					cli_execute_unparsed(v.error)
307				end
308				status = false
309			end
310
311			if v.after ~= nil then
312				pstatus = cli_execute_unparsed(v.after) == 0
313				if not pstatus and not silent then
314					print(MSG_FAILEXAF:format(v.after, k))
315				end
316				status = status and pstatus
317			end
318
319--		else
320--			if not silent then
321--				print("Skipping module '". . k .. "'")
322--			end
323		end
324	end
325
326	return status
327end
328
329-- Returns true if we processed the file successfully, false if we did not.
330-- If 'silent' is true, being unable to read the file is not considered a
331-- failure.
332function config.processFile(name, silent)
333	if silent == nil then
334		silent = false
335	end
336
337	local text = readFile(name, silent)
338	if text == nil then
339		return silent
340	end
341
342	return config.parse(text)
343end
344
345-- silent runs will not return false if we fail to open the file
346function config.parse(text)
347	local n = 1
348	local status = true
349
350	for line in text:gmatch("([^\n]+)") do
351		if line:match("^%s*$") == nil then
352			local found = false
353
354			for _, val in ipairs(pattern_table) do
355				local k, v, c = line:match(val.str)
356				if k ~= nil then
357					found = true
358
359					if config.isValidComment(c) then
360						val.process(k, v)
361					else
362						print(MSG_MALFORMED:format(n,
363						    line))
364						status = false
365					end
366
367					break
368				end
369			end
370
371			if not found then
372				print(MSG_MALFORMED:format(n, line))
373				status = false
374			end
375		end
376		n = n + 1
377	end
378
379	return status
380end
381
382-- other_kernel is optionally the name of a kernel to load, if not the default
383-- or autoloaded default from the module_path
384function config.loadKernel(other_kernel)
385	local flags = loader.getenv("kernel_options") or ""
386	local kernel = other_kernel or loader.getenv("kernel")
387
388	local function tryLoad(names)
389		for name in names:gmatch("([^;]+)%s*;?") do
390			local r = loader.perform("load " .. flags ..
391			    " " .. name)
392			if r == 0 then
393				return name
394			end
395		end
396		return nil
397	end
398
399	local function loadBootfile()
400		local bootfile = loader.getenv("bootfile")
401
402		-- append default kernel name
403		if bootfile == nil then
404			bootfile = "kernel"
405		else
406			bootfile = bootfile .. ";kernel"
407		end
408
409		return tryLoad(bootfile)
410	end
411
412	-- kernel not set, try load from default module_path
413	if kernel == nil then
414		local res = loadBootfile()
415
416		if res ~= nil then
417			-- Default kernel is loaded
418			config.kernel_loaded = nil
419			return true
420		else
421			print(MSG_DEFAULTKERNFAIL)
422			return false
423		end
424	else
425		-- Use our cached module_path, so we don't end up with multiple
426		-- automatically added kernel paths to our final module_path
427		local module_path = config.module_path
428		local res
429
430		if other_kernel ~= nil then
431			kernel = other_kernel
432		end
433		-- first try load kernel with module_path = /boot/${kernel}
434		-- then try load with module_path=${kernel}
435		local paths = {"/boot/" .. kernel, kernel}
436
437		for _, v in pairs(paths) do
438			loader.setenv("module_path", v)
439			res = loadBootfile()
440
441			-- succeeded, add path to module_path
442			if res ~= nil then
443				config.kernel_loaded = kernel
444				if module_path ~= nil then
445					loader.setenv("module_path", v .. ";" ..
446					    module_path)
447				end
448				return true
449			end
450		end
451
452		-- failed to load with ${kernel} as a directory
453		-- try as a file
454		res = tryLoad(kernel)
455		if res ~= nil then
456			config.kernel_loaded = kernel
457			return true
458		else
459			print(MSG_KERNFAIL:format(kernel))
460			return false
461		end
462	end
463end
464
465function config.selectKernel(kernel)
466	config.kernel_selected = kernel
467end
468
469function config.load(file)
470	if not file then
471		file = "/boot/defaults/loader.conf"
472	end
473
474	if not config.processFile(file) then
475		print(MSG_FAILPARSECFG:format(file))
476	end
477
478	local f = loader.getenv("loader_conf_files")
479	if f ~= nil then
480		for name in f:gmatch("([%w%p]+)%s*") do
481			-- These may or may not exist, and that's ok. Do a
482			-- silent parse so that we complain on parse errors but
483			-- not for them simply not existing.
484			if not config.processFile(name, true) then
485				print(MSG_FAILPARSECFG:format(name))
486			end
487		end
488	end
489
490	checkNextboot()
491
492	-- Cache the provided module_path at load time for later use
493	config.module_path = loader.getenv("module_path")
494	local verbose = loader.getenv("verbose_loading")
495	if verbose == nil then
496		verbose = "no"
497	end
498	config.verbose = verbose:lower() == "yes"
499end
500
501-- Reload configuration
502function config.reload(file)
503	modules = {}
504	config.restoreEnv()
505	config.load(file)
506	core.configReloaded()
507end
508
509function config.loadelf()
510	local kernel = config.kernel_selected or config.kernel_loaded
511	local loaded
512
513	print(MSG_KERNLOADING)
514	loaded = config.loadKernel(kernel)
515
516	if not loaded then
517		return
518	end
519
520	print(MSG_MODLOADING)
521	if not config.loadmod(modules, not config.verbose) then
522		print(MSG_MODLOADFAIL)
523	end
524end
525
526return config
527