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