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 MODULEEXPR = '([%w-_]+)'
59 local function restoreEnv()
60 -- Examine changed environment variables
61 for k, v in pairs(env_changed) do
62 local restore_value = env_restore[k]
63 if restore_value == nil then
64 -- This one doesn't need restored for some reason
67 local current_value = loader.getenv(k)
68 if current_value ~= v then
69 -- This was overwritten by some action taken on the menu
70 -- most likely; we'll leave it be.
73 restore_value = restore_value.value
74 if restore_value ~= nil then
75 loader.setenv(k, restore_value)
86 local function setEnv(key, value)
87 -- Track the original value for this if we haven't already
88 if env_restore[key] == nil then
89 env_restore[key] = {value = loader.getenv(key)}
92 env_changed[key] = value
94 return loader.setenv(key, value)
97 -- name here is one of 'name', 'type', flags', 'before', 'after', or 'error.'
98 -- These are set from lines in loader.conf(5): ${key}_${name}="${value}" where
99 -- ${key} is a module name.
100 local function setKey(key, name, value)
101 if modules[key] == nil then
104 modules[key][name] = value
107 -- Escapes the named value for use as a literal in a replacement pattern.
108 -- e.g. dhcp.host-name gets turned into dhcp%.host%-name to remove the special
110 local function escapeName(name)
111 return name:gsub("([%p])", "%%%1")
114 local function processEnvVar(value)
115 for name in value:gmatch("${([^}]+)}") do
116 local replacement = loader.getenv(name) or ""
117 value = value:gsub("${" .. escapeName(name) .. "}", replacement)
119 for name in value:gmatch("$([%w%p]+)%s*") do
120 local replacement = loader.getenv(name) or ""
121 value = value:gsub("$" .. escapeName(name), replacement)
126 -- str in this table is a regex pattern. It will automatically be anchored to
127 -- the beginning of a line and any preceding whitespace will be skipped. The
128 -- pattern should have no more than two captures patterns, which correspond to
129 -- the two parameters (usually 'key' and 'value') that are passed to the
130 -- process function. All trailing characters will be validated.
132 -- We have two special entries in this table: the first is the first entry,
133 -- a full-line comment. The second is for 'exec' handling. Both have a single
134 -- capture group, but the difference is that the full-line comment pattern will
135 -- match the entire line. This does not run afoul of the later end of line
136 -- validation that we'll do after a match. However, the 'exec' pattern will.
137 -- We document the exceptions with a special 'groups' index that indicates
138 -- the number of capture groups, if not two. We'll use this later to do
139 -- validation on the proper entry.
140 local pattern_table = {
143 process = function(_, _) end,
146 -- module_load="value"
148 str = MODULEEXPR .. "_load%s*=%s*\"([%w%s%p]-)\"",
149 process = function(k, v)
150 if modules[k] == nil then
153 modules[k].load = v:upper()
156 -- module_name="value"
158 str = MODULEEXPR .. "_name%s*=%s*\"([%w%s%p]-)\"",
159 process = function(k, v)
163 -- module_type="value"
165 str = MODULEEXPR .. "_type%s*=%s*\"([%w%s%p]-)\"",
166 process = function(k, v)
170 -- module_flags="value"
172 str = MODULEEXPR .. "_flags%s*=%s*\"([%w%s%p]-)\"",
173 process = function(k, v)
174 setKey(k, "flags", v)
177 -- module_before="value"
179 str = MODULEEXPR .. "_before%s*=%s*\"([%w%s%p]-)\"",
180 process = function(k, v)
181 setKey(k, "before", v)
184 -- module_after="value"
186 str = MODULEEXPR .. "_after%s*=%s*\"([%w%s%p]-)\"",
187 process = function(k, v)
188 setKey(k, "after", v)
191 -- module_error="value"
193 str = MODULEEXPR .. "_error%s*=%s*\"([%w%s%p]-)\"",
194 process = function(k, v)
195 setKey(k, "error", v)
200 str = "exec%s*=%s*\"([%w%s%p]-)\"",
201 process = function(k, _)
202 if cli_execute_unparsed(k) ~= 0 then
203 print(MSG_FAILEXEC:format(k))
210 str = "([%w%p]+)%s*=%s*\"([%w%s%p]-)\"",
211 process = function(k, v)
212 if setEnv(k, processEnvVar(v)) ~= 0 then
213 print(MSG_FAILSETENV:format(k, v))
219 str = "([%w%p]+)%s*=%s*(-?%d+)",
220 process = function(k, v)
221 if setEnv(k, processEnvVar(v)) ~= 0 then
222 print(MSG_FAILSETENV:format(k, tostring(v)))
228 local function isValidComment(line)
230 local s = line:match("^%s*#.*")
232 s = line:match("^%s*$")
241 local function loadModule(mod, silent)
244 for k, v in pairs(mod) do
245 if v.load ~= nil and v.load:lower() == "yes" then
247 if v.type ~= nil then
248 str = str .. "-t " .. v.type .. " "
250 if v.name ~= nil then
255 if v.flags ~= nil then
256 str = str .. " " .. v.flags
258 if v.before ~= nil then
259 pstatus = cli_execute_unparsed(v.before) == 0
260 if not pstatus and not silent then
261 print(MSG_FAILEXBEF:format(v.before, k))
263 status = status and pstatus
266 if cli_execute_unparsed(str) ~= 0 then
268 print(MSG_FAILEXMOD:format(str))
270 if v.error ~= nil then
271 cli_execute_unparsed(v.error)
276 if v.after ~= nil then
277 pstatus = cli_execute_unparsed(v.after) == 0
278 if not pstatus and not silent then
279 print(MSG_FAILEXAF:format(v.after, k))
281 status = status and pstatus
290 local function readConfFiles(loaded_files)
291 local f = loader.getenv("loader_conf_files")
293 for name in f:gmatch("([%w%p]+)%s*") do
294 if loaded_files[name] ~= nil then
298 local prefiles = loader.getenv("loader_conf_files")
300 print("Loading " .. name)
301 -- These may or may not exist, and that's ok. Do a
302 -- silent parse so that we complain on parse errors but
303 -- not for them simply not existing.
304 if not config.processFile(name, true) then
305 print(MSG_FAILPARSECFG:format(name))
308 loaded_files[name] = true
309 local newfiles = loader.getenv("loader_conf_files")
310 if prefiles ~= newfiles then
311 readConfFiles(loaded_files)
318 local function readFile(name, silent)
319 local f = io.open(name)
322 print(MSG_FAILOPENCFG:format(name))
327 local text, _ = io.read(f)
328 -- We might have read in the whole file, this won't be needed any more.
331 if text == nil and not silent then
332 print(MSG_FAILREADCFG:format(name))
337 local function checkNextboot()
338 local nextboot_file = loader.getenv("nextboot_conf")
339 if nextboot_file == nil then
343 local text = readFile(nextboot_file, true)
348 if text:match("^nextboot_enable=\"NO\"") ~= nil then
349 -- We're done; nextboot is not enabled
353 if not config.parse(text) then
354 print(MSG_FAILPARSECFG:format(nextboot_file))
357 -- Attempt to rewrite the first line and only the first line of the
358 -- nextboot_file. We overwrite it with nextboot_enable="NO", then
359 -- check for that on load.
360 -- It's worth noting that this won't work on every filesystem, so we
361 -- won't do anything notable if we have any errors in this process.
362 local nfile = io.open(nextboot_file, 'w')
364 -- We need the trailing space here to account for the extra
365 -- character taken up by the string nextboot_enable="YES"
366 -- Or new end quotation mark lands on the S, and we want to
367 -- rewrite the entirety of the first line.
368 io.write(nfile, "nextboot_enable=\"NO\" ")
374 config.verbose = false
376 -- The first item in every carousel is always the default item.
377 function config.getCarouselIndex(id)
378 return carousel_choices[id] or 1
381 function config.setCarouselIndex(id, idx)
382 carousel_choices[id] = idx
385 -- Returns true if we processed the file successfully, false if we did not.
386 -- If 'silent' is true, being unable to read the file is not considered a
388 function config.processFile(name, silent)
389 if silent == nil then
393 local text = readFile(name, silent)
398 return config.parse(text)
401 -- silent runs will not return false if we fail to open the file
402 function config.parse(text)
406 for line in text:gmatch("([^\n]+)") do
407 if line:match("^%s*$") == nil then
408 for _, val in ipairs(pattern_table) do
409 local pattern = '^%s*' .. val.str .. '%s*(.*)';
410 local cgroups = val.groups or 2
411 local k, v, c = line:match(pattern)
413 -- Offset by one, drats
419 if isValidComment(c) then
428 print(MSG_MALFORMED:format(n, line))
438 -- other_kernel is optionally the name of a kernel to load, if not the default
439 -- or autoloaded default from the module_path
440 function config.loadKernel(other_kernel)
441 local flags = loader.getenv("kernel_options") or ""
442 local kernel = other_kernel or loader.getenv("kernel")
444 local function tryLoad(names)
445 for name in names:gmatch("([^;]+)%s*;?") do
446 local r = loader.perform("load " .. name ..
455 local function loadBootfile()
456 local bootfile = loader.getenv("bootfile")
458 -- append default kernel name
459 if bootfile == nil then
462 bootfile = bootfile .. ";kernel"
465 return tryLoad(bootfile)
468 -- kernel not set, try load from default module_path
469 if kernel == nil then
470 local res = loadBootfile()
473 -- Default kernel is loaded
474 config.kernel_loaded = nil
477 print(MSG_DEFAULTKERNFAIL)
481 -- Use our cached module_path, so we don't end up with multiple
482 -- automatically added kernel paths to our final module_path
483 local module_path = config.module_path
486 if other_kernel ~= nil then
487 kernel = other_kernel
489 -- first try load kernel with module_path = /boot/${kernel}
490 -- then try load with module_path=${kernel}
491 local paths = {"/boot/" .. kernel, kernel}
493 for _, v in pairs(paths) do
494 loader.setenv("module_path", v)
497 -- succeeded, add path to module_path
499 config.kernel_loaded = kernel
500 if module_path ~= nil then
501 loader.setenv("module_path", v .. ";" ..
508 -- failed to load with ${kernel} as a directory
510 res = tryLoad(kernel)
512 config.kernel_loaded = kernel
515 print(MSG_KERNFAIL:format(kernel))
521 function config.selectKernel(kernel)
522 config.kernel_selected = kernel
525 function config.load(file, reloading)
527 file = "/boot/defaults/loader.conf"
530 if not config.processFile(file) then
531 print(MSG_FAILPARSECFG:format(file))
534 local loaded_files = {file = true}
535 readConfFiles(loaded_files)
539 -- Cache the provided module_path at load time for later use
540 config.module_path = loader.getenv("module_path")
541 local verbose = loader.getenv("verbose_loading") or "no"
542 config.verbose = verbose:lower() == "yes"
543 if not reloading then
544 hook.runAll("config.loaded")
548 -- Reload configuration
549 function config.reload(file)
552 config.load(file, true)
553 hook.runAll("config.reloaded")
556 function config.loadelf()
557 local kernel = config.kernel_selected or config.kernel_loaded
560 print(MSG_KERNLOADING)
561 loaded = config.loadKernel(kernel)
567 print(MSG_MODLOADING)
568 if not loadModule(modules, not config.verbose) then
569 print(MSG_MODLOADFAIL)
573 hook.registerType("config.loaded")
574 hook.registerType("config.reloaded")