xref: /freebsd/stand/lua/config.lua (revision 5bf5ca772c6de2d53344a78cf461447cc322ccea)
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 loader.perform(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 = {}
200
201-- The first item in every carousel is always the default item.
202function config.getCarouselIndex(id)
203	local val = carousel_choices[id]
204	if val == nil then
205		return 1
206	end
207	return val
208end
209
210function config.setCarouselIndex(id, idx)
211	carousel_choices[id] = idx
212end
213
214function config.restoreEnv()
215	-- Examine changed environment variables
216	for k, v in pairs(config.env_changed) do
217		local restore_value = config.env_restore[k]
218		if restore_value == nil then
219			-- This one doesn't need restored for some reason
220			goto continue
221		end
222		local current_value = loader.getenv(k)
223		if current_value ~= v then
224			-- This was overwritten by some action taken on the menu
225			-- most likely; we'll leave it be.
226			goto continue
227		end
228		restore_value = restore_value.value
229		if restore_value ~= nil then
230			loader.setenv(k, restore_value)
231		else
232			loader.unsetenv(k)
233		end
234		::continue::
235	end
236
237	config.env_changed = {}
238	config.env_restore = {}
239end
240
241function config.setenv(key, value)
242	-- Track the original value for this if we haven't already
243	if config.env_restore[key] == nil then
244		config.env_restore[key] = {value = loader.getenv(key)}
245	end
246
247	config.env_changed[key] = value
248
249	return loader.setenv(key, value)
250end
251
252-- name here is one of 'name', 'type', flags', 'before', 'after', or 'error.'
253-- These are set from lines in loader.conf(5): ${key}_${name}="${value}" where
254-- ${key} is a module name.
255function config.setKey(key, name, value)
256	if modules[key] == nil then
257		modules[key] = {}
258	end
259	modules[key][name] = value
260end
261
262function config.isValidComment(line)
263	if line ~= nil then
264		local s = line:match("^%s*#.*")
265		if s == nil then
266			s = line:match("^%s*$")
267		end
268		if s == nil then
269			return false
270		end
271	end
272	return true
273end
274
275function config.loadmod(mod, silent)
276	local status = true
277	local pstatus
278	for k, v in pairs(mod) do
279		if v.load == "YES" then
280			local str = "load "
281			if v.flags ~= nil then
282				str = str .. v.flags .. " "
283			end
284			if v.type ~= nil then
285				str = str .. "-t " .. v.type .. " "
286			end
287			if v.name ~= nil then
288				str = str .. v.name
289			else
290				str = str .. k
291			end
292			if v.before ~= nil then
293				pstatus = loader.perform(v.before) == 0
294				if not pstatus and not silent then
295					print(MSG_FAILEXBEF:format(v.before, k))
296				end
297				status = status and pstatus
298			end
299
300			if loader.perform(str) ~= 0 then
301				if not silent then
302					print(MSG_FAILEXMOD:format(str))
303				end
304				if v.error ~= nil then
305					loader.perform(v.error)
306				end
307				status = false
308			end
309
310			if v.after ~= nil then
311				pstatus = loader.perform(v.after) == 0
312				if not pstatus and not silent then
313					print(MSG_FAILEXAF:format(v.after, k))
314				end
315				status = status and pstatus
316			end
317
318--		else
319--			if not silent then
320--				print("Skipping module '". . k .. "'")
321--			end
322		end
323	end
324
325	return status
326end
327
328-- Returns true if we processed the file successfully, false if we did not.
329-- If 'silent' is true, being unable to read the file is not considered a
330-- failure.
331function config.processFile(name, silent)
332	if silent == nil then
333		silent = false
334	end
335
336	local text = readFile(name, silent)
337	if text == nil then
338		return silent
339	end
340
341	return config.parse(text)
342end
343
344-- silent runs will not return false if we fail to open the file
345function config.parse(text)
346	local n = 1
347	local status = true
348
349	for line in text:gmatch("([^\n]+)") do
350		if line:match("^%s*$") == nil then
351			local found = false
352
353			for _, val in ipairs(pattern_table) do
354				local k, v, c = line:match(val.str)
355				if k ~= nil then
356					found = true
357
358					if config.isValidComment(c) then
359						val.process(k, v)
360					else
361						print(MSG_MALFORMED:format(n,
362						    line))
363						status = false
364					end
365
366					break
367				end
368			end
369
370			if not found then
371				print(MSG_MALFORMED:format(n, line))
372				status = false
373			end
374		end
375		n = n + 1
376	end
377
378	return status
379end
380
381-- other_kernel is optionally the name of a kernel to load, if not the default
382-- or autoloaded default from the module_path
383function config.loadKernel(other_kernel)
384	local flags = loader.getenv("kernel_options") or ""
385	local kernel = other_kernel or loader.getenv("kernel")
386
387	local function tryLoad(names)
388		for name in names:gmatch("([^;]+)%s*;?") do
389			local r = loader.perform("load " .. flags ..
390			    " " .. name)
391			if r == 0 then
392				return name
393			end
394		end
395		return nil
396	end
397
398	local function loadBootfile()
399		local bootfile = loader.getenv("bootfile")
400
401		-- append default kernel name
402		if bootfile == nil then
403			bootfile = "kernel"
404		else
405			bootfile = bootfile .. ";kernel"
406		end
407
408		return tryLoad(bootfile)
409	end
410
411	-- kernel not set, try load from default module_path
412	if kernel == nil then
413		local res = loadBootfile()
414
415		if res ~= nil then
416			-- Default kernel is loaded
417			config.kernel_loaded = nil
418			return true
419		else
420			print(MSG_DEFAULTKERNFAIL)
421			return false
422		end
423	else
424		-- Use our cached module_path, so we don't end up with multiple
425		-- automatically added kernel paths to our final module_path
426		local module_path = config.module_path
427		local res
428
429		if other_kernel ~= nil then
430			kernel = other_kernel
431		end
432		-- first try load kernel with module_path = /boot/${kernel}
433		-- then try load with module_path=${kernel}
434		local paths = {"/boot/" .. kernel, kernel}
435
436		for _, v in pairs(paths) do
437			loader.setenv("module_path", v)
438			res = loadBootfile()
439
440			-- succeeded, add path to module_path
441			if res ~= nil then
442				config.kernel_loaded = kernel
443				if module_path ~= nil then
444					loader.setenv("module_path", v .. ";" ..
445					    module_path)
446				end
447				return true
448			end
449		end
450
451		-- failed to load with ${kernel} as a directory
452		-- try as a file
453		res = tryLoad(kernel)
454		if res ~= nil then
455			config.kernel_loaded = kernel
456			return true
457		else
458			print(MSG_KERNFAIL:format(kernel))
459			return false
460		end
461	end
462end
463
464function config.selectKernel(kernel)
465	config.kernel_selected = kernel
466end
467
468function config.load(file)
469	if not file then
470		file = "/boot/defaults/loader.conf"
471	end
472
473	if not config.processFile(file) then
474		print(MSG_FAILPARSECFG:format(file))
475	end
476
477	local f = loader.getenv("loader_conf_files")
478	if f ~= nil then
479		for name in f:gmatch("([%w%p]+)%s*") do
480			-- These may or may not exist, and that's ok. Do a
481			-- silent parse so that we complain on parse errors but
482			-- not for them simply not existing.
483			if not config.processFile(name, true) then
484				print(MSG_FAILPARSECFG:format(name))
485			end
486		end
487	end
488
489	checkNextboot()
490
491	-- Cache the provided module_path at load time for later use
492	config.module_path = loader.getenv("module_path")
493end
494
495-- Reload configuration
496function config.reload(file)
497	modules = {}
498	config.restoreEnv()
499	config.load(file)
500end
501
502function config.loadelf()
503	local kernel = config.kernel_selected or config.kernel_loaded
504	local loaded
505
506	print(MSG_KERNLOADING)
507	loaded = config.loadKernel(kernel)
508
509	if not loaded then
510		return
511	end
512
513	print(MSG_MODLOADING)
514	if not config.loadmod(modules) then
515		print(MSG_MODLOADFAIL)
516	end
517end
518
519return config
520