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'"
58 local MSG_MODLOADFAIL = "Could not load one or more modules!"
60 local MODULEEXPR = '([%w-_]+)'
61 local QVALEXPR = "\"([%w%s%p]-)\""
62 local QVALREPL = QVALEXPR:gsub('%%', '%%%%')
63 local WORDEXPR = "([%w]+)"
64 local WORDREPL = WORDEXPR:gsub('%%', '%%%%')
66 local function restoreEnv()
67 -- Examine changed environment variables
68 for k, v in pairs(env_changed) do
69 local restore_value = env_restore[k]
70 if restore_value == nil then
71 -- This one doesn't need restored for some reason
74 local current_value = loader.getenv(k)
75 if current_value ~= v then
76 -- This was overwritten by some action taken on the menu
77 -- most likely; we'll leave it be.
80 restore_value = restore_value.value
81 if restore_value ~= nil then
82 loader.setenv(k, restore_value)
93 local function setEnv(key, value)
94 -- Track the original value for this if we haven't already
95 if env_restore[key] == nil then
96 env_restore[key] = {value = loader.getenv(key)}
99 env_changed[key] = value
101 return loader.setenv(key, value)
104 -- name here is one of 'name', 'type', flags', 'before', 'after', or 'error.'
105 -- These are set from lines in loader.conf(5): ${key}_${name}="${value}" where
106 -- ${key} is a module name.
107 local function setKey(key, name, value)
108 if modules[key] == nil then
111 modules[key][name] = value
114 -- Escapes the named value for use as a literal in a replacement pattern.
115 -- e.g. dhcp.host-name gets turned into dhcp%.host%-name to remove the special
117 local function escapeName(name)
118 return name:gsub("([%p])", "%%%1")
121 local function processEnvVar(value)
122 for name in value:gmatch("${([^}]+)}") do
123 local replacement = loader.getenv(name) or ""
124 value = value:gsub("${" .. escapeName(name) .. "}", replacement)
126 for name in value:gmatch("$([%w%p]+)%s*") do
127 local replacement = loader.getenv(name) or ""
128 value = value:gsub("$" .. escapeName(name), replacement)
133 local function checkPattern(line, pattern)
134 local function _realCheck(_line, _pattern)
135 return _line:match(_pattern)
138 if pattern:find('$VALUE') then
140 k, v, c = _realCheck(line, pattern:gsub('$VALUE', QVALREPL))
144 return _realCheck(line, pattern:gsub('$VALUE', WORDREPL))
146 return _realCheck(line, pattern)
150 -- str in this table is a regex pattern. It will automatically be anchored to
151 -- the beginning of a line and any preceding whitespace will be skipped. The
152 -- pattern should have no more than two captures patterns, which correspond to
153 -- the two parameters (usually 'key' and 'value') that are passed to the
154 -- process function. All trailing characters will be validated. Any $VALUE
155 -- token included in a pattern will be tried first with a quoted value capture
156 -- group, then a single-word value capture group. This is our kludge for Lua
157 -- regex not supporting branching.
159 -- We have two special entries in this table: the first is the first entry,
160 -- a full-line comment. The second is for 'exec' handling. Both have a single
161 -- capture group, but the difference is that the full-line comment pattern will
162 -- match the entire line. This does not run afoul of the later end of line
163 -- validation that we'll do after a match. However, the 'exec' pattern will.
164 -- We document the exceptions with a special 'groups' index that indicates
165 -- the number of capture groups, if not two. We'll use this later to do
166 -- validation on the proper entry.
168 local pattern_table = {
171 process = function(_, _) end,
174 -- module_load="value"
176 str = MODULEEXPR .. "_load%s*=%s*$VALUE",
177 process = function(k, v)
178 if modules[k] == nil then
181 modules[k].load = v:upper()
184 -- module_name="value"
186 str = MODULEEXPR .. "_name%s*=%s*$VALUE",
187 process = function(k, v)
191 -- module_type="value"
193 str = MODULEEXPR .. "_type%s*=%s*$VALUE",
194 process = function(k, v)
198 -- module_flags="value"
200 str = MODULEEXPR .. "_flags%s*=%s*$VALUE",
201 process = function(k, v)
202 setKey(k, "flags", v)
205 -- module_before="value"
207 str = MODULEEXPR .. "_before%s*=%s*$VALUE",
208 process = function(k, v)
209 setKey(k, "before", v)
212 -- module_after="value"
214 str = MODULEEXPR .. "_after%s*=%s*$VALUE",
215 process = function(k, v)
216 setKey(k, "after", v)
219 -- module_error="value"
221 str = MODULEEXPR .. "_error%s*=%s*$VALUE",
222 process = function(k, v)
223 setKey(k, "error", v)
228 str = "exec%s*=%s*" .. QVALEXPR,
229 process = function(k, _)
230 if cli_execute_unparsed(k) ~= 0 then
231 print(MSG_FAILEXEC:format(k))
238 str = "([%w%p]+)%s*=%s*$VALUE",
239 process = function(k, v)
240 if setEnv(k, processEnvVar(v)) ~= 0 then
241 print(MSG_FAILSETENV:format(k, v))
247 str = "([%w%p]+)%s*=%s*(-?%d+)",
248 process = function(k, v)
249 if setEnv(k, processEnvVar(v)) ~= 0 then
250 print(MSG_FAILSETENV:format(k, tostring(v)))
256 local function isValidComment(line)
258 local s = line:match("^%s*#.*")
260 s = line:match("^%s*$")
269 local function getBlacklist()
270 local blacklist_str = loader.getenv('module_blacklist')
271 if blacklist_str == nil then
276 for mod in blacklist_str:gmatch("[;, ]?([%w-_]+)[;, ]?") do
277 blacklist[mod] = true
282 local function loadModule(mod, silent)
284 local blacklist = getBlacklist()
286 for k, v in pairs(mod) do
287 if v.load ~= nil and v.load:lower() == "yes" then
288 local module_name = v.name or k
289 if blacklist[module_name] ~= nil then
291 print(MSG_MODBLACKLIST:format(module_name))
296 if v.type ~= nil then
297 str = str .. "-t " .. v.type .. " "
299 str = str .. module_name
300 if v.flags ~= nil then
301 str = str .. " " .. v.flags
303 if v.before ~= nil then
304 pstatus = cli_execute_unparsed(v.before) == 0
305 if not pstatus and not silent then
306 print(MSG_FAILEXBEF:format(v.before, k))
308 status = status and pstatus
311 if cli_execute_unparsed(str) ~= 0 then
313 print(MSG_FAILEXMOD:format(str))
315 if v.error ~= nil then
316 cli_execute_unparsed(v.error)
321 if v.after ~= nil then
322 pstatus = cli_execute_unparsed(v.after) == 0
323 if not pstatus and not silent then
324 print(MSG_FAILEXAF:format(v.after, k))
326 status = status and pstatus
336 local function readConfFiles(loaded_files)
337 local f = loader.getenv("loader_conf_files")
339 for name in f:gmatch("([%w%p]+)%s*") do
340 if loaded_files[name] ~= nil then
344 local prefiles = loader.getenv("loader_conf_files")
346 print("Loading " .. name)
347 -- These may or may not exist, and that's ok. Do a
348 -- silent parse so that we complain on parse errors but
349 -- not for them simply not existing.
350 if not config.processFile(name, true) then
351 print(MSG_FAILPARSECFG:format(name))
354 loaded_files[name] = true
355 local newfiles = loader.getenv("loader_conf_files")
356 if prefiles ~= newfiles then
357 readConfFiles(loaded_files)
364 local function readFile(name, silent)
365 local f = io.open(name)
368 print(MSG_FAILOPENCFG:format(name))
373 local text, _ = io.read(f)
374 -- We might have read in the whole file, this won't be needed any more.
377 if text == nil and not silent then
378 print(MSG_FAILREADCFG:format(name))
383 local function checkNextboot()
384 local nextboot_file = loader.getenv("nextboot_conf")
385 if nextboot_file == nil then
389 local text = readFile(nextboot_file, true)
394 if text:match("^nextboot_enable=\"NO\"") ~= nil then
395 -- We're done; nextboot is not enabled
399 if not config.parse(text) then
400 print(MSG_FAILPARSECFG:format(nextboot_file))
403 -- Attempt to rewrite the first line and only the first line of the
404 -- nextboot_file. We overwrite it with nextboot_enable="NO", then
405 -- check for that on load.
406 -- It's worth noting that this won't work on every filesystem, so we
407 -- won't do anything notable if we have any errors in this process.
408 local nfile = io.open(nextboot_file, 'w')
410 -- We need the trailing space here to account for the extra
411 -- character taken up by the string nextboot_enable="YES"
412 -- Or new end quotation mark lands on the S, and we want to
413 -- rewrite the entirety of the first line.
414 io.write(nfile, "nextboot_enable=\"NO\" ")
420 config.verbose = false
422 -- The first item in every carousel is always the default item.
423 function config.getCarouselIndex(id)
424 return carousel_choices[id] or 1
427 function config.setCarouselIndex(id, idx)
428 carousel_choices[id] = idx
431 -- Returns true if we processed the file successfully, false if we did not.
432 -- If 'silent' is true, being unable to read the file is not considered a
434 function config.processFile(name, silent)
435 if silent == nil then
439 local text = readFile(name, silent)
444 return config.parse(text)
447 -- silent runs will not return false if we fail to open the file
448 function config.parse(text)
452 for line in text:gmatch("([^\n]+)") do
453 if line:match("^%s*$") == nil then
454 for _, val in ipairs(pattern_table) do
455 local pattern = '^%s*' .. val.str .. '%s*(.*)';
456 local cgroups = val.groups or 2
457 local k, v, c = checkPattern(line, pattern)
459 -- Offset by one, drats
465 if isValidComment(c) then
474 print(MSG_MALFORMED:format(n, line))
484 -- other_kernel is optionally the name of a kernel to load, if not the default
485 -- or autoloaded default from the module_path
486 function config.loadKernel(other_kernel)
487 local flags = loader.getenv("kernel_options") or ""
488 local kernel = other_kernel or loader.getenv("kernel")
490 local function tryLoad(names)
491 for name in names:gmatch("([^;]+)%s*;?") do
492 local r = loader.perform("load " .. name ..
501 local function getModulePath()
502 local module_path = loader.getenv("module_path")
503 local kernel_path = loader.getenv("kernel_path")
505 if kernel_path == nil then
509 -- Strip the loaded kernel path from module_path. This currently assumes
510 -- that the kernel path will be prepended to the module_path when it's
512 kernel_path = escapeName(kernel_path .. ';')
513 return module_path:gsub(kernel_path, '')
516 local function loadBootfile()
517 local bootfile = loader.getenv("bootfile")
519 -- append default kernel name
520 if bootfile == nil then
523 bootfile = bootfile .. ";kernel"
526 return tryLoad(bootfile)
529 -- kernel not set, try load from default module_path
530 if kernel == nil then
531 local res = loadBootfile()
534 -- Default kernel is loaded
535 config.kernel_loaded = nil
538 print(MSG_DEFAULTKERNFAIL)
542 -- Use our cached module_path, so we don't end up with multiple
543 -- automatically added kernel paths to our final module_path
544 local module_path = getModulePath()
547 if other_kernel ~= nil then
548 kernel = other_kernel
550 -- first try load kernel with module_path = /boot/${kernel}
551 -- then try load with module_path=${kernel}
552 local paths = {"/boot/" .. kernel, kernel}
554 for _, v in pairs(paths) do
555 loader.setenv("module_path", v)
558 -- succeeded, add path to module_path
560 config.kernel_loaded = kernel
561 if module_path ~= nil then
562 loader.setenv("module_path", v .. ";" ..
564 loader.setenv("kernel_path", v)
570 -- failed to load with ${kernel} as a directory
572 res = tryLoad(kernel)
574 config.kernel_loaded = kernel
577 print(MSG_KERNFAIL:format(kernel))
583 function config.selectKernel(kernel)
584 config.kernel_selected = kernel
587 function config.load(file, reloading)
589 file = "/boot/defaults/loader.conf"
592 if not config.processFile(file) then
593 print(MSG_FAILPARSECFG:format(file))
596 local loaded_files = {file = true}
597 readConfFiles(loaded_files)
601 local verbose = loader.getenv("verbose_loading") or "no"
602 config.verbose = verbose:lower() == "yes"
603 if not reloading then
604 hook.runAll("config.loaded")
608 -- Reload configuration
609 function config.reload(file)
612 config.load(file, true)
613 hook.runAll("config.reloaded")
616 function config.loadelf()
617 local xen_kernel = loader.getenv('xen_kernel')
618 local kernel = config.kernel_selected or config.kernel_loaded
621 if xen_kernel ~= nil then
622 print(MSG_XENKERNLOADING)
623 if cli_execute_unparsed('load ' .. xen_kernel) ~= 0 then
624 print(MSG_XENKERNFAIL:format(xen_kernel))
628 print(MSG_KERNLOADING)
629 loaded = config.loadKernel(kernel)
635 print(MSG_MODLOADING)
636 if not loadModule(modules, not config.verbose) then
637 print(MSG_MODLOADFAIL)
641 hook.registerType("config.loaded")
642 hook.registerType("config.reloaded")