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_MODBLACKLIST = "Not loading blacklisted module '%s'"
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 getBlacklist()
270 local blacklist_str = loader.getenv('module_blacklist')
271 if blacklist_str == nil then
275 for mod in blacklist_str:gmatch("[;, ]?([%w-_]+)[;, ]?") do
276 blacklist[mod] = true
281 local function loadModule(mod, silent)
283 local blacklist = getBlacklist()
285 for k, v in pairs(mod) do
286 if v.load ~= nil and v.load:lower() == "yes" then
287 local module_name = v.name or k
288 if blacklist[module_name] ~= nil then
290 print(MSG_MODBLACKLIST:format(module_name))
295 loader.printc(module_name .. "...")
298 if v.type ~= nil then
299 str = str .. "-t " .. v.type .. " "
301 str = str .. module_name
302 if v.flags ~= nil then
303 str = str .. " " .. v.flags
305 if v.before ~= nil then
306 pstatus = cli_execute_unparsed(v.before) == 0
307 if not pstatus and not silent then
308 print(MSG_FAILEXBEF:format(v.before, k))
310 status = status and pstatus
313 if cli_execute_unparsed(str) ~= 0 then
314 -- XXX Temporary shim: don't break the boot if
315 -- loader hadn't been recompiled with this
317 if loader.command_error then
318 print(loader.command_error())
323 if v.error ~= nil then
324 cli_execute_unparsed(v.error)
327 elseif v.after ~= nil then
328 pstatus = cli_execute_unparsed(v.after) == 0
329 if not pstatus and not silent then
330 print(MSG_FAILEXAF:format(v.after, k))
335 status = status and pstatus
344 local function readConfFiles(loaded_files)
345 local f = loader.getenv("loader_conf_files")
347 for name in f:gmatch("([%w%p]+)%s*") do
348 if loaded_files[name] ~= nil then
352 local prefiles = loader.getenv("loader_conf_files")
354 print("Loading " .. name)
355 -- These may or may not exist, and that's ok. Do a
356 -- silent parse so that we complain on parse errors but
357 -- not for them simply not existing.
358 if not config.processFile(name, true) then
359 print(MSG_FAILPARSECFG:format(name))
362 loaded_files[name] = true
363 local newfiles = loader.getenv("loader_conf_files")
364 if prefiles ~= newfiles then
365 readConfFiles(loaded_files)
372 local function readFile(name, silent)
373 local f = io.open(name)
376 print(MSG_FAILOPENCFG:format(name))
381 local text, _ = io.read(f)
382 -- We might have read in the whole file, this won't be needed any more.
385 if text == nil and not silent then
386 print(MSG_FAILREADCFG:format(name))
391 local function checkNextboot()
392 local nextboot_file = loader.getenv("nextboot_conf")
393 if nextboot_file == nil then
397 local text = readFile(nextboot_file, true)
402 if text:match("^nextboot_enable=\"NO\"") ~= nil then
403 -- We're done; nextboot is not enabled
407 if not config.parse(text) then
408 print(MSG_FAILPARSECFG:format(nextboot_file))
411 -- Attempt to rewrite the first line and only the first line of the
412 -- nextboot_file. We overwrite it with nextboot_enable="NO", then
413 -- check for that on load.
414 -- It's worth noting that this won't work on every filesystem, so we
415 -- won't do anything notable if we have any errors in this process.
416 local nfile = io.open(nextboot_file, 'w')
418 -- We need the trailing space here to account for the extra
419 -- character taken up by the string nextboot_enable="YES"
420 -- Or new end quotation mark lands on the S, and we want to
421 -- rewrite the entirety of the first line.
422 io.write(nfile, "nextboot_enable=\"NO\" ")
428 config.verbose = false
430 -- The first item in every carousel is always the default item.
431 function config.getCarouselIndex(id)
432 return carousel_choices[id] or 1
435 function config.setCarouselIndex(id, idx)
436 carousel_choices[id] = idx
439 -- Returns true if we processed the file successfully, false if we did not.
440 -- If 'silent' is true, being unable to read the file is not considered a
442 function config.processFile(name, silent)
443 if silent == nil then
447 local text = readFile(name, silent)
452 return config.parse(text)
455 -- silent runs will not return false if we fail to open the file
456 function config.parse(text)
460 for line in text:gmatch("([^\n]+)") do
461 if line:match("^%s*$") == nil then
462 for _, val in ipairs(pattern_table) do
463 local pattern = '^%s*' .. val.str .. '%s*(.*)';
464 local cgroups = val.groups or 2
465 local k, v, c = checkPattern(line, pattern)
467 -- Offset by one, drats
473 if isValidComment(c) then
482 print(MSG_MALFORMED:format(n, line))
492 -- other_kernel is optionally the name of a kernel to load, if not the default
493 -- or autoloaded default from the module_path
494 function config.loadKernel(other_kernel)
495 local flags = loader.getenv("kernel_options") or ""
496 local kernel = other_kernel or loader.getenv("kernel")
498 local function tryLoad(names)
499 for name in names:gmatch("([^;]+)%s*;?") do
500 local r = loader.perform("load " .. name ..
509 local function getModulePath()
510 local module_path = loader.getenv("module_path")
511 local kernel_path = loader.getenv("kernel_path")
513 if kernel_path == nil then
517 -- Strip the loaded kernel path from module_path. This currently assumes
518 -- that the kernel path will be prepended to the module_path when it's
520 kernel_path = escapeName(kernel_path .. ';')
521 return module_path:gsub(kernel_path, '')
524 local function loadBootfile()
525 local bootfile = loader.getenv("bootfile")
527 -- append default kernel name
528 if bootfile == nil then
531 bootfile = bootfile .. ";kernel"
534 return tryLoad(bootfile)
537 -- kernel not set, try load from default module_path
538 if kernel == nil then
539 local res = loadBootfile()
542 -- Default kernel is loaded
543 config.kernel_loaded = nil
546 print(MSG_DEFAULTKERNFAIL)
550 -- Use our cached module_path, so we don't end up with multiple
551 -- automatically added kernel paths to our final module_path
552 local module_path = getModulePath()
555 if other_kernel ~= nil then
556 kernel = other_kernel
558 -- first try load kernel with module_path = /boot/${kernel}
559 -- then try load with module_path=${kernel}
560 local paths = {"/boot/" .. kernel, kernel}
562 for _, v in pairs(paths) do
563 loader.setenv("module_path", v)
566 -- succeeded, add path to module_path
568 config.kernel_loaded = kernel
569 if module_path ~= nil then
570 loader.setenv("module_path", v .. ";" ..
572 loader.setenv("kernel_path", v)
578 -- failed to load with ${kernel} as a directory
580 res = tryLoad(kernel)
582 config.kernel_loaded = kernel
585 print(MSG_KERNFAIL:format(kernel))
591 function config.selectKernel(kernel)
592 config.kernel_selected = kernel
595 function config.load(file, reloading)
597 file = "/boot/defaults/loader.conf"
600 if not config.processFile(file) then
601 print(MSG_FAILPARSECFG:format(file))
604 local loaded_files = {file = true}
605 readConfFiles(loaded_files)
609 local verbose = loader.getenv("verbose_loading") or "no"
610 config.verbose = verbose:lower() == "yes"
611 if not reloading then
612 hook.runAll("config.loaded")
616 -- Reload configuration
617 function config.reload(file)
620 config.load(file, true)
621 hook.runAll("config.reloaded")
624 function config.loadelf()
625 local xen_kernel = loader.getenv('xen_kernel')
626 local kernel = config.kernel_selected or config.kernel_loaded
629 if xen_kernel ~= nil then
630 print(MSG_XENKERNLOADING)
631 if cli_execute_unparsed('load ' .. xen_kernel) ~= 0 then
632 print(MSG_XENKERNFAIL:format(xen_kernel))
636 print(MSG_KERNLOADING)
637 loaded = config.loadKernel(kernel)
643 print(MSG_MODLOADING)
644 return loadModule(modules, not config.verbose)
647 hook.registerType("config.loaded")
648 hook.registerType("config.reloaded")