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-_]+)'
61 local function restoreEnv()
62 -- Examine changed environment variables
63 for k, v in pairs(env_changed) do
64 local restore_value = env_restore[k]
65 if restore_value == nil then
66 -- This one doesn't need restored for some reason
69 local current_value = loader.getenv(k)
70 if current_value ~= v then
71 -- This was overwritten by some action taken on the menu
72 -- most likely; we'll leave it be.
75 restore_value = restore_value.value
76 if restore_value ~= nil then
77 loader.setenv(k, restore_value)
88 local function setEnv(key, value)
89 -- Track the original value for this if we haven't already
90 if env_restore[key] == nil then
91 env_restore[key] = {value = loader.getenv(key)}
94 env_changed[key] = value
96 return loader.setenv(key, value)
99 -- name here is one of 'name', 'type', flags', 'before', 'after', or 'error.'
100 -- These are set from lines in loader.conf(5): ${key}_${name}="${value}" where
101 -- ${key} is a module name.
102 local function setKey(key, name, value)
103 if modules[key] == nil then
106 modules[key][name] = value
109 -- Escapes the named value for use as a literal in a replacement pattern.
110 -- e.g. dhcp.host-name gets turned into dhcp%.host%-name to remove the special
112 local function escapeName(name)
113 return name:gsub("([%p])", "%%%1")
116 local function processEnvVar(value)
117 for name in value:gmatch("${([^}]+)}") do
118 local replacement = loader.getenv(name) or ""
119 value = value:gsub("${" .. escapeName(name) .. "}", replacement)
121 for name in value:gmatch("$([%w%p]+)%s*") do
122 local replacement = loader.getenv(name) or ""
123 value = value:gsub("$" .. escapeName(name), replacement)
128 -- str in this table is a regex pattern. It will automatically be anchored to
129 -- the beginning of a line and any preceding whitespace will be skipped. The
130 -- pattern should have no more than two captures patterns, which correspond to
131 -- the two parameters (usually 'key' and 'value') that are passed to the
132 -- process function. All trailing characters will be validated.
134 -- We have two special entries in this table: the first is the first entry,
135 -- a full-line comment. The second is for 'exec' handling. Both have a single
136 -- capture group, but the difference is that the full-line comment pattern will
137 -- match the entire line. This does not run afoul of the later end of line
138 -- validation that we'll do after a match. However, the 'exec' pattern will.
139 -- We document the exceptions with a special 'groups' index that indicates
140 -- the number of capture groups, if not two. We'll use this later to do
141 -- validation on the proper entry.
142 local pattern_table = {
145 process = function(_, _) end,
148 -- module_load="value"
150 str = MODULEEXPR .. "_load%s*=%s*\"([%w%s%p]-)\"",
151 process = function(k, v)
152 if modules[k] == nil then
155 modules[k].load = v:upper()
158 -- module_name="value"
160 str = MODULEEXPR .. "_name%s*=%s*\"([%w%s%p]-)\"",
161 process = function(k, v)
165 -- module_type="value"
167 str = MODULEEXPR .. "_type%s*=%s*\"([%w%s%p]-)\"",
168 process = function(k, v)
172 -- module_flags="value"
174 str = MODULEEXPR .. "_flags%s*=%s*\"([%w%s%p]-)\"",
175 process = function(k, v)
176 setKey(k, "flags", v)
179 -- module_before="value"
181 str = MODULEEXPR .. "_before%s*=%s*\"([%w%s%p]-)\"",
182 process = function(k, v)
183 setKey(k, "before", v)
186 -- module_after="value"
188 str = MODULEEXPR .. "_after%s*=%s*\"([%w%s%p]-)\"",
189 process = function(k, v)
190 setKey(k, "after", v)
193 -- module_error="value"
195 str = MODULEEXPR .. "_error%s*=%s*\"([%w%s%p]-)\"",
196 process = function(k, v)
197 setKey(k, "error", v)
202 str = "exec%s*=%s*\"([%w%s%p]-)\"",
203 process = function(k, _)
204 if cli_execute_unparsed(k) ~= 0 then
205 print(MSG_FAILEXEC:format(k))
212 str = "([%w%p]+)%s*=%s*\"([%w%s%p]-)\"",
213 process = function(k, v)
214 if setEnv(k, processEnvVar(v)) ~= 0 then
215 print(MSG_FAILSETENV:format(k, v))
221 str = "([%w%p]+)%s*=%s*(-?%d+)",
222 process = function(k, v)
223 if setEnv(k, processEnvVar(v)) ~= 0 then
224 print(MSG_FAILSETENV:format(k, tostring(v)))
230 local function isValidComment(line)
232 local s = line:match("^%s*#.*")
234 s = line:match("^%s*$")
243 local function loadModule(mod, silent)
246 for k, v in pairs(mod) do
247 if v.load ~= nil and v.load:lower() == "yes" then
249 if v.type ~= nil then
250 str = str .. "-t " .. v.type .. " "
252 if v.name ~= nil then
257 if v.flags ~= nil then
258 str = str .. " " .. v.flags
260 if v.before ~= nil then
261 pstatus = cli_execute_unparsed(v.before) == 0
262 if not pstatus and not silent then
263 print(MSG_FAILEXBEF:format(v.before, k))
265 status = status and pstatus
268 if cli_execute_unparsed(str) ~= 0 then
270 print(MSG_FAILEXMOD:format(str))
272 if v.error ~= nil then
273 cli_execute_unparsed(v.error)
278 if v.after ~= nil then
279 pstatus = cli_execute_unparsed(v.after) == 0
280 if not pstatus and not silent then
281 print(MSG_FAILEXAF:format(v.after, k))
283 status = status and pstatus
292 local function readConfFiles(loaded_files)
293 local f = loader.getenv("loader_conf_files")
295 for name in f:gmatch("([%w%p]+)%s*") do
296 if loaded_files[name] ~= nil then
300 local prefiles = loader.getenv("loader_conf_files")
302 print("Loading " .. name)
303 -- These may or may not exist, and that's ok. Do a
304 -- silent parse so that we complain on parse errors but
305 -- not for them simply not existing.
306 if not config.processFile(name, true) then
307 print(MSG_FAILPARSECFG:format(name))
310 loaded_files[name] = true
311 local newfiles = loader.getenv("loader_conf_files")
312 if prefiles ~= newfiles then
313 readConfFiles(loaded_files)
320 local function readFile(name, silent)
321 local f = io.open(name)
324 print(MSG_FAILOPENCFG:format(name))
329 local text, _ = io.read(f)
330 -- We might have read in the whole file, this won't be needed any more.
333 if text == nil and not silent then
334 print(MSG_FAILREADCFG:format(name))
339 local function checkNextboot()
340 local nextboot_file = loader.getenv("nextboot_conf")
341 if nextboot_file == nil then
345 local text = readFile(nextboot_file, true)
350 if text:match("^nextboot_enable=\"NO\"") ~= nil then
351 -- We're done; nextboot is not enabled
355 if not config.parse(text) then
356 print(MSG_FAILPARSECFG:format(nextboot_file))
359 -- Attempt to rewrite the first line and only the first line of the
360 -- nextboot_file. We overwrite it with nextboot_enable="NO", then
361 -- check for that on load.
362 -- It's worth noting that this won't work on every filesystem, so we
363 -- won't do anything notable if we have any errors in this process.
364 local nfile = io.open(nextboot_file, 'w')
366 -- We need the trailing space here to account for the extra
367 -- character taken up by the string nextboot_enable="YES"
368 -- Or new end quotation mark lands on the S, and we want to
369 -- rewrite the entirety of the first line.
370 io.write(nfile, "nextboot_enable=\"NO\" ")
376 config.verbose = false
378 -- The first item in every carousel is always the default item.
379 function config.getCarouselIndex(id)
380 return carousel_choices[id] or 1
383 function config.setCarouselIndex(id, idx)
384 carousel_choices[id] = idx
387 -- Returns true if we processed the file successfully, false if we did not.
388 -- If 'silent' is true, being unable to read the file is not considered a
390 function config.processFile(name, silent)
391 if silent == nil then
395 local text = readFile(name, silent)
400 return config.parse(text)
403 -- silent runs will not return false if we fail to open the file
404 function config.parse(text)
408 for line in text:gmatch("([^\n]+)") do
409 if line:match("^%s*$") == nil then
410 for _, val in ipairs(pattern_table) do
411 local pattern = '^%s*' .. val.str .. '%s*(.*)';
412 local cgroups = val.groups or 2
413 local k, v, c = line:match(pattern)
415 -- Offset by one, drats
421 if isValidComment(c) then
430 print(MSG_MALFORMED:format(n, line))
440 -- other_kernel is optionally the name of a kernel to load, if not the default
441 -- or autoloaded default from the module_path
442 function config.loadKernel(other_kernel)
443 local flags = loader.getenv("kernel_options") or ""
444 local kernel = other_kernel or loader.getenv("kernel")
446 local function tryLoad(names)
447 for name in names:gmatch("([^;]+)%s*;?") do
448 local r = loader.perform("load " .. name ..
457 local function loadBootfile()
458 local bootfile = loader.getenv("bootfile")
460 -- append default kernel name
461 if bootfile == nil then
464 bootfile = bootfile .. ";kernel"
467 return tryLoad(bootfile)
470 -- kernel not set, try load from default module_path
471 if kernel == nil then
472 local res = loadBootfile()
475 -- Default kernel is loaded
476 config.kernel_loaded = nil
479 print(MSG_DEFAULTKERNFAIL)
483 -- Use our cached module_path, so we don't end up with multiple
484 -- automatically added kernel paths to our final module_path
485 local module_path = config.module_path
488 if other_kernel ~= nil then
489 kernel = other_kernel
491 -- first try load kernel with module_path = /boot/${kernel}
492 -- then try load with module_path=${kernel}
493 local paths = {"/boot/" .. kernel, kernel}
495 for _, v in pairs(paths) do
496 loader.setenv("module_path", v)
499 -- succeeded, add path to module_path
501 config.kernel_loaded = kernel
502 if module_path ~= nil then
503 loader.setenv("module_path", v .. ";" ..
510 -- failed to load with ${kernel} as a directory
512 res = tryLoad(kernel)
514 config.kernel_loaded = kernel
517 print(MSG_KERNFAIL:format(kernel))
523 function config.selectKernel(kernel)
524 config.kernel_selected = kernel
527 function config.load(file, reloading)
529 file = "/boot/defaults/loader.conf"
532 if not config.processFile(file) then
533 print(MSG_FAILPARSECFG:format(file))
536 local loaded_files = {file = true}
537 readConfFiles(loaded_files)
541 -- Cache the provided module_path at load time for later use
542 config.module_path = loader.getenv("module_path")
543 local verbose = loader.getenv("verbose_loading") or "no"
544 config.verbose = verbose:lower() == "yes"
545 if not reloading then
546 hook.runAll("config.loaded")
550 -- Reload configuration
551 function config.reload(file)
554 config.load(file, true)
555 hook.runAll("config.reloaded")
558 function config.loadelf()
559 local xen_kernel = loader.getenv('xen_kernel')
560 local kernel = config.kernel_selected or config.kernel_loaded
563 if xen_kernel ~= nil then
564 print(MSG_XENKERNLOADING)
565 if cli_execute_unparsed('load ' .. xen_kernel) ~= 0 then
566 print(MSG_XENKERNFAIL:format(xen_kernel))
570 print(MSG_KERNLOADING)
571 loaded = config.loadKernel(kernel)
577 print(MSG_MODLOADING)
578 if not loadModule(modules, not config.verbose) then
579 print(MSG_MODLOADFAIL)
583 hook.registerType("config.loaded")
584 hook.registerType("config.reloaded")