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 -- Escapes the named value for use as a literal in a replacement pattern.
106 -- e.g. dhcp.host-name gets turned into dhcp%.host%-name to remove the special
108 local function escapeName(name)
109 return name:gsub("([%p])", "%%%1")
112 local function processEnvVar(value)
113 for name in value:gmatch("${([^}]+)}") do
114 local replacement = loader.getenv(name) or ""
115 value = value:gsub("${" .. escapeName(name) .. "}", replacement)
117 for name in value:gmatch("$([%w%p]+)%s*") do
118 local replacement = loader.getenv(name) or ""
119 value = value:gsub("$" .. escapeName(name), replacement)
124 local pattern_table = {
127 process = function(_, _) end,
129 -- module_load="value"
131 str = "^%s*([%w_]+)_load%s*=%s*\"([%w%s%p]-)\"%s*(.*)",
132 process = function(k, v)
133 if modules[k] == nil then
136 modules[k].load = v:upper()
139 -- module_name="value"
141 str = "^%s*([%w_]+)_name%s*=%s*\"([%w%s%p]-)\"%s*(.*)",
142 process = function(k, v)
146 -- module_type="value"
148 str = "^%s*([%w_]+)_type%s*=%s*\"([%w%s%p]-)\"%s*(.*)",
149 process = function(k, v)
153 -- module_flags="value"
155 str = "^%s*([%w_]+)_flags%s*=%s*\"([%w%s%p]-)\"%s*(.*)",
156 process = function(k, v)
157 setKey(k, "flags", v)
160 -- module_before="value"
162 str = "^%s*([%w_]+)_before%s*=%s*\"([%w%s%p]-)\"%s*(.*)",
163 process = function(k, v)
164 setKey(k, "before", v)
167 -- module_after="value"
169 str = "^%s*([%w_]+)_after%s*=%s*\"([%w%s%p]-)\"%s*(.*)",
170 process = function(k, v)
171 setKey(k, "after", v)
174 -- module_error="value"
176 str = "^%s*([%w_]+)_error%s*=%s*\"([%w%s%p]-)\"%s*(.*)",
177 process = function(k, v)
178 setKey(k, "error", v)
183 str = "^%s*exec%s*=%s*\"([%w%s%p]-)\"%s*(.*)",
184 process = function(k, _)
185 if cli_execute_unparsed(k) ~= 0 then
186 print(MSG_FAILEXEC:format(k))
192 str = "^%s*([%w%p]+)%s*=%s*\"([%w%s%p]-)\"%s*(.*)",
193 process = function(k, v)
194 if setEnv(k, processEnvVar(v)) ~= 0 then
195 print(MSG_FAILSETENV:format(k, v))
201 str = "^%s*([%w%p]+)%s*=%s*(%d+)%s*(.*)",
202 process = function(k, v)
203 if setEnv(k, processEnvVar(v)) ~= 0 then
204 print(MSG_FAILSETENV:format(k, tostring(v)))
210 local function isValidComment(line)
212 local s = line:match("^%s*#.*")
214 s = line:match("^%s*$")
223 local function loadModule(mod, silent)
226 for k, v in pairs(mod) do
227 if v.load ~= nil and v.load:lower() == "yes" then
229 if v.type ~= nil then
230 str = str .. "-t " .. v.type .. " "
232 if v.name ~= nil then
237 if v.flags ~= nil then
238 str = str .. " " .. v.flags
240 if v.before ~= nil then
241 pstatus = cli_execute_unparsed(v.before) == 0
242 if not pstatus and not silent then
243 print(MSG_FAILEXBEF:format(v.before, k))
245 status = status and pstatus
248 if cli_execute_unparsed(str) ~= 0 then
250 print(MSG_FAILEXMOD:format(str))
252 if v.error ~= nil then
253 cli_execute_unparsed(v.error)
258 if v.after ~= nil then
259 pstatus = cli_execute_unparsed(v.after) == 0
260 if not pstatus and not silent then
261 print(MSG_FAILEXAF:format(v.after, k))
263 status = status and pstatus
272 local function readConfFiles(loaded_files)
273 local f = loader.getenv("loader_conf_files")
275 for name in f:gmatch("([%w%p]+)%s*") do
276 if loaded_files[name] ~= nil then
280 local prefiles = loader.getenv("loader_conf_files")
282 print("Loading " .. name)
283 -- These may or may not exist, and that's ok. Do a
284 -- silent parse so that we complain on parse errors but
285 -- not for them simply not existing.
286 if not config.processFile(name, true) then
287 print(MSG_FAILPARSECFG:format(name))
290 loaded_files[name] = true
291 local newfiles = loader.getenv("loader_conf_files")
292 if prefiles ~= newfiles then
293 readConfFiles(loaded_files)
300 local function readFile(name, silent)
301 local f = io.open(name)
304 print(MSG_FAILOPENCFG:format(name))
309 local text, _ = io.read(f)
310 -- We might have read in the whole file, this won't be needed any more.
313 if text == nil and not silent then
314 print(MSG_FAILREADCFG:format(name))
319 local function checkNextboot()
320 local nextboot_file = loader.getenv("nextboot_conf")
321 if nextboot_file == nil then
325 local text = readFile(nextboot_file, true)
330 if text:match("^nextboot_enable=\"NO\"") ~= nil then
331 -- We're done; nextboot is not enabled
335 if not config.parse(text) then
336 print(MSG_FAILPARSECFG:format(nextboot_file))
339 -- Attempt to rewrite the first line and only the first line of the
340 -- nextboot_file. We overwrite it with nextboot_enable="NO", then
341 -- check for that on load.
342 -- It's worth noting that this won't work on every filesystem, so we
343 -- won't do anything notable if we have any errors in this process.
344 local nfile = io.open(nextboot_file, 'w')
346 -- We need the trailing space here to account for the extra
347 -- character taken up by the string nextboot_enable="YES"
348 -- Or new end quotation mark lands on the S, and we want to
349 -- rewrite the entirety of the first line.
350 io.write(nfile, "nextboot_enable=\"NO\" ")
356 config.verbose = false
358 -- The first item in every carousel is always the default item.
359 function config.getCarouselIndex(id)
360 return carousel_choices[id] or 1
363 function config.setCarouselIndex(id, idx)
364 carousel_choices[id] = idx
367 -- Returns true if we processed the file successfully, false if we did not.
368 -- If 'silent' is true, being unable to read the file is not considered a
370 function config.processFile(name, silent)
371 if silent == nil then
375 local text = readFile(name, silent)
380 return config.parse(text)
383 -- silent runs will not return false if we fail to open the file
384 function config.parse(text)
388 for line in text:gmatch("([^\n]+)") do
389 if line:match("^%s*$") == nil then
392 for _, val in ipairs(pattern_table) do
393 local k, v, c = line:match(val.str)
397 if isValidComment(c) then
400 print(MSG_MALFORMED:format(n,
410 print(MSG_MALFORMED:format(n, line))
420 -- other_kernel is optionally the name of a kernel to load, if not the default
421 -- or autoloaded default from the module_path
422 function config.loadKernel(other_kernel)
423 local flags = loader.getenv("kernel_options") or ""
424 local kernel = other_kernel or loader.getenv("kernel")
426 local function tryLoad(names)
427 for name in names:gmatch("([^;]+)%s*;?") do
428 local r = loader.perform("load " .. name ..
437 local function loadBootfile()
438 local bootfile = loader.getenv("bootfile")
440 -- append default kernel name
441 if bootfile == nil then
444 bootfile = bootfile .. ";kernel"
447 return tryLoad(bootfile)
450 -- kernel not set, try load from default module_path
451 if kernel == nil then
452 local res = loadBootfile()
455 -- Default kernel is loaded
456 config.kernel_loaded = nil
459 print(MSG_DEFAULTKERNFAIL)
463 -- Use our cached module_path, so we don't end up with multiple
464 -- automatically added kernel paths to our final module_path
465 local module_path = config.module_path
468 if other_kernel ~= nil then
469 kernel = other_kernel
471 -- first try load kernel with module_path = /boot/${kernel}
472 -- then try load with module_path=${kernel}
473 local paths = {"/boot/" .. kernel, kernel}
475 for _, v in pairs(paths) do
476 loader.setenv("module_path", v)
479 -- succeeded, add path to module_path
481 config.kernel_loaded = kernel
482 if module_path ~= nil then
483 loader.setenv("module_path", v .. ";" ..
490 -- failed to load with ${kernel} as a directory
492 res = tryLoad(kernel)
494 config.kernel_loaded = kernel
497 print(MSG_KERNFAIL:format(kernel))
503 function config.selectKernel(kernel)
504 config.kernel_selected = kernel
507 function config.load(file, reloading)
509 file = "/boot/defaults/loader.conf"
512 if not config.processFile(file) then
513 print(MSG_FAILPARSECFG:format(file))
516 local loaded_files = {file = true}
517 readConfFiles(loaded_files)
521 -- Cache the provided module_path at load time for later use
522 config.module_path = loader.getenv("module_path")
523 local verbose = loader.getenv("verbose_loading") or "no"
524 config.verbose = verbose:lower() == "yes"
525 if not reloading then
526 hook.runAll("config.loaded")
530 -- Reload configuration
531 function config.reload(file)
534 config.load(file, true)
535 hook.runAll("config.reloaded")
538 function config.loadelf()
539 local kernel = config.kernel_selected or config.kernel_loaded
542 print(MSG_KERNLOADING)
543 loaded = config.loadKernel(kernel)
549 print(MSG_MODLOADING)
550 if not loadModule(modules, not config.verbose) then
551 print(MSG_MODLOADFAIL)
555 hook.registerType("config.loaded")
556 hook.registerType("config.reloaded")