]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - stand/lua/config.lua
config.lua(8): "may should" is not proper grammar
[FreeBSD/FreeBSD.git] / stand / lua / config.lua
1 --
2 -- SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3 --
4 -- Copyright (c) 2015 Pedro Souza <pedrosouza@freebsd.org>
5 -- Copyright (c) 2018 Kyle Evans <kevans@FreeBSD.org>
6 -- All rights reserved.
7 --
8 -- Redistribution and use in source and binary forms, with or without
9 -- modification, are permitted provided that the following conditions
10 -- are met:
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.
16 --
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
27 -- SUCH DAMAGE.
28 --
29 -- $FreeBSD$
30 --
31
32 local hook = require("hook")
33
34 local config = {}
35 local modules = {}
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 = {}
41
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_FAILEXAF = "Failed to execute '%s' after loading '%s'"
49 local MSG_MALFORMED = "Malformed line (%d):\n\t'%s'"
50 local MSG_DEFAULTKERNFAIL = "No kernel set, failed to load from module_path"
51 local MSG_KERNFAIL = "Failed to load kernel '%s'"
52 local MSG_XENKERNFAIL = "Failed to load Xen kernel '%s'"
53 local MSG_XENKERNLOADING = "Loading Xen kernel..."
54 local MSG_KERNLOADING = "Loading kernel..."
55 local MSG_MODLOADING = "Loading configured modules..."
56 local MSG_MODBLACKLIST = "Not loading blacklisted module '%s'"
57
58 local MODULEEXPR = '([%w-_]+)'
59 local QVALEXPR = "\"([%w%s%p]-)\""
60 local QVALREPL = QVALEXPR:gsub('%%', '%%%%')
61 local WORDEXPR = "([%w]+)"
62 local WORDREPL = WORDEXPR:gsub('%%', '%%%%')
63
64 local function restoreEnv()
65         -- Examine changed environment variables
66         for k, v in pairs(env_changed) do
67                 local restore_value = env_restore[k]
68                 if restore_value == nil then
69                         -- This one doesn't need restored for some reason
70                         goto continue
71                 end
72                 local current_value = loader.getenv(k)
73                 if current_value ~= v then
74                         -- This was overwritten by some action taken on the menu
75                         -- most likely; we'll leave it be.
76                         goto continue
77                 end
78                 restore_value = restore_value.value
79                 if restore_value ~= nil then
80                         loader.setenv(k, restore_value)
81                 else
82                         loader.unsetenv(k)
83                 end
84                 ::continue::
85         end
86
87         env_changed = {}
88         env_restore = {}
89 end
90
91 local function setEnv(key, value)
92         -- Track the original value for this if we haven't already
93         if env_restore[key] == nil then
94                 env_restore[key] = {value = loader.getenv(key)}
95         end
96
97         env_changed[key] = value
98
99         return loader.setenv(key, value)
100 end
101
102 -- name here is one of 'name', 'type', flags', 'before', 'after', or 'error.'
103 -- These are set from lines in loader.conf(5): ${key}_${name}="${value}" where
104 -- ${key} is a module name.
105 local function setKey(key, name, value)
106         if modules[key] == nil then
107                 modules[key] = {}
108         end
109         modules[key][name] = value
110 end
111
112 -- Escapes the named value for use as a literal in a replacement pattern.
113 -- e.g. dhcp.host-name gets turned into dhcp%.host%-name to remove the special
114 -- meaning.
115 local function escapeName(name)
116         return name:gsub("([%p])", "%%%1")
117 end
118
119 local function processEnvVar(value)
120         for name in value:gmatch("${([^}]+)}") do
121                 local replacement = loader.getenv(name) or ""
122                 value = value:gsub("${" .. escapeName(name) .. "}", replacement)
123         end
124         for name in value:gmatch("$([%w%p]+)%s*") do
125                 local replacement = loader.getenv(name) or ""
126                 value = value:gsub("$" .. escapeName(name), replacement)
127         end
128         return value
129 end
130
131 local function checkPattern(line, pattern)
132         local function _realCheck(_line, _pattern)
133                 return _line:match(_pattern)
134         end
135
136         if pattern:find('$VALUE') then
137                 local k, v, c
138                 k, v, c = _realCheck(line, pattern:gsub('$VALUE', QVALREPL))
139                 if k ~= nil then
140                         return k,v, c
141                 end
142                 return _realCheck(line, pattern:gsub('$VALUE', WORDREPL))
143         else
144                 return _realCheck(line, pattern)
145         end
146 end
147
148 -- str in this table is a regex pattern.  It will automatically be anchored to
149 -- the beginning of a line and any preceding whitespace will be skipped.  The
150 -- pattern should have no more than two captures patterns, which correspond to
151 -- the two parameters (usually 'key' and 'value') that are passed to the
152 -- process function.  All trailing characters will be validated.  Any $VALUE
153 -- token included in a pattern will be tried first with a quoted value capture
154 -- group, then a single-word value capture group.  This is our kludge for Lua
155 -- regex not supporting branching.
156 --
157 -- We have two special entries in this table: the first is the first entry,
158 -- a full-line comment.  The second is for 'exec' handling.  Both have a single
159 -- capture group, but the difference is that the full-line comment pattern will
160 -- match the entire line.  This does not run afoul of the later end of line
161 -- validation that we'll do after a match.  However, the 'exec' pattern will.
162 -- We document the exceptions with a special 'groups' index that indicates
163 -- the number of capture groups, if not two.  We'll use this later to do
164 -- validation on the proper entry.
165 --
166 local pattern_table = {
167         {
168                 str = "(#.*)",
169                 process = function(_, _)  end,
170                 groups = 1,
171         },
172         --  module_load="value"
173         {
174                 str = MODULEEXPR .. "_load%s*=%s*$VALUE",
175                 process = function(k, v)
176                         if modules[k] == nil then
177                                 modules[k] = {}
178                         end
179                         modules[k].load = v:upper()
180                 end,
181         },
182         --  module_name="value"
183         {
184                 str = MODULEEXPR .. "_name%s*=%s*$VALUE",
185                 process = function(k, v)
186                         setKey(k, "name", v)
187                 end,
188         },
189         --  module_type="value"
190         {
191                 str = MODULEEXPR .. "_type%s*=%s*$VALUE",
192                 process = function(k, v)
193                         setKey(k, "type", v)
194                 end,
195         },
196         --  module_flags="value"
197         {
198                 str = MODULEEXPR .. "_flags%s*=%s*$VALUE",
199                 process = function(k, v)
200                         setKey(k, "flags", v)
201                 end,
202         },
203         --  module_before="value"
204         {
205                 str = MODULEEXPR .. "_before%s*=%s*$VALUE",
206                 process = function(k, v)
207                         setKey(k, "before", v)
208                 end,
209         },
210         --  module_after="value"
211         {
212                 str = MODULEEXPR .. "_after%s*=%s*$VALUE",
213                 process = function(k, v)
214                         setKey(k, "after", v)
215                 end,
216         },
217         --  module_error="value"
218         {
219                 str = MODULEEXPR .. "_error%s*=%s*$VALUE",
220                 process = function(k, v)
221                         setKey(k, "error", v)
222                 end,
223         },
224         --  exec="command"
225         {
226                 str = "exec%s*=%s*" .. QVALEXPR,
227                 process = function(k, _)
228                         if cli_execute_unparsed(k) ~= 0 then
229                                 print(MSG_FAILEXEC:format(k))
230                         end
231                 end,
232                 groups = 1,
233         },
234         --  env_var="value"
235         {
236                 str = "([%w%p]+)%s*=%s*$VALUE",
237                 process = function(k, v)
238                         if setEnv(k, processEnvVar(v)) ~= 0 then
239                                 print(MSG_FAILSETENV:format(k, v))
240                         end
241                 end,
242         },
243         --  env_var=num
244         {
245                 str = "([%w%p]+)%s*=%s*(-?%d+)",
246                 process = function(k, v)
247                         if setEnv(k, processEnvVar(v)) ~= 0 then
248                                 print(MSG_FAILSETENV:format(k, tostring(v)))
249                         end
250                 end,
251         },
252 }
253
254 local function isValidComment(line)
255         if line ~= nil then
256                 local s = line:match("^%s*#.*")
257                 if s == nil then
258                         s = line:match("^%s*$")
259                 end
260                 if s == nil then
261                         return false
262                 end
263         end
264         return true
265 end
266
267 local function getBlacklist()
268         local blacklist = {}
269         local blacklist_str = loader.getenv('module_blacklist')
270         if blacklist_str == nil then
271                 return blacklist
272         end
273
274         for mod in blacklist_str:gmatch("[;, ]?([%w-_]+)[;, ]?") do
275                 blacklist[mod] = true
276         end
277         return blacklist
278 end
279
280 local function loadModule(mod, silent)
281         local status = true
282         local blacklist = getBlacklist()
283         local pstatus
284         for k, v in pairs(mod) do
285                 if v.load ~= nil and v.load:lower() == "yes" then
286                         local module_name = v.name or k
287                         if blacklist[module_name] ~= nil then
288                                 if not silent then
289                                         print(MSG_MODBLACKLIST:format(module_name))
290                                 end
291                                 goto continue
292                         end
293                         if not silent then
294                                 loader.printc(module_name .. "...")
295                         end
296                         local str = "load "
297                         if v.type ~= nil then
298                                 str = str .. "-t " .. v.type .. " "
299                         end
300                         str = str .. module_name
301                         if v.flags ~= nil then
302                                 str = str .. " " .. v.flags
303                         end
304                         if v.before ~= nil then
305                                 pstatus = cli_execute_unparsed(v.before) == 0
306                                 if not pstatus and not silent then
307                                         print(MSG_FAILEXBEF:format(v.before, k))
308                                 end
309                                 status = status and pstatus
310                         end
311
312                         if cli_execute_unparsed(str) ~= 0 then
313                                 -- XXX Temporary shim: don't break the boot if
314                                 -- loader hadn't been recompiled with this
315                                 -- function exposed.
316                                 if loader.command_error then
317                                         print(loader.command_error())
318                                 end
319                                 if not silent then
320                                         print("failed!")
321                                 end
322                                 if v.error ~= nil then
323                                         cli_execute_unparsed(v.error)
324                                 end
325                                 status = false
326                         elseif v.after ~= nil then
327                                 pstatus = cli_execute_unparsed(v.after) == 0
328                                 if not pstatus and not silent then
329                                         print(MSG_FAILEXAF:format(v.after, k))
330                                 end
331                                 if not silent then
332                                         print("ok")
333                                 end
334                                 status = status and pstatus
335                         end
336                 end
337                 ::continue::
338         end
339
340         return status
341 end
342
343 local function readFile(name, silent)
344         local f = io.open(name)
345         if f == nil then
346                 if not silent then
347                         print(MSG_FAILOPENCFG:format(name))
348                 end
349                 return nil
350         end
351
352         local text, _ = io.read(f)
353         -- We might have read in the whole file, this won't be needed any more.
354         io.close(f)
355
356         if text == nil and not silent then
357                 print(MSG_FAILREADCFG:format(name))
358         end
359         return text
360 end
361
362 local function checkNextboot()
363         local nextboot_file = loader.getenv("nextboot_conf")
364         if nextboot_file == nil then
365                 return
366         end
367
368         local text = readFile(nextboot_file, true)
369         if text == nil then
370                 return
371         end
372
373         if text:match("^nextboot_enable=\"NO\"") ~= nil then
374                 -- We're done; nextboot is not enabled
375                 return
376         end
377
378         if not config.parse(text) then
379                 print(MSG_FAILPARSECFG:format(nextboot_file))
380         end
381
382         -- Attempt to rewrite the first line and only the first line of the
383         -- nextboot_file. We overwrite it with nextboot_enable="NO", then
384         -- check for that on load.
385         -- It's worth noting that this won't work on every filesystem, so we
386         -- won't do anything notable if we have any errors in this process.
387         local nfile = io.open(nextboot_file, 'w')
388         if nfile ~= nil then
389                 -- We need the trailing space here to account for the extra
390                 -- character taken up by the string nextboot_enable="YES"
391                 -- Or new end quotation mark lands on the S, and we want to
392                 -- rewrite the entirety of the first line.
393                 io.write(nfile, "nextboot_enable=\"NO\" ")
394                 io.close(nfile)
395         end
396 end
397
398 -- Module exports
399 config.verbose = false
400
401 -- The first item in every carousel is always the default item.
402 function config.getCarouselIndex(id)
403         return carousel_choices[id] or 1
404 end
405
406 function config.setCarouselIndex(id, idx)
407         carousel_choices[id] = idx
408 end
409
410 -- Returns true if we processed the file successfully, false if we did not.
411 -- If 'silent' is true, being unable to read the file is not considered a
412 -- failure.
413 function config.processFile(name, silent)
414         if silent == nil then
415                 silent = false
416         end
417
418         local text = readFile(name, silent)
419         if text == nil then
420                 return silent
421         end
422
423         return config.parse(text)
424 end
425
426 -- silent runs will not return false if we fail to open the file
427 function config.parse(text)
428         local n = 1
429         local status = true
430
431         for line in text:gmatch("([^\n]+)") do
432                 if line:match("^%s*$") == nil then
433                         for _, val in ipairs(pattern_table) do
434                                 local pattern = '^%s*' .. val.str .. '%s*(.*)';
435                                 local cgroups = val.groups or 2
436                                 local k, v, c = checkPattern(line, pattern)
437                                 if k ~= nil then
438                                         -- Offset by one, drats
439                                         if cgroups == 1 then
440                                                 c = v
441                                                 v = nil
442                                         end
443
444                                         if isValidComment(c) then
445                                                 val.process(k, v)
446                                                 goto nextline
447                                         end
448
449                                         break
450                                 end
451                         end
452
453                         print(MSG_MALFORMED:format(n, line))
454                         status = false
455                 end
456                 ::nextline::
457                 n = n + 1
458         end
459
460         return status
461 end
462
463 function config.readConfFiles(files, loaded_files)
464         if files ~= nil then
465                 -- The caller may not have passed in loader_conf_files; we could
466                 -- have instead gotten some other string of files.  We don't
467                 -- want to trigger any redundant re-read/loads based on this.
468                 local prefiles = loader.getenv("loader_conf_files")
469                 for name in files:gmatch("([%w%p]+)%s*") do
470                         if loaded_files[name] ~= nil then
471                                 goto continue
472                         end
473
474                         print("Loading " .. name)
475                         -- These may or may not exist, and that's ok. Do a
476                         -- silent parse so that we complain on parse errors but
477                         -- not for them simply not existing.
478                         if not config.processFile(name, true) then
479                                 print(MSG_FAILPARSECFG:format(name))
480                         end
481
482                         loaded_files[name] = true
483                         local newfiles = loader.getenv("loader_conf_files")
484                         if prefiles ~= newfiles then
485                                 -- Recurse; process the new files immediately.
486                                 -- If we come back and it turns out we've
487                                 -- already loaded the rest of what was in the
488                                 -- original loader_conf_files, no big deal.
489                                 config.readConfFiles(newfiles, loaded_files)
490                                 prefiles = newfiles
491                         end
492                         ::continue::
493                 end
494         end
495 end
496
497 -- other_kernel is optionally the name of a kernel to load, if not the default
498 -- or autoloaded default from the module_path
499 function config.loadKernel(other_kernel)
500         local flags = loader.getenv("kernel_options") or ""
501         local kernel = other_kernel or loader.getenv("kernel")
502
503         local function tryLoad(names)
504                 for name in names:gmatch("([^;]+)%s*;?") do
505                         local r = loader.perform("load " .. name ..
506                              " " .. flags)
507                         if r == 0 then
508                                 return name
509                         end
510                 end
511                 return nil
512         end
513
514         local function getModulePath()
515                 local module_path = loader.getenv("module_path")
516                 local kernel_path = loader.getenv("kernel_path")
517
518                 if kernel_path == nil then
519                         return module_path
520                 end
521
522                 -- Strip the loaded kernel path from module_path. This currently assumes
523                 -- that the kernel path will be prepended to the module_path when it's
524                 -- found.
525                 kernel_path = escapeName(kernel_path .. ';')
526                 return module_path:gsub(kernel_path, '')
527         end
528
529         local function loadBootfile()
530                 local bootfile = loader.getenv("bootfile")
531
532                 -- append default kernel name
533                 if bootfile == nil then
534                         bootfile = "kernel"
535                 else
536                         bootfile = bootfile .. ";kernel"
537                 end
538
539                 return tryLoad(bootfile)
540         end
541
542         -- kernel not set, try load from default module_path
543         if kernel == nil then
544                 local res = loadBootfile()
545
546                 if res ~= nil then
547                         -- Default kernel is loaded
548                         config.kernel_loaded = nil
549                         return true
550                 else
551                         print(MSG_DEFAULTKERNFAIL)
552                         return false
553                 end
554         else
555                 -- Use our cached module_path, so we don't end up with multiple
556                 -- automatically added kernel paths to our final module_path
557                 local module_path = getModulePath()
558                 local res
559
560                 if other_kernel ~= nil then
561                         kernel = other_kernel
562                 end
563                 -- first try load kernel with module_path = /boot/${kernel}
564                 -- then try load with module_path=${kernel}
565                 local paths = {"/boot/" .. kernel, kernel}
566
567                 for _, v in pairs(paths) do
568                         loader.setenv("module_path", v)
569                         res = loadBootfile()
570
571                         -- succeeded, add path to module_path
572                         if res ~= nil then
573                                 config.kernel_loaded = kernel
574                                 if module_path ~= nil then
575                                         loader.setenv("module_path", v .. ";" ..
576                                             module_path)
577                                         loader.setenv("kernel_path", v)
578                                 end
579                                 return true
580                         end
581                 end
582
583                 -- failed to load with ${kernel} as a directory
584                 -- try as a file
585                 res = tryLoad(kernel)
586                 if res ~= nil then
587                         config.kernel_loaded = kernel
588                         return true
589                 else
590                         print(MSG_KERNFAIL:format(kernel))
591                         return false
592                 end
593         end
594 end
595
596 function config.selectKernel(kernel)
597         config.kernel_selected = kernel
598 end
599
600 function config.load(file, reloading)
601         if not file then
602                 file = "/boot/defaults/loader.conf"
603         end
604
605         if not config.processFile(file) then
606                 print(MSG_FAILPARSECFG:format(file))
607         end
608
609         local loaded_files = {file = true}
610         config.readConfFiles(loader.getenv("loader_conf_files"), loaded_files)
611
612         checkNextboot()
613
614         local verbose = loader.getenv("verbose_loading") or "no"
615         config.verbose = verbose:lower() == "yes"
616         if not reloading then
617                 hook.runAll("config.loaded")
618         end
619 end
620
621 -- Reload configuration
622 function config.reload(file)
623         modules = {}
624         restoreEnv()
625         config.load(file, true)
626         hook.runAll("config.reloaded")
627 end
628
629 function config.loadelf()
630         local xen_kernel = loader.getenv('xen_kernel')
631         local kernel = config.kernel_selected or config.kernel_loaded
632         local status
633
634         if xen_kernel ~= nil then
635                 print(MSG_XENKERNLOADING)
636                 if cli_execute_unparsed('load ' .. xen_kernel) ~= 0 then
637                         print(MSG_XENKERNFAIL:format(xen_kernel))
638                         return false
639                 end
640         end
641         print(MSG_KERNLOADING)
642         if not config.loadKernel(kernel) then
643                 return false
644         end
645         hook.runAll("kernel.loaded")
646
647         print(MSG_MODLOADING)
648         status = loadModule(modules, not config.verbose)
649         hook.runAll("modules.loaded")
650         return status
651 end
652
653 hook.registerType("config.loaded")
654 hook.registerType("config.reloaded")
655 hook.registerType("kernel.loaded")
656 hook.registerType("modules.loaded")
657 return config