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_XENKERNFAIL = "Failed to load Xen kernel '%s'"
54 local MSG_XENKERNLOADING = "Loading Xen kernel..."
55 local MSG_KERNLOADING = "Loading kernel..."
56 local MSG_MODLOADING = "Loading configured modules..."
57 local MSG_MODLOADFAIL = "Could not load one or more modules!"
59 local MODULEEXPR = '([%w-_]+)'
60 local QVALEXPR = "\"([%w%s%p]-)\""
61 local QVALREPL = QVALEXPR:gsub('%%', '%%%%')
62 local WORDEXPR = "([%w]+)"
63 local WORDREPL = WORDEXPR:gsub('%%', '%%%%')
65 local function restoreEnv()
66 -- Examine changed environment variables
67 for k, v in pairs(env_changed) do
68 local restore_value = env_restore[k]
69 if restore_value == nil then
70 -- This one doesn't need restored for some reason
73 local current_value = loader.getenv(k)
74 if current_value ~= v then
75 -- This was overwritten by some action taken on the menu
76 -- most likely; we'll leave it be.
79 restore_value = restore_value.value
80 if restore_value ~= nil then
81 loader.setenv(k, restore_value)
92 local function setEnv(key, value)
93 -- Track the original value for this if we haven't already
94 if env_restore[key] == nil then
95 env_restore[key] = {value = loader.getenv(key)}
98 env_changed[key] = value
100 return loader.setenv(key, value)
103 -- name here is one of 'name', 'type', flags', 'before', 'after', or 'error.'
104 -- These are set from lines in loader.conf(5): ${key}_${name}="${value}" where
105 -- ${key} is a module name.
106 local function setKey(key, name, value)
107 if modules[key] == nil then
110 modules[key][name] = value
113 -- Escapes the named value for use as a literal in a replacement pattern.
114 -- e.g. dhcp.host-name gets turned into dhcp%.host%-name to remove the special
116 local function escapeName(name)
117 return name:gsub("([%p])", "%%%1")
120 local function processEnvVar(value)
121 for name in value:gmatch("${([^}]+)}") do
122 local replacement = loader.getenv(name) or ""
123 value = value:gsub("${" .. escapeName(name) .. "}", replacement)
125 for name in value:gmatch("$([%w%p]+)%s*") do
126 local replacement = loader.getenv(name) or ""
127 value = value:gsub("$" .. escapeName(name), replacement)
132 local function checkPattern(line, pattern)
133 local function _realCheck(_line, _pattern)
134 return _line:match(_pattern)
137 if pattern:find('$VALUE') then
139 k, v, c = _realCheck(line, pattern:gsub('$VALUE', QVALREPL))
143 return _realCheck(line, pattern:gsub('$VALUE', WORDREPL))
145 return _realCheck(line, pattern)
149 -- str in this table is a regex pattern. It will automatically be anchored to
150 -- the beginning of a line and any preceding whitespace will be skipped. The
151 -- pattern should have no more than two captures patterns, which correspond to
152 -- the two parameters (usually 'key' and 'value') that are passed to the
153 -- process function. All trailing characters will be validated. Any $VALUE
154 -- token included in a pattern will be tried first with a quoted value capture
155 -- group, then a single-word value capture group. This is our kludge for Lua
156 -- regex not supporting branching.
158 -- We have two special entries in this table: the first is the first entry,
159 -- a full-line comment. The second is for 'exec' handling. Both have a single
160 -- capture group, but the difference is that the full-line comment pattern will
161 -- match the entire line. This does not run afoul of the later end of line
162 -- validation that we'll do after a match. However, the 'exec' pattern will.
163 -- We document the exceptions with a special 'groups' index that indicates
164 -- the number of capture groups, if not two. We'll use this later to do
165 -- validation on the proper entry.
167 local pattern_table = {
170 process = function(_, _) end,
173 -- module_load="value"
175 str = MODULEEXPR .. "_load%s*=%s*$VALUE",
176 process = function(k, v)
177 if modules[k] == nil then
180 modules[k].load = v:upper()
183 -- module_name="value"
185 str = MODULEEXPR .. "_name%s*=%s*$VALUE",
186 process = function(k, v)
190 -- module_type="value"
192 str = MODULEEXPR .. "_type%s*=%s*$VALUE",
193 process = function(k, v)
197 -- module_flags="value"
199 str = MODULEEXPR .. "_flags%s*=%s*$VALUE",
200 process = function(k, v)
201 setKey(k, "flags", v)
204 -- module_before="value"
206 str = MODULEEXPR .. "_before%s*=%s*$VALUE",
207 process = function(k, v)
208 setKey(k, "before", v)
211 -- module_after="value"
213 str = MODULEEXPR .. "_after%s*=%s*$VALUE",
214 process = function(k, v)
215 setKey(k, "after", v)
218 -- module_error="value"
220 str = MODULEEXPR .. "_error%s*=%s*$VALUE",
221 process = function(k, v)
222 setKey(k, "error", v)
227 str = "exec%s*=%s*" .. QVALEXPR,
228 process = function(k, _)
229 if cli_execute_unparsed(k) ~= 0 then
230 print(MSG_FAILEXEC:format(k))
237 str = "([%w%p]+)%s*=%s*$VALUE",
238 process = function(k, v)
239 if setEnv(k, processEnvVar(v)) ~= 0 then
240 print(MSG_FAILSETENV:format(k, v))
246 str = "([%w%p]+)%s*=%s*(-?%d+)",
247 process = function(k, v)
248 if setEnv(k, processEnvVar(v)) ~= 0 then
249 print(MSG_FAILSETENV:format(k, tostring(v)))
255 local function isValidComment(line)
257 local s = line:match("^%s*#.*")
259 s = line:match("^%s*$")
268 local function loadModule(mod, silent)
271 for k, v in pairs(mod) do
272 if v.load ~= nil and v.load:lower() == "yes" then
274 if v.type ~= nil then
275 str = str .. "-t " .. v.type .. " "
277 if v.name ~= nil then
282 if v.flags ~= nil then
283 str = str .. " " .. v.flags
285 if v.before ~= nil then
286 pstatus = cli_execute_unparsed(v.before) == 0
287 if not pstatus and not silent then
288 print(MSG_FAILEXBEF:format(v.before, k))
290 status = status and pstatus
293 if cli_execute_unparsed(str) ~= 0 then
295 print(MSG_FAILEXMOD:format(str))
297 if v.error ~= nil then
298 cli_execute_unparsed(v.error)
303 if v.after ~= nil then
304 pstatus = cli_execute_unparsed(v.after) == 0
305 if not pstatus and not silent then
306 print(MSG_FAILEXAF:format(v.after, k))
308 status = status and pstatus
317 local function readConfFiles(loaded_files)
318 local f = loader.getenv("loader_conf_files")
320 for name in f:gmatch("([%w%p]+)%s*") do
321 if loaded_files[name] ~= nil then
325 local prefiles = loader.getenv("loader_conf_files")
327 print("Loading " .. name)
328 -- These may or may not exist, and that's ok. Do a
329 -- silent parse so that we complain on parse errors but
330 -- not for them simply not existing.
331 if not config.processFile(name, true) then
332 print(MSG_FAILPARSECFG:format(name))
335 loaded_files[name] = true
336 local newfiles = loader.getenv("loader_conf_files")
337 if prefiles ~= newfiles then
338 readConfFiles(loaded_files)
345 local function readFile(name, silent)
346 local f = io.open(name)
349 print(MSG_FAILOPENCFG:format(name))
354 local text, _ = io.read(f)
355 -- We might have read in the whole file, this won't be needed any more.
358 if text == nil and not silent then
359 print(MSG_FAILREADCFG:format(name))
364 local function checkNextboot()
365 local nextboot_file = loader.getenv("nextboot_conf")
366 if nextboot_file == nil then
370 local text = readFile(nextboot_file, true)
375 if text:match("^nextboot_enable=\"NO\"") ~= nil then
376 -- We're done; nextboot is not enabled
380 if not config.parse(text) then
381 print(MSG_FAILPARSECFG:format(nextboot_file))
384 -- Attempt to rewrite the first line and only the first line of the
385 -- nextboot_file. We overwrite it with nextboot_enable="NO", then
386 -- check for that on load.
387 -- It's worth noting that this won't work on every filesystem, so we
388 -- won't do anything notable if we have any errors in this process.
389 local nfile = io.open(nextboot_file, 'w')
391 -- We need the trailing space here to account for the extra
392 -- character taken up by the string nextboot_enable="YES"
393 -- Or new end quotation mark lands on the S, and we want to
394 -- rewrite the entirety of the first line.
395 io.write(nfile, "nextboot_enable=\"NO\" ")
401 config.verbose = false
403 -- The first item in every carousel is always the default item.
404 function config.getCarouselIndex(id)
405 return carousel_choices[id] or 1
408 function config.setCarouselIndex(id, idx)
409 carousel_choices[id] = idx
412 -- Returns true if we processed the file successfully, false if we did not.
413 -- If 'silent' is true, being unable to read the file is not considered a
415 function config.processFile(name, silent)
416 if silent == nil then
420 local text = readFile(name, silent)
425 return config.parse(text)
428 -- silent runs will not return false if we fail to open the file
429 function config.parse(text)
433 for line in text:gmatch("([^\n]+)") do
434 if line:match("^%s*$") == nil then
435 for _, val in ipairs(pattern_table) do
436 local pattern = '^%s*' .. val.str .. '%s*(.*)';
437 local cgroups = val.groups or 2
438 local k, v, c = checkPattern(line, pattern)
440 -- Offset by one, drats
446 if isValidComment(c) then
455 print(MSG_MALFORMED:format(n, line))
465 -- other_kernel is optionally the name of a kernel to load, if not the default
466 -- or autoloaded default from the module_path
467 function config.loadKernel(other_kernel)
468 local flags = loader.getenv("kernel_options") or ""
469 local kernel = other_kernel or loader.getenv("kernel")
471 local function tryLoad(names)
472 for name in names:gmatch("([^;]+)%s*;?") do
473 local r = loader.perform("load " .. name ..
482 local function getModulePath()
483 local module_path = loader.getenv("module_path")
484 local kernel_path = loader.getenv("kernel_path")
486 if kernel_path == nil then
490 -- Strip the loaded kernel path from module_path. This currently assumes
491 -- that the kernel path will be prepended to the module_path when it's
493 kernel_path = escapeName(kernel_path .. ';')
494 return module_path:gsub(kernel_path, '')
497 local function loadBootfile()
498 local bootfile = loader.getenv("bootfile")
500 -- append default kernel name
501 if bootfile == nil then
504 bootfile = bootfile .. ";kernel"
507 return tryLoad(bootfile)
510 -- kernel not set, try load from default module_path
511 if kernel == nil then
512 local res = loadBootfile()
515 -- Default kernel is loaded
516 config.kernel_loaded = nil
519 print(MSG_DEFAULTKERNFAIL)
523 -- Use our cached module_path, so we don't end up with multiple
524 -- automatically added kernel paths to our final module_path
525 local module_path = getModulePath()
528 if other_kernel ~= nil then
529 kernel = other_kernel
531 -- first try load kernel with module_path = /boot/${kernel}
532 -- then try load with module_path=${kernel}
533 local paths = {"/boot/" .. kernel, kernel}
535 for _, v in pairs(paths) do
536 loader.setenv("module_path", v)
539 -- succeeded, add path to module_path
541 config.kernel_loaded = kernel
542 if module_path ~= nil then
543 loader.setenv("module_path", v .. ";" ..
545 loader.setenv("kernel_path", v)
551 -- failed to load with ${kernel} as a directory
553 res = tryLoad(kernel)
555 config.kernel_loaded = kernel
558 print(MSG_KERNFAIL:format(kernel))
564 function config.selectKernel(kernel)
565 config.kernel_selected = kernel
568 function config.load(file, reloading)
570 file = "/boot/defaults/loader.conf"
573 if not config.processFile(file) then
574 print(MSG_FAILPARSECFG:format(file))
577 local loaded_files = {file = true}
578 readConfFiles(loaded_files)
582 local verbose = loader.getenv("verbose_loading") or "no"
583 config.verbose = verbose:lower() == "yes"
584 if not reloading then
585 hook.runAll("config.loaded")
589 -- Reload configuration
590 function config.reload(file)
593 config.load(file, true)
594 hook.runAll("config.reloaded")
597 function config.loadelf()
598 local xen_kernel = loader.getenv('xen_kernel')
599 local kernel = config.kernel_selected or config.kernel_loaded
602 if xen_kernel ~= nil then
603 print(MSG_XENKERNLOADING)
604 if cli_execute_unparsed('load ' .. xen_kernel) ~= 0 then
605 print(MSG_XENKERNFAIL:format(xen_kernel))
609 print(MSG_KERNLOADING)
610 loaded = config.loadKernel(kernel)
616 print(MSG_MODLOADING)
617 if not loadModule(modules, not config.verbose) then
618 print(MSG_MODLOADFAIL)
622 hook.registerType("config.loaded")
623 hook.registerType("config.reloaded")