2 -- SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 -- Copyright (c) 2015 Pedro Souza <pedrosouza@freebsd.org>
5 -- Copyright (C) 2018 Kyle Evans <kevans@FreeBSD.org>
6 -- All rights reserved.
8 -- Redistribution and use in source and binary forms, with or without
9 -- modification, are permitted provided that the following conditions
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.
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
32 local hook = require("hook")
36 local carousel_choices = {}
37 -- Which variables we changed
38 local env_changed = {}
39 -- Values to restore env to (nil to unset)
40 local env_restore = {}
42 local MSG_FAILEXEC = "Failed to exec '%s'"
43 local MSG_FAILSETENV = "Failed to '%s' with value: %s"
44 local MSG_FAILOPENCFG = "Failed to open config: '%s'"
45 local MSG_FAILREADCFG = "Failed to read config: '%s'"
46 local MSG_FAILPARSECFG = "Failed to parse config: '%s'"
47 local MSG_FAILEXBEF = "Failed to execute '%s' before loading '%s'"
48 local MSG_FAILEXMOD = "Failed to execute '%s'"
49 local MSG_FAILEXAF = "Failed to execute '%s' after loading '%s'"
50 local MSG_MALFORMED = "Malformed line (%d):\n\t'%s'"
51 local MSG_DEFAULTKERNFAIL = "No kernel set, failed to load from module_path"
52 local MSG_KERNFAIL = "Failed to load kernel '%s'"
53 local MSG_KERNLOADING = "Loading kernel..."
54 local MSG_MODLOADING = "Loading configured modules..."
55 local MSG_MODLOADFAIL = "Could not load one or more modules!"
57 local function restoreEnv()
58 -- Examine changed environment variables
59 for k, v in pairs(env_changed) do
60 local restore_value = env_restore[k]
61 if restore_value == nil then
62 -- This one doesn't need restored for some reason
65 local current_value = loader.getenv(k)
66 if current_value ~= v then
67 -- This was overwritten by some action taken on the menu
68 -- most likely; we'll leave it be.
71 restore_value = restore_value.value
72 if restore_value ~= nil then
73 loader.setenv(k, restore_value)
84 local function setEnv(key, value)
85 -- Track the original value for this if we haven't already
86 if env_restore[key] == nil then
87 env_restore[key] = {value = loader.getenv(key)}
90 env_changed[key] = value
92 return loader.setenv(key, value)
95 -- name here is one of 'name', 'type', flags', 'before', 'after', or 'error.'
96 -- These are set from lines in loader.conf(5): ${key}_${name}="${value}" where
97 -- ${key} is a module name.
98 local function setKey(key, name, value)
99 if modules[key] == nil then
102 modules[key][name] = value
105 local pattern_table = {
108 process = function(_, _) end,
110 -- module_load="value"
112 str = "^%s*([%w_]+)_load%s*=%s*\"([%w%s%p]-)\"%s*(.*)",
113 process = function(k, v)
114 if modules[k] == nil then
117 modules[k].load = v:upper()
120 -- module_name="value"
122 str = "^%s*([%w_]+)_name%s*=%s*\"([%w%s%p]-)\"%s*(.*)",
123 process = function(k, v)
127 -- module_type="value"
129 str = "^%s*([%w_]+)_type%s*=%s*\"([%w%s%p]-)\"%s*(.*)",
130 process = function(k, v)
134 -- module_flags="value"
136 str = "^%s*([%w_]+)_flags%s*=%s*\"([%w%s%p]-)\"%s*(.*)",
137 process = function(k, v)
138 setKey(k, "flags", v)
141 -- module_before="value"
143 str = "^%s*([%w_]+)_before%s*=%s*\"([%w%s%p]-)\"%s*(.*)",
144 process = function(k, v)
145 setKey(k, "before", v)
148 -- module_after="value"
150 str = "^%s*([%w_]+)_after%s*=%s*\"([%w%s%p]-)\"%s*(.*)",
151 process = function(k, v)
152 setKey(k, "after", v)
155 -- module_error="value"
157 str = "^%s*([%w_]+)_error%s*=%s*\"([%w%s%p]-)\"%s*(.*)",
158 process = function(k, v)
159 setKey(k, "error", v)
164 str = "^%s*exec%s*=%s*\"([%w%s%p]-)\"%s*(.*)",
165 process = function(k, _)
166 if cli_execute_unparsed(k) ~= 0 then
167 print(MSG_FAILEXEC:format(k))
173 str = "^%s*([%w%p]+)%s*=%s*\"([%w%s%p]-)\"%s*(.*)",
174 process = function(k, v)
175 if setEnv(k, v) ~= 0 then
176 print(MSG_FAILSETENV:format(k, v))
182 str = "^%s*([%w%p]+)%s*=%s*(%d+)%s*(.*)",
183 process = function(k, v)
184 if setEnv(k, v) ~= 0 then
185 print(MSG_FAILSETENV:format(k, tostring(v)))
191 local function isValidComment(line)
193 local s = line:match("^%s*#.*")
195 s = line:match("^%s*$")
204 local function loadModule(mod, silent)
207 for k, v in pairs(mod) do
208 if v.load ~= nil and v.load:lower() == "yes" then
210 if v.flags ~= nil then
211 str = str .. v.flags .. " "
213 if v.type ~= nil then
214 str = str .. "-t " .. v.type .. " "
216 if v.name ~= nil then
221 if v.before ~= nil then
222 pstatus = cli_execute_unparsed(v.before) == 0
223 if not pstatus and not silent then
224 print(MSG_FAILEXBEF:format(v.before, k))
226 status = status and pstatus
229 if cli_execute_unparsed(str) ~= 0 then
231 print(MSG_FAILEXMOD:format(str))
233 if v.error ~= nil then
234 cli_execute_unparsed(v.error)
239 if v.after ~= nil then
240 pstatus = cli_execute_unparsed(v.after) == 0
241 if not pstatus and not silent then
242 print(MSG_FAILEXAF:format(v.after, k))
244 status = status and pstatus
254 local function readFile(name, silent)
255 local f = io.open(name)
258 print(MSG_FAILOPENCFG:format(name))
263 local text, _ = io.read(f)
264 -- We might have read in the whole file, this won't be needed any more.
267 if text == nil and not silent then
268 print(MSG_FAILREADCFG:format(name))
273 local function checkNextboot()
274 local nextboot_file = loader.getenv("nextboot_file")
275 if nextboot_file == nil then
279 local text = readFile(nextboot_file, true)
284 if text:match("^nextboot_enable=\"NO\"") ~= nil then
285 -- We're done; nextboot is not enabled
289 if not config.parse(text) then
290 print(MSG_FAILPARSECFG:format(nextboot_file))
293 -- Attempt to rewrite the first line and only the first line of the
294 -- nextboot_file. We overwrite it with nextboot_enable="NO", then
295 -- check for that on load.
296 -- It's worth noting that this won't work on every filesystem, so we
297 -- won't do anything notable if we have any errors in this process.
298 local nfile = io.open(nextboot_file, 'w')
300 -- We need the trailing space here to account for the extra
301 -- character taken up by the string nextboot_enable="YES"
302 -- Or new end quotation mark lands on the S, and we want to
303 -- rewrite the entirety of the first line.
304 io.write(nfile, "nextboot_enable=\"NO\" ")
310 config.verbose = false
312 -- The first item in every carousel is always the default item.
313 function config.getCarouselIndex(id)
314 return carousel_choices[id] or 1
317 function config.setCarouselIndex(id, idx)
318 carousel_choices[id] = idx
321 -- Returns true if we processed the file successfully, false if we did not.
322 -- If 'silent' is true, being unable to read the file is not considered a
324 function config.processFile(name, silent)
325 if silent == nil then
329 local text = readFile(name, silent)
334 return config.parse(text)
337 -- silent runs will not return false if we fail to open the file
338 function config.parse(text)
342 for line in text:gmatch("([^\n]+)") do
343 if line:match("^%s*$") == nil then
346 for _, val in ipairs(pattern_table) do
347 local k, v, c = line:match(val.str)
351 if isValidComment(c) then
354 print(MSG_MALFORMED:format(n,
364 print(MSG_MALFORMED:format(n, line))
374 -- other_kernel is optionally the name of a kernel to load, if not the default
375 -- or autoloaded default from the module_path
376 function config.loadKernel(other_kernel)
377 local flags = loader.getenv("kernel_options") or ""
378 local kernel = other_kernel or loader.getenv("kernel")
380 local function tryLoad(names)
381 for name in names:gmatch("([^;]+)%s*;?") do
382 local r = loader.perform("load " .. flags ..
391 local function loadBootfile()
392 local bootfile = loader.getenv("bootfile")
394 -- append default kernel name
395 if bootfile == nil then
398 bootfile = bootfile .. ";kernel"
401 return tryLoad(bootfile)
404 -- kernel not set, try load from default module_path
405 if kernel == nil then
406 local res = loadBootfile()
409 -- Default kernel is loaded
410 config.kernel_loaded = nil
413 print(MSG_DEFAULTKERNFAIL)
417 -- Use our cached module_path, so we don't end up with multiple
418 -- automatically added kernel paths to our final module_path
419 local module_path = config.module_path
422 if other_kernel ~= nil then
423 kernel = other_kernel
425 -- first try load kernel with module_path = /boot/${kernel}
426 -- then try load with module_path=${kernel}
427 local paths = {"/boot/" .. kernel, kernel}
429 for _, v in pairs(paths) do
430 loader.setenv("module_path", v)
433 -- succeeded, add path to module_path
435 config.kernel_loaded = kernel
436 if module_path ~= nil then
437 loader.setenv("module_path", v .. ";" ..
444 -- failed to load with ${kernel} as a directory
446 res = tryLoad(kernel)
448 config.kernel_loaded = kernel
451 print(MSG_KERNFAIL:format(kernel))
457 function config.selectKernel(kernel)
458 config.kernel_selected = kernel
461 function config.load(file)
463 file = "/boot/defaults/loader.conf"
466 if not config.processFile(file) then
467 print(MSG_FAILPARSECFG:format(file))
470 local f = loader.getenv("loader_conf_files")
472 for name in f:gmatch("([%w%p]+)%s*") do
473 -- These may or may not exist, and that's ok. Do a
474 -- silent parse so that we complain on parse errors but
475 -- not for them simply not existing.
476 if not config.processFile(name, true) then
477 print(MSG_FAILPARSECFG:format(name))
484 -- Cache the provided module_path at load time for later use
485 config.module_path = loader.getenv("module_path")
486 local verbose = loader.getenv("verbose_loading") or "no"
487 config.verbose = verbose:lower() == "yes"
490 -- Reload configuration
491 function config.reload(file)
495 hook.runAll("config.reloaded")
498 function config.loadelf()
499 local kernel = config.kernel_selected or config.kernel_loaded
502 print(MSG_KERNLOADING)
503 loaded = config.loadKernel(kernel)
509 print(MSG_MODLOADING)
510 if not loadModule(modules, not config.verbose) then
511 print(MSG_MODLOADFAIL)
515 hook.registerType("config.reloaded")