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_FAILDIR = "Failed to load conf dir '%s': not a directory"
43 local MSG_FAILEXEC = "Failed to exec '%s'"
44 local MSG_FAILSETENV = "Failed to '%s' with value: %s"
45 local MSG_FAILOPENCFG = "Failed to open config: '%s'"
46 local MSG_FAILREADCFG = "Failed to read config: '%s'"
47 local MSG_FAILPARSECFG = "Failed to parse config: '%s'"
48 local MSG_FAILPARSEVAR = "Failed to parse variable '%s': %s"
49 local MSG_FAILEXBEF = "Failed to execute '%s' before loading '%s'"
50 local MSG_FAILEXAF = "Failed to execute '%s' after loading '%s'"
51 local MSG_MALFORMED = "Malformed line (%d):\n\t'%s'"
52 local MSG_DEFAULTKERNFAIL = "No kernel set, failed to load from module_path"
53 local MSG_KERNFAIL = "Failed to load kernel '%s'"
54 local MSG_XENKERNFAIL = "Failed to load Xen kernel '%s'"
55 local MSG_XENKERNLOADING = "Loading Xen kernel..."
56 local MSG_KERNLOADING = "Loading kernel..."
57 local MSG_MODLOADING = "Loading configured modules..."
58 local MSG_MODBLACKLIST = "Not loading blacklisted module '%s'"
60 local MSG_FAILSYN_QUOTE = "Stray quote at position '%d'"
61 local MSG_FAILSYN_EOLESC = "Stray escape at end of line"
62 local MSG_FAILSYN_EOLVAR = "Unescaped $ at end of line"
63 local MSG_FAILSYN_BADVAR = "Malformed variable expression at position '%d'"
65 local MODULEEXPR = '([-%w_]+)'
66 local QVALEXPR = '"(.*)"'
67 local QVALREPL = QVALEXPR:gsub('%%', '%%%%')
68 local WORDEXPR = "([-%w%d][-%w%d_.]*)"
69 local WORDREPL = WORDEXPR:gsub('%%', '%%%%')
71 -- Entries that should never make it into the environment; each one should have
72 -- a documented reason for its existence, and these should all be implementation
73 -- details of the config module.
74 local loader_env_restricted_table = {
75 -- loader_conf_files should be considered write-only, and consumers
76 -- should not rely on any particular value; it's a loader implementation
77 -- detail. Moreover, it's not a particularly useful variable to have in
78 -- the kenv. Save the overhead, let it get fetched other ways.
79 loader_conf_files = true,
82 local function restoreEnv()
83 -- Examine changed environment variables
84 for k, v in pairs(env_changed) do
85 local restore_value = env_restore[k]
86 if restore_value == nil then
87 -- This one doesn't need restored for some reason
90 local current_value = loader.getenv(k)
91 if current_value ~= v then
92 -- This was overwritten by some action taken on the menu
93 -- most likely; we'll leave it be.
96 restore_value = restore_value.value
97 if restore_value ~= nil then
98 loader.setenv(k, restore_value)
109 -- XXX This getEnv/setEnv should likely be exported at some point. We can save
110 -- the call back into loader.getenv for any variable that's been set or
111 -- overridden by any loader.conf using this implementation with little overhead
112 -- since we're already tracking the values.
113 local function getEnv(key)
114 if loader_env_restricted_table[key] ~= nil or
115 env_changed[key] ~= nil then
116 return env_changed[key]
119 return loader.getenv(key)
122 local function setEnv(key, value)
123 env_changed[key] = value
125 if loader_env_restricted_table[key] ~= nil then
129 -- Track the original value for this if we haven't already
130 if env_restore[key] == nil then
131 env_restore[key] = {value = loader.getenv(key)}
134 return loader.setenv(key, value)
137 -- name here is one of 'name', 'type', flags', 'before', 'after', or 'error.'
138 -- These are set from lines in loader.conf(5): ${key}_${name}="${value}" where
139 -- ${key} is a module name.
140 local function setKey(key, name, value)
141 if modules[key] == nil then
144 modules[key][name] = value
147 -- Escapes the named value for use as a literal in a replacement pattern.
148 -- e.g. dhcp.host-name gets turned into dhcp%.host%-name to remove the special
150 local function escapeName(name)
151 return name:gsub("([%p])", "%%%1")
154 local function processEnvVar(value)
155 local pval, vlen = '', #value
156 local nextpos, vdelim, vinit = 1
163 local c = value:sub(i, i)
166 return nil, MSG_FAILSYN_EOLESC
169 pval = pval .. value:sub(i + 1, i + 1)
171 return nil, MSG_FAILSYN_QUOTE:format(i)
174 return nil, MSG_FAILSYN_EOLVAR
176 if value:sub(i + 1, i + 1) == "{" then
185 vpat = "^([%w][-%w%d_.]*)"
188 local name = value:match(vpat, vinit)
190 return nil, MSG_FAILSYN_BADVAR:format(i)
192 nextpos = vinit + #name
194 nextpos = nextpos + 1
197 local repl = loader.getenv(name) or ""
210 local function checkPattern(line, pattern)
211 local function _realCheck(_line, _pattern)
212 return _line:match(_pattern)
215 if pattern:find('$VALUE') then
217 k, v, c = _realCheck(line, pattern:gsub('$VALUE', QVALREPL))
221 return _realCheck(line, pattern:gsub('$VALUE', WORDREPL))
223 return _realCheck(line, pattern)
227 -- str in this table is a regex pattern. It will automatically be anchored to
228 -- the beginning of a line and any preceding whitespace will be skipped. The
229 -- pattern should have no more than two captures patterns, which correspond to
230 -- the two parameters (usually 'key' and 'value') that are passed to the
231 -- process function. All trailing characters will be validated. Any $VALUE
232 -- token included in a pattern will be tried first with a quoted value capture
233 -- group, then a single-word value capture group. This is our kludge for Lua
234 -- regex not supporting branching.
236 -- We have two special entries in this table: the first is the first entry,
237 -- a full-line comment. The second is for 'exec' handling. Both have a single
238 -- capture group, but the difference is that the full-line comment pattern will
239 -- match the entire line. This does not run afoul of the later end of line
240 -- validation that we'll do after a match. However, the 'exec' pattern will.
241 -- We document the exceptions with a special 'groups' index that indicates
242 -- the number of capture groups, if not two. We'll use this later to do
243 -- validation on the proper entry.
245 local pattern_table = {
248 process = function(_, _) end,
251 -- module_load="value"
253 str = MODULEEXPR .. "_load%s*=%s*$VALUE",
254 process = function(k, v)
255 if modules[k] == nil then
258 modules[k].load = v:upper()
261 -- module_name="value"
263 str = MODULEEXPR .. "_name%s*=%s*$VALUE",
264 process = function(k, v)
268 -- module_type="value"
270 str = MODULEEXPR .. "_type%s*=%s*$VALUE",
271 process = function(k, v)
275 -- module_flags="value"
277 str = MODULEEXPR .. "_flags%s*=%s*$VALUE",
278 process = function(k, v)
279 setKey(k, "flags", v)
282 -- module_before="value"
284 str = MODULEEXPR .. "_before%s*=%s*$VALUE",
285 process = function(k, v)
286 setKey(k, "before", v)
289 -- module_after="value"
291 str = MODULEEXPR .. "_after%s*=%s*$VALUE",
292 process = function(k, v)
293 setKey(k, "after", v)
296 -- module_error="value"
298 str = MODULEEXPR .. "_error%s*=%s*$VALUE",
299 process = function(k, v)
300 setKey(k, "error", v)
305 str = "exec%s*=%s*" .. QVALEXPR,
306 process = function(k, _)
307 if cli_execute_unparsed(k) ~= 0 then
308 print(MSG_FAILEXEC:format(k))
313 -- env_var="value" or env_var=[word|num]
315 str = "([%w][%w%d-_.]*)%s*=%s*$VALUE",
316 process = function(k, v)
317 local pv, msg = processEnvVar(v)
319 print(MSG_FAILPARSEVAR:format(k, msg))
322 if setEnv(k, pv) ~= 0 then
323 print(MSG_FAILSETENV:format(k, v))
329 local function isValidComment(line)
331 local s = line:match("^%s*#.*")
333 s = line:match("^%s*$")
342 local function getBlacklist()
344 local blacklist_str = loader.getenv('module_blacklist')
345 if blacklist_str == nil then
349 for mod in blacklist_str:gmatch("[;, ]?([-%w_]+)[;, ]?") do
350 blacklist[mod] = true
355 local function loadModule(mod, silent)
357 local blacklist = getBlacklist()
359 for k, v in pairs(mod) do
360 if v.load ~= nil and v.load:lower() == "yes" then
361 local module_name = v.name or k
362 if not v.force and blacklist[module_name] ~= nil then
364 print(MSG_MODBLACKLIST:format(module_name))
369 loader.printc(module_name .. "...")
372 if v.type ~= nil then
373 str = str .. "-t " .. v.type .. " "
375 str = str .. module_name
376 if v.flags ~= nil then
377 str = str .. " " .. v.flags
379 if v.before ~= nil then
380 pstatus = cli_execute_unparsed(v.before) == 0
381 if not pstatus and not silent then
382 print(MSG_FAILEXBEF:format(v.before, k))
384 status = status and pstatus
387 if cli_execute_unparsed(str) ~= 0 then
388 -- XXX Temporary shim: don't break the boot if
389 -- loader hadn't been recompiled with this
391 if loader.command_error then
392 print(loader.command_error())
397 if v.error ~= nil then
398 cli_execute_unparsed(v.error)
401 elseif v.after ~= nil then
402 pstatus = cli_execute_unparsed(v.after) == 0
403 if not pstatus and not silent then
404 print(MSG_FAILEXAF:format(v.after, k))
409 status = status and pstatus
418 local function readFile(name, silent)
419 local f = io.open(name)
422 print(MSG_FAILOPENCFG:format(name))
427 local text, _ = io.read(f)
428 -- We might have read in the whole file, this won't be needed any more.
431 if text == nil and not silent then
432 print(MSG_FAILREADCFG:format(name))
437 local function checkNextboot()
438 local nextboot_file = loader.getenv("nextboot_conf")
439 if nextboot_file == nil then
443 local text = readFile(nextboot_file, true)
448 if text:match("^nextboot_enable=\"NO\"") ~= nil then
449 -- We're done; nextboot is not enabled
453 if not config.parse(text) then
454 print(MSG_FAILPARSECFG:format(nextboot_file))
457 -- Attempt to rewrite the first line and only the first line of the
458 -- nextboot_file. We overwrite it with nextboot_enable="NO", then
459 -- check for that on load.
460 -- It's worth noting that this won't work on every filesystem, so we
461 -- won't do anything notable if we have any errors in this process.
462 local nfile = io.open(nextboot_file, 'w')
464 -- We need the trailing space here to account for the extra
465 -- character taken up by the string nextboot_enable="YES"
466 -- Or new end quotation mark lands on the S, and we want to
467 -- rewrite the entirety of the first line.
468 io.write(nfile, "nextboot_enable=\"NO\" ")
474 config.verbose = false
476 -- The first item in every carousel is always the default item.
477 function config.getCarouselIndex(id)
478 return carousel_choices[id] or 1
481 function config.setCarouselIndex(id, idx)
482 carousel_choices[id] = idx
485 -- Returns true if we processed the file successfully, false if we did not.
486 -- If 'silent' is true, being unable to read the file is not considered a
488 function config.processFile(name, silent)
489 if silent == nil then
493 local text = readFile(name, silent)
498 return config.parse(text)
501 -- silent runs will not return false if we fail to open the file
502 function config.parse(text)
506 for line in text:gmatch("([^\n]+)") do
507 if line:match("^%s*$") == nil then
508 for _, val in ipairs(pattern_table) do
509 local pattern = '^%s*' .. val.str .. '%s*(.*)';
510 local cgroups = val.groups or 2
511 local k, v, c = checkPattern(line, pattern)
513 -- Offset by one, drats
519 if isValidComment(c) then
528 print(MSG_MALFORMED:format(n, line))
538 function config.readConf(file, loaded_files)
539 if loaded_files == nil then
543 if loaded_files[file] ~= nil then
547 -- We'll process loader_conf_dirs at the top-level readConf
548 local load_conf_dirs = next(loaded_files) == nil
549 print("Loading " .. file)
551 -- The final value of loader_conf_files is not important, so just
552 -- clobber it here. We'll later check if it's no longer nil and process
553 -- the new value for files to read.
554 setEnv("loader_conf_files", nil)
556 -- These may or may not exist, and that's ok. Do a
557 -- silent parse so that we complain on parse errors but
558 -- not for them simply not existing.
559 if not config.processFile(file, true) then
560 print(MSG_FAILPARSECFG:format(file))
563 loaded_files[file] = true
565 -- Going to process "loader_conf_files" extra-files
566 local loader_conf_files = getEnv("loader_conf_files")
567 if loader_conf_files ~= nil then
568 for name in loader_conf_files:gmatch("[%w%p]+") do
569 config.readConf(name, loaded_files)
573 if load_conf_dirs then
574 local loader_conf_dirs = getEnv("loader_conf_dirs")
575 if loader_conf_dirs ~= nil then
576 for name in loader_conf_dirs:gmatch("[%w%p]+") do
577 if lfs.attributes(name, "mode") ~= "directory" then
578 print(MSG_FAILDIR:format(name))
581 for cfile in lfs.dir(name) do
582 if cfile:match(".conf$") then
583 local fpath = name .. "/" .. cfile
584 if lfs.attributes(fpath, "mode") == "file" then
585 config.readConf(fpath, loaded_files)
595 -- other_kernel is optionally the name of a kernel to load, if not the default
596 -- or autoloaded default from the module_path
597 function config.loadKernel(other_kernel)
598 local flags = loader.getenv("kernel_options") or ""
599 local kernel = other_kernel or loader.getenv("kernel")
601 local function tryLoad(names)
602 for name in names:gmatch("([^;]+)%s*;?") do
603 local r = loader.perform("load " .. name ..
612 local function getModulePath()
613 local module_path = loader.getenv("module_path")
614 local kernel_path = loader.getenv("kernel_path")
616 if kernel_path == nil then
620 -- Strip the loaded kernel path from module_path. This currently assumes
621 -- that the kernel path will be prepended to the module_path when it's
623 kernel_path = escapeName(kernel_path .. ';')
624 return module_path:gsub(kernel_path, '')
627 local function loadBootfile()
628 local bootfile = loader.getenv("bootfile")
630 -- append default kernel name
631 if bootfile == nil then
634 bootfile = bootfile .. ";kernel"
637 return tryLoad(bootfile)
640 -- kernel not set, try load from default module_path
641 if kernel == nil then
642 local res = loadBootfile()
645 -- Default kernel is loaded
646 config.kernel_loaded = nil
649 print(MSG_DEFAULTKERNFAIL)
653 -- Use our cached module_path, so we don't end up with multiple
654 -- automatically added kernel paths to our final module_path
655 local module_path = getModulePath()
658 if other_kernel ~= nil then
659 kernel = other_kernel
661 -- first try load kernel with module_path = /boot/${kernel}
662 -- then try load with module_path=${kernel}
663 local paths = {"/boot/" .. kernel, kernel}
665 for _, v in pairs(paths) do
666 loader.setenv("module_path", v)
669 -- succeeded, add path to module_path
671 config.kernel_loaded = kernel
672 if module_path ~= nil then
673 loader.setenv("module_path", v .. ";" ..
675 loader.setenv("kernel_path", v)
681 -- failed to load with ${kernel} as a directory
683 res = tryLoad(kernel)
685 config.kernel_loaded = kernel
688 print(MSG_KERNFAIL:format(kernel))
694 function config.selectKernel(kernel)
695 config.kernel_selected = kernel
698 function config.load(file, reloading)
700 file = "/boot/defaults/loader.conf"
703 config.readConf(file)
707 local verbose = loader.getenv("verbose_loading") or "no"
708 config.verbose = verbose:lower() == "yes"
709 if not reloading then
710 hook.runAll("config.loaded")
714 -- Reload configuration
715 function config.reload(file)
718 config.load(file, true)
719 hook.runAll("config.reloaded")
722 function config.loadelf()
723 local xen_kernel = loader.getenv('xen_kernel')
724 local kernel = config.kernel_selected or config.kernel_loaded
727 if xen_kernel ~= nil then
728 print(MSG_XENKERNLOADING)
729 if cli_execute_unparsed('load ' .. xen_kernel) ~= 0 then
730 print(MSG_XENKERNFAIL:format(xen_kernel))
734 print(MSG_KERNLOADING)
735 if not config.loadKernel(kernel) then
738 hook.runAll("kernel.loaded")
740 print(MSG_MODLOADING)
741 status = loadModule(modules, not config.verbose)
742 hook.runAll("modules.loaded")
746 function config.enableModule(modname)
747 if modules[modname] == nil then
748 modules[modname] = {}
749 elseif modules[modname].load == "YES" then
750 modules[modname].force = true
754 modules[modname].load = "YES"
755 modules[modname].force = true
759 function config.disableModule(modname)
760 if modules[modname] == nil then
762 elseif modules[modname].load ~= "YES" then
766 modules[modname].load = "NO"
767 modules[modname].force = nil
771 function config.isModuleEnabled(modname)
772 local mod = modules[modname]
773 if not mod or mod.load ~= "YES" then
781 local blacklist = getBlacklist()
782 return not blacklist[modname]
785 function config.getModuleInfo()
788 blacklist = getBlacklist()
792 hook.registerType("config.loaded")
793 hook.registerType("config.reloaded")
794 hook.registerType("kernel.loaded")
795 hook.registerType("modules.loaded")