diff --git a/board/common/rootfs/etc/finit.d/available/ptp4l@.conf b/board/common/rootfs/etc/finit.d/available/ptp4l@.conf index caf4d7c2c3..9e8ab9732d 100644 --- a/board/common/rootfs/etc/finit.d/available/ptp4l@.conf +++ b/board/common/rootfs/etc/finit.d/available/ptp4l@.conf @@ -1,3 +1,3 @@ -service name:ptp4l :%i log:prio:daemon,tag:ptp4l-%i \ - [2345] ptp4l -f /etc/linuxptp/ptp4l-%i.conf \ +service name:ptp4l :%i log:prio:daemon,tag:ptp4l-%i env:-/etc/default/ptp4l \ + [2345] ptp4l -f /etc/linuxptp/ptp4l-%i.conf $PTP4L_ARGS \ -- PTP instance %i diff --git a/board/common/rootfs/usr/bin/askline b/board/common/rootfs/usr/bin/askline new file mode 100755 index 0000000000..7420b0d747 --- /dev/null +++ b/board/common/rootfs/usr/bin/askline @@ -0,0 +1,16 @@ +#!/bin/sh +# Prompt for a single-line value, prefilled with the current one. +# +# askline LABEL FILE +# +# FILE holds the current value on entry and the new value on exit. +# shellcheck disable=SC3045 + +LABEL=$1 +FILE=$2 + +current=$(cat "$FILE" 2>/dev/null) +read -er -p "$LABEL> " -i "$current" value || exit 1 + +umask 0177 +printf '%s' "$value" > "$FILE" diff --git a/board/common/rootfs/usr/bin/datetime b/board/common/rootfs/usr/bin/datetime new file mode 100755 index 0000000000..8d5481a29b --- /dev/null +++ b/board/common/rootfs/usr/bin/datetime @@ -0,0 +1,62 @@ +#!/bin/sh +# Set system date and time via the set-current-datetime RPC. +# +# datetime [-e] [VALUE] +# +# With -e the current time is offered for editing in a prompt. VALUE +# is converted to the ISO-8601 format required by the RPC, and the +# result is echoed before setting so mistakes are easy to spot. + +usage() +{ + cat >&2 < "$tmp" + if ! askline datetime "$tmp"; then + rm -f "$tmp" + exit 1 + fi + value=$(cat "$tmp") + rm -f "$tmp" +fi +[ -n "$value" ] || usage + +case $value in + [0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9]Z | \ + [0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9][+-][0-9][0-9]:[0-9][0-9]) + iso=$value + ;; + *) + # Let date(1) parse anything else as local time, it does not + # know the ISO-8601 'T' separator. + plain=$(printf '%s' "$value" | sed 's/T/ /') + if ! iso=$(date -d "$plain" -Isec 2>/dev/null); then + echo "Cannot parse '$value'" >&2 + usage + fi + ;; +esac + +echo "Setting datetime $iso" +exec rpc /ietf-system:set-current-datetime current-datetime "$iso" diff --git a/doc/ChangeLog.md b/doc/ChangeLog.md index f74ba7b649..6b0e02f8bf 100644 --- a/doc/ChangeLog.md +++ b/doc/ChangeLog.md @@ -13,6 +13,25 @@ All notable changes to the project are documented in this file. - Add per-server `minpoll` and `maxpoll` options to the NTP client configuration, for tuning how often each server is polled +### Added + +- Add `/system/advanced` for low-level system customization, issue #463: + - `rc.d`: user scripts stored in the configuration, run once at boot + after the startup configuration has been applied, in the order listed + - `default`: daemon environment files written to `/etc/default`, e.g., + extra `ptp4l` command line options +- The CLI `edit` command now also edits settings interactively: passwords + and keys are prompted for, `binary` settings open in the text editor, and + `string` settings are edited on a line prefilled with the current value. + The `text-editor` and `change` commands are removed +- Add CLI `edit` and `clear` verbs to admin-exec: `edit datetime` and + `edit boot-order` prompt with the current value, `clear dhcp-server + statistics` replaces `dhcp-server clear-statistics`. `set datetime` now + also accepts free-form input, e.g., `14:05`, and echoes the ISO-8601 + value it sets +- The CLI `configure` command takes an optional path to start in a + sub-context directly, e.g., `configure system authentication` + [v26.08.0][] - 2026-09-01 ------------------------- diff --git a/doc/cli/configure.md b/doc/cli/configure.md index b8300af453..5d3e997f82 100644 --- a/doc/cli/configure.md +++ b/doc/cli/configure.md @@ -13,7 +13,7 @@ admin@host:/config/> delete Delete configuration setting(s) diff Summarize uncommitted changes do Execute operational mode command - edit Descend to the specified configuration node + edit Descend to configuration node, or edit a setting interactively end Alias to up, leave this subsection/node exit Ascend to the parent configuration node, or abort (from top) leave Finalize candidate and apply to running-config @@ -21,7 +21,6 @@ admin@host:/config/> rollback Restore candidate to running-config set Set configuration setting show Show configuration - text-editor Modify binary content in a text editor top Ascend to the configuration root up Ascend to the parent configuration node ``` @@ -179,8 +178,7 @@ admin@host:/config/system/authentication/user/admin/authorized-key/example@host/ > **Note** > > The `ssh-keygen` program already base64 encodes the public key data, -> so there is no need to use the `text-editor` command, `set` does the -> job. +> so there is no need to use the `edit` command, `set` does the job. ---- diff --git a/doc/cli/text-editor.md b/doc/cli/edit.md similarity index 76% rename from doc/cli/text-editor.md rename to doc/cli/edit.md index a07d9585ca..f1ee1b2e9a 100644 --- a/doc/cli/text-editor.md +++ b/doc/cli/edit.md @@ -1,7 +1,16 @@ -# Text Editor +# Edit Command -The CLI built-in `text-editor` command can be used to edit type `binary` -settings in configure context. +In configure context, `edit` descends into a container or list entry, +e.g., `edit interface eth0`. Used on a setting it instead modifies the +current value interactively, depending on the type of setting: + + - passwords and keys: prompt without echo, with confirmation + - `binary` settings: open the built-in text editor, e.g., `edit content` + in a boot script, or `edit motd-banner` + - `string` settings: prompt on a single line prefilled with the current + value, use the arrow keys to move around and Enter to accept + +Other types are set with `set`. The default editor is a Micro Emacs clone. Users not familiar with terminal based editors may benefit from this introduction. diff --git a/doc/cli/introduction.md b/doc/cli/introduction.md index aeb7f0652e..a11f058615 100644 --- a/doc/cli/introduction.md +++ b/doc/cli/introduction.md @@ -51,9 +51,11 @@ Available commands can be seen by pressing `?` at the prompt: ``` admin@host:/> + clear Clear runtime state, e.g., statistics configure Create new candidate-config based on running-config copy Copy file or configuration, e.g., copy running-config startup-config dir List available configuration files + edit Edit system state interactively, e.g., current date/time exit Exit from CLI (log out) factory-reset Restore the system to factory default state follow Monitor a log file, use Ctrl-C to abort @@ -96,6 +98,9 @@ admin@host-12-34-56:/config/> ... # Try: Tab or ? admin@host-12-34-56:/config/> leave ``` +The `configure` command also takes an optional path, to start out in a +sub-context directly, e.g., `configure system authentication`. + The `leave` command activates the changes by issuing a transaction to, essentially, copy the *candidate* back to *running*. Depending on the changes made, this can take a few seconds. If the changes are invalid, @@ -119,8 +124,8 @@ In *configure context* the following commands are available: | `set foo bar val` | Set `bar` leaf node in `foo` subcontext to `val` | | `no foo bar` | Clear/delete configuration made to `bar` in `foo` | | `edit foo baz` | Enter `baz` sub-sub-context in `foo` subcontext | -| `change password` | Start password dialogue to change a user's password | -| `text-editor foo` | Open a text editor to edit binary setting `foo` | +| `edit password` | Start password dialogue to change a user's password | +| `edit foo` | Edit setting `foo` interactively, see `help edit` | | `abort` | Abort changes in configuration, return to admin-exec | | `exit` | Exit one level sub-context, or abort from top-level | | `leave` | Save changes to `running-config`, return to admin-exec | diff --git a/doc/cli/quick.md b/doc/cli/quick.md index 4762b3c06b..067db66a9c 100644 --- a/doc/cli/quick.md +++ b/doc/cli/quick.md @@ -20,11 +20,11 @@ keybindings are really useful to learn! |---------------------|----------------------------------------------------| | `help introduction` | An introduction to the CLI | | `help configure` | How to use configure context | -| `help text-editor` | Help with the built-in text-editor command | +| `help edit` | Editing settings interactively, incl. text editor | | `help keybindings` | Lists available keybindings & other helpful tricks | > **Tip:** Online Help > > In `configure` context the `help ` command shows the YANG > description text for each node and container. To reach the admin -> exec help from configure context, e.g., `do help text-editor` +> exec help from configure context, e.g., `do help edit` diff --git a/doc/container.md b/doc/container.md index 4f3ab2d78b..9e9178e38a 100644 --- a/doc/container.md +++ b/doc/container.md @@ -871,7 +871,7 @@ its `startup-config` (or even `factory-config`) a temporary file is created using the decoded base64 data from the `content` node.
admin@example:/config/container/ntpd/> edit mount ntpd.conf
-admin@example:/config/container/ntpd/mount/ntpd.conf> text-editor content
+admin@example:/config/container/ntpd/mount/ntpd.conf> edit content
 ... interactive editor starts up ...
 admin@example:/config/container/ntpd/mount/ntpd.conf> set target /etc/ntpd.conf
 admin@example:/config/container/ntpd/mount/ntpd.conf> end
@@ -888,7 +888,7 @@ the contents are base64 encoded and stored in the candidate datastore.
 > host's startup-config.
 
 Infix has three different text editors available.  For more information,
-see [CLI Text Editor](cli/text-editor.md).
+see the [CLI edit command](cli/edit.md).
 
 
 Example Containers
@@ -975,7 +975,7 @@ admin@example:/config/container/nftables/> set network host
 admin@example:/config/container/nftables/> set privileged
 admin@example:/config/container/nftables/> edit mount nftables.conf
 admin@example:/config/…/mount/nftables.conf/> set target /etc/nftables.conf
-admin@example:/config/…/mount/nftables.conf/> text-editor content
+admin@example:/config/…/mount/nftables.conf/> edit content
 ... interactive editor starts up where you can paste your rules ...
 admin@example:/config/…/mount/nftables.conf/> leave
 
@@ -1003,7 +1003,7 @@ admin@example:/config/container/ntpd/> set image ghcr.io/kernelkit/curios-ntp admin@example:/config/container/ntpd/> set network interface ntpd # From veth0 above admin@example:/config/container/ntpd/> edit mount ntp.conf admin@example:/config/container/ntpd/mount/ntp.conf/> set target /etc/ntp.conf -admin@example:/config/container/ntpd/mount/ntp.conf/> text-editor content +admin@example:/config/container/ntpd/mount/ntp.conf/> edit content ... interactive editor starts up where you can paste your rules ... admin@example:/config/container/ntpd/mount/ntp.conf/> end admin@example:/config/container/ntpd/> edit volume varlib diff --git a/doc/scripting-sysrepocfg.md b/doc/scripting-sysrepocfg.md index ca58e934da..82c56e8910 100644 --- a/doc/scripting-sysrepocfg.md +++ b/doc/scripting-sysrepocfg.md @@ -263,9 +263,9 @@ on interface *e0*. A YANG `binary` type setting is Base64 encoded and requires a little bit more tricks. We take the opportunity to showcase a shell script helper: -`/usr/bin/text-editor`, which works just like the `text-editor` command -in the CLI, but this one takes an XPath argument to the binary leaf to -edit. +`/usr/bin/text-editor`, which works just like the `edit` command in the +CLI does for a `binary` setting, but this one takes an XPath argument to +the leaf to edit. Stripped down, it looks something like this: diff --git a/doc/system.md b/doc/system.md index 4407ac863b..1d9aa84a67 100644 --- a/doc/system.md +++ b/doc/system.md @@ -67,8 +67,7 @@ admin@example:/config/system/…/example@host/> leave > [!NOTE] > The `ssh-keygen` program already base64 encodes the public key data, -> so there is no need to use the `text-editor` command, `set` does the -> job. +> so there is no need to use the `edit` command, `set` does the job. ## Multiple Users @@ -394,15 +393,15 @@ to clients, it is up to the clients to request the domain name *option*. ## Changing Login Banner The `motd-banner` setting is an Infix augment and an example of a -`binary` type setting that can be changed interactively with the -built-in [`text-editor` command](cli/text-editor.md). +`binary` type setting that is changed interactively with the built-in +[`edit` command](cli/edit.md). > [!TIP] > See the next section for how to change the editor used to something > you may be more familiar with.
admin@example:/config/> edit system
-admin@example:/config/system/> text-editor motd-banner
+admin@example:/config/system/> edit motd-banner
 admin@example:/config/system/> leave
 admin@example:/>
 
@@ -413,7 +412,7 @@ Log out and log back in again to inspect the changes. ## Changing the Editor The system has three different built-in editors that can be used -as the `text-editor` command: +by the `edit` command: - `emacs` (Micro Emacs) - `nano` (GNU Nano) @@ -546,6 +545,74 @@ reference ID, stratum, time offsets, frequency, and root delay. > The system uses `chronyd` Network Time Protocol (NTP) daemon. The > output shown here is best explained in the [Chrony documentation][4]. +## Boot Scripts + +For debugging and development it is sometimes useful to run a custom +script every time the system boots, e.g., to put a hardware component +in test mode, or to start a data collector for a transient problem. +Such scripts can be stored in the configuration under +`/system/advanced/rc.ds`, so that everything that runs on the system can +be traced back to the `startup-config`. + +Scripts are run once at boot, as `root`, one at a time, in the order +listed, after the startup configuration has been applied. A script +without a `#!` interpreter line is run by `/bin/sh`. Output and exit +status are logged to the system log, see `show log`. Changes to the +scripts only take effect at the next boot. + +> [!TIP] +> Individual scripts can be disabled, e.g., to keep a script around +> without running it. + +The script contents is a `binary` type setting, so like the [login +banner](#changing-login-banner) it is edited with the built-in +[`edit` command](cli/edit.md): + +
admin@example:/> configure
+admin@example:/config/> edit system advanced rc.d phy-test
+admin@example:/config/system/advanced/rc.d/phy-test/> set description "Put PHY in test mode"
+admin@example:/config/system/advanced/rc.d/phy-test/> edit content
+admin@example:/config/system/advanced/rc.d/phy-test/> leave
+admin@example:/> copy running-config startup-config
+admin@example:/> reboot
+
+ +> [!NOTE] +> The CLI has no command to reorder scripts. A new script is always +> added last, so to change the order, delete a script and add it again. +> Alternatively, edit `/cfg/startup-config.cfg` from a shell and +> reboot. The WebUI supports reordering scripts by drag-and-drop. + + +## Daemon Default Files + +Most system daemons source an environment file, `/etc/default/NAME`, +at startup for extra command line options, e.g., `PTP4L_ARGS` in +`/etc/default/ptp4l`. Such files can be stored in the configuration +under `/system/advanced/defaults`, to tune daemon behavior beyond what +the rest of the configuration exposes. For example, to force PTP minor +version 0 for a NIC that does not support anything else: + +
admin@example:/> configure
+admin@example:/config/> edit system advanced default ptp4l
+admin@example:/config/system/advanced/default/ptp4l/> set description "Intel NIC only speaks PTP v2.0"
+admin@example:/config/system/advanced/default/ptp4l/> edit content
+... enter PTP4L_ARGS="--ptp_minor_version 0" and save ...
+admin@example:/config/system/advanced/default/ptp4l/> leave
+
+ +The file is written when the configuration is activated, and a system +service with the same name is restarted if its environment changed. A +file that shadows one shipped with the system is restored when the +entry is disabled or removed. + +> [!WARNING] +> These files are applied as-is. A bad setting can prevent a daemon +> from starting, and the configuration may then be lost at next boot if +> the system falls back to its fail-secure mode. Always test with +> `copy running-config startup-config` deferred until verified. + + [1]: https://www.rfc-editor.org/rfc/rfc7317 [2]: https://github.com/kernelkit/infix/blob/main/src/confd/yang/infix-system%402024-02-29.yang [3]: https://www.rfc-editor.org/rfc/rfc8341 diff --git a/package/confd/confd.mk b/package/confd/confd.mk index 3ab017da3a..53d2eed89b 100644 --- a/package/confd/confd.mk +++ b/package/confd/confd.mk @@ -51,10 +51,10 @@ else CONFD_CONF_OPTS += --disable-webui endif define CONFD_INSTALL_EXTRA - for fn in confd.conf crond.conf resolvconf.conf; do \ + for fn in confd.conf crond.conf rcd.conf resolvconf.conf; do \ cp $(CONFD_PKGDIR)/$$fn $(FINIT_D)/available/; \ done - for fn in confd.conf resolvconf.conf; do \ + for fn in confd.conf rcd.conf resolvconf.conf; do \ ln -sf ../available/$$fn $(FINIT_D)/enabled/$$fn; \ done cp $(CONFD_PKGDIR)/tmpfiles.conf $(TARGET_DIR)/etc/tmpfiles.d/confd.conf diff --git a/package/confd/rcd.conf b/package/confd/rcd.conf new file mode 100644 index 0000000000..6c99298a95 --- /dev/null +++ b/package/confd/rcd.conf @@ -0,0 +1,4 @@ +# Run user scripts from /etc/rc.d once at boot, after the startup +# configuration has been applied, see /system/advanced/rc.d +task [2345] name:rcd log \ + /usr/libexec/finit/runparts -bp /etc/rc.d -- Running rc.d scripts diff --git a/package/klish-plugin-sysrepo/klish-plugin-sysrepo.hash b/package/klish-plugin-sysrepo/klish-plugin-sysrepo.hash index c652e519d0..087f9c342f 100644 --- a/package/klish-plugin-sysrepo/klish-plugin-sysrepo.hash +++ b/package/klish-plugin-sysrepo/klish-plugin-sysrepo.hash @@ -1,3 +1,3 @@ # Locally calculated sha256 9d9d33b873917ca5d0bdcc47a36d2fd385971ab0c045d1472fcadf95ee5bcf5b LICENCE -sha256 7bfdaef838ee8bd3995140c40144abe79ff1c6391c7b48445e6728cd4e7e56a8 klish-plugin-sysrepo-2f14503c7ea6eb24c8adaf0cf2cf7a511114b09e-git4.tar.gz +sha256 0c07cb330a9f3855eefe9f9fa0d9f91d921cbf369571e943ab9ac264cd281db0 klish-plugin-sysrepo-3b4e69780e64f0b8f42dc3784defe72285911ad4-git4.tar.gz diff --git a/package/klish-plugin-sysrepo/klish-plugin-sysrepo.mk b/package/klish-plugin-sysrepo/klish-plugin-sysrepo.mk index 488407fffc..ec4ece5a0b 100644 --- a/package/klish-plugin-sysrepo/klish-plugin-sysrepo.mk +++ b/package/klish-plugin-sysrepo/klish-plugin-sysrepo.mk @@ -4,10 +4,8 @@ # ################################################################################ -KLISH_PLUGIN_SYSREPO_VERSION = 2f14503c7ea6eb24c8adaf0cf2cf7a511114b09e +KLISH_PLUGIN_SYSREPO_VERSION = 3b4e69780e64f0b8f42dc3784defe72285911ad4 KLISH_PLUGIN_SYSREPO_SITE = https://github.com/kernelkit/klish-plugin-sysrepo.git -#KLISH_PLUGIN_SYSREPO_VERSION = cdd3eb51a7f7ee0ed5bd925fa636061d3b1b85fb -#KLISH_PLUGIN_SYSREPO_SITE = https://src.libcode.org/pkun/klish-plugin-sysrepo.git KLISH_PLUGIN_SYSREPO_SITE_METHOD = git KLISH_PLUGIN_SYSREPO_LICENSE = BSD-3 KLISH_PLUGIN_SYSREPO_LICENSE_FILES = LICENCE diff --git a/src/confd/src/main.c b/src/confd/src/main.c index 789f19fe6d..77d63ffee3 100644 --- a/src/confd/src/main.c +++ b/src/confd/src/main.c @@ -599,7 +599,7 @@ static int bootstrap_config(sr_conn_ctx_t *conn, sr_session_ctx_t *sess, NOTE("Loading %s ...", config_path); if (load_config(conn, sess, config_path, timeout_ms)) { handle_startup_failure(sess, failure_path, conn, timeout_ms); - return 0; /* continue running even in fail-secure */ + return 1; /* fail-secure, keep running */ } NOTE("Loaded %s successfully, syncing startup datastore.", config_path); @@ -847,14 +847,18 @@ int main(int argc, char **argv) * sr_replace_config() will trigger their change callbacks. * The event pump process processes those callbacks. */ conout(3, "Loading startup-config"); - if (bootstrap_config(conn, sess, factory_path, startup_path, - failure_path, test_path, timeout_ms)) { + r = bootstrap_config(conn, sess, factory_path, startup_path, + failure_path, test_path, timeout_ms); + if (r < 0) { kill(pump_pid, SIGTERM); waitpid(pump_pid, NULL, 0); conout(1, NULL); goto cleanup; } - conout(0, NULL); + if (r > 0) + conout(2, "Failed loading startup-config, running failure-config"); + else + conout(0, NULL); /* Phase 11: Stop event pump — bootstrap is done */ kill(pump_pid, SIGTERM); diff --git a/src/confd/src/system.c b/src/confd/src/system.c index 5bb7a0dd28..0635bf1abf 100644 --- a/src/confd/src/system.c +++ b/src/confd/src/system.c @@ -3,6 +3,7 @@ #include #include #include +#include #include #include #include @@ -31,6 +32,11 @@ #define XPATH_MOTD_BANNER_ XPATH_BASE_"/infix-system:motd-banner" #define XPATH_MOTD_ XPATH_BASE_"/infix-system:motd" #define XPATH_EDITOR_ XPATH_BASE_"/infix-system:text-editor" +#define XPATH_RCD_ XPATH_BASE_"/infix-system:advanced/rc.ds" +#define RCD_DIR "/etc/rc.d" +#define XPATH_DEFAULT_ XPATH_BASE_"/infix-system:advanced/defaults" +#define DEFAULT_DIR "/etc/default" +#define DEFAULT_ORIG "/run/confd/default" #define CLOCK_PATH_ "/ietf-system:system-state/clock" #define PLATFORM_PATH_ "/ietf-system:system-state/platform" #define PASSWORD_PATH "/ietf-system:system/authentication/user/password" @@ -1488,6 +1494,194 @@ static int change_motd_banner(sr_session_ctx_t *session, struct lyd_node *config return SR_ERR_OK; } +/* /etc/rc.d is only ever populated from the running configuration, see issue #463 */ +static int rcd_reset(void) +{ + rmrf(RCD_DIR); + if (mkpath(RCD_DIR, 0755)) { + ERRNO("failed creating %s", RCD_DIR); + return -1; + } + + return 0; +} + +/* Decode base64 data to file fn, created with mode */ +static int write_binary(const char *fn, mode_t mode, const char *what, const char *data) +{ + unsigned char *txt; + size_t len, pos; + int fd, rc = -1; + + txt = base64_decode((const unsigned char *)data, strlen(data), &len); + if (!txt) { + ERROR("failed base64 decoding of %s", what); + return -1; + } + + fd = open(fn, O_CREAT | O_WRONLY | O_TRUNC, mode); + if (fd < 0) { + ERRNO("failed creating %s", fn); + goto done; + } + + for (pos = 0; pos < len;) { + ssize_t n = write(fd, txt + pos, len - pos); + + if (n < 0) { + if (errno == EINTR) + continue; + ERRNO("failed writing %s", fn); + close(fd); + goto done; + } + pos += n; + } + + rc = close(fd); +done: + free(txt); + return rc; +} + +static int rcd_write(int num, const char *name, const char *data) +{ + char fn[sizeof(RCD_DIR) + strlen(name) + 8]; + + snprintf(fn, sizeof(fn), "%s/%02d-%s", RCD_DIR, num, name); + return write_binary(fn, 0700, name, data); +} + +static int change_rc_d(sr_session_ctx_t *session, struct lyd_node *config, struct lyd_node *diff, sr_event_t event, struct confd *confd) +{ + struct lyd_node *rcd, *script; + int num = 0, installed = 0; + + if (event != SR_EV_DONE || !lydx_get_xpathf(diff, XPATH_RCD_)) + return SR_ERR_OK; + + if (rcd_reset()) + return SR_ERR_SYS; + + rcd = lydx_get_xpathf(config, XPATH_RCD_); + if (!rcd) + return SR_ERR_OK; + + LYX_LIST_FOR_EACH(lyd_child(rcd), script, "rc.d") { + const char *enabled = lydx_get_cattr(script, "enabled"); + const char *name = lydx_get_cattr(script, "name"); + + num++; + if (enabled && !strcmp(enabled, "false")) + continue; + + if (rcd_write(num, name, lydx_get_cattr(script, "content"))) + return SR_ERR_SYS; + installed++; + } + + NOTE("Installed %d rc.d script(s) in %s, run at next boot", installed, RCD_DIR); + + return SR_ERR_OK; +} + +/* + * Files in /etc/default may shadow ones shipped with the system. The + * original, or an empty marker if there was none, is kept in DEFAULT_ORIG + * for as long as we manage the file, so it can be restored on removal. + */ +static void default_restore(const char *name) +{ + char orig[sizeof(DEFAULT_ORIG) + strlen(name) + 2]; + char fn[sizeof(DEFAULT_DIR) + strlen(name) + 2]; + struct stat st; + + snprintf(orig, sizeof(orig), "%s/%s", DEFAULT_ORIG, name); + snprintf(fn, sizeof(fn), "%s/%s", DEFAULT_DIR, name); + + if (stat(orig, &st)) + return; /* not managed by us */ + + if (st.st_size) { + if (copyfile(orig, fn, 0, 0) <= 0) + ERRNO("failed restoring %s", fn); + } else + erase(fn); + + erase(orig); +} + +static int default_install(const char *name, const char *data) +{ + char orig[sizeof(DEFAULT_ORIG) + strlen(name) + 2]; + char fn[sizeof(DEFAULT_DIR) + strlen(name) + 2]; + + snprintf(orig, sizeof(orig), "%s/%s", DEFAULT_ORIG, name); + snprintf(fn, sizeof(fn), "%s/%s", DEFAULT_DIR, name); + + if (!fexist(orig)) { + if (fexist(fn)) { + if (copyfile(fn, orig, 0, 0) <= 0) { + ERRNO("failed saving original %s", fn); + return -1; + } + } else if (touch(orig)) { + ERRNO("failed creating %s", orig); + return -1; + } + } + + return write_binary(fn, 0644, fn, data); +} + +static int change_default(sr_session_ctx_t *session, struct lyd_node *config, struct lyd_node *diff, sr_event_t event, struct confd *confd) +{ + struct lyd_node *def, *file; + struct dirent **d = NULL; + int i, num; + + if (event != SR_EV_DONE || !lydx_get_xpathf(diff, XPATH_DEFAULT_)) + return SR_ERR_OK; + + if (mkpath(DEFAULT_ORIG, 0755)) { + ERRNO("failed creating %s", DEFAULT_ORIG); + return SR_ERR_SYS; + } + + def = lydx_get_xpathf(config, XPATH_DEFAULT_); + + /* Restore files we manage that are no longer wanted */ + num = scandir(DEFAULT_ORIG, &d, NULL, alphasort); + for (i = 0; i < num; i++) { + const char *name = d[i]->d_name; + struct lyd_node *node = NULL; + + if (name[0] == '.') + continue; + + if (def) + node = lydx_get_xpathf(def, "default[name='%s']", name); + if (!node || !lydx_is_enabled(node, "enabled")) + default_restore(name); + } + while (num-- > 0) + free(d[num]); + free(d); + + if (!def) + return SR_ERR_OK; + + LYX_LIST_FOR_EACH(lyd_child(def), file, "default") { + if (!lydx_is_enabled(file, "enabled")) + continue; + + if (default_install(lydx_get_cattr(file, "name"), lydx_get_cattr(file, "content"))) + return SR_ERR_SYS; + } + + return SR_ERR_OK; +} + static int change_editor(sr_session_ctx_t *session, struct lyd_node *config, struct lyd_node *diff, sr_event_t event, struct confd *confd) { const char *alt = "/etc/alternatives/editor"; @@ -1682,6 +1876,10 @@ int system_change(sr_session_ctx_t *session, struct lyd_node *config, struct lyd return rc; if ((rc = change_motd_banner(session, config, diff, event, confd))) return rc; + if ((rc = change_rc_d(session, config, diff, event, confd))) + return rc; + if ((rc = change_default(session, config, diff, event, confd))) + return rc; if ((rc = change_nacm(session, config, diff, event, confd))) /* Must be called after ietf_system_change_auth, which create the users */ return rc; @@ -1701,6 +1899,7 @@ int system_rpc_init(struct confd *confd) int rc; os_init(); + rcd_reset(); REGISTER_RPC(confd->session, "/ietf-system:system-restart", rpc_exec, "reboot", &confd->sub); REGISTER_RPC(confd->session, "/ietf-system:system-shutdown", rpc_exec, "poweroff", &confd->sub); diff --git a/src/confd/yang/confd.inc b/src/confd/yang/confd.inc index 86286ff302..62ba37b9d0 100644 --- a/src/confd/yang/confd.inc +++ b/src/confd/yang/confd.inc @@ -43,7 +43,7 @@ MODULES=( "infix-firewall-icmp-types@2025-04-26.yang" "infix-meta@2025-12-10.yang" "infix-services@2026-06-17.yang" - "infix-system@2026-09-01.yang" + "infix-system@2026-09-08.yang" "ieee802-ethernet-interface@2025-09-10.yang" "ieee802-ethernet-phy-type@2025-09-10.yang" "infix-ethernet-interface@2026-05-21.yang" diff --git a/src/confd/yang/confd/infix-system.yang b/src/confd/yang/confd/infix-system.yang index 84e6f3d51a..c077b0fae2 100644 --- a/src/confd/yang/confd/infix-system.yang +++ b/src/confd/yang/confd/infix-system.yang @@ -32,6 +32,13 @@ module infix-system { contact "kernelkit@googlegroups.com"; description "Infix augments and deviations to ietf-system."; + revision 2026-09-08 { + description "Add /system/advanced, for low-level system customization: + - rc.ds: user scripts run once at boot, extracted from the + configuration to /etc/rc.d + - defaults: daemon environment files in /etc/default"; + reference "internal"; + } revision 2026-09-01 { description "Add per-server minpoll/maxpoll to NTP client configuration."; reference "internal"; @@ -311,7 +318,7 @@ module infix-system { Instead, use 'motd-banner', which takes a base64 encoded text file as an argument. For CLI users, edit with the - 'text-editor motd-banner' command."; + 'edit motd-banner' command."; status obsolete; // Replaced with motd-banner (binary) type string; } @@ -330,7 +337,7 @@ module infix-system { } leaf text-editor { - description "Text editor to use in CLI for text-editor command."; + description "Text editor to use in CLI when editing binary settings."; type identityref { base editor-type; } @@ -355,6 +362,160 @@ module infix-system { } } + augment "/sys:system" { + description "Advanced, low-level system customization."; + container advanced { + description "Advanced system customization, for debugging and development. + + Settings in this container reach below the abstractions of the + rest of the configuration and are applied as-is by the system. + + Use with care!"; + + container rc.ds { + description "Scripts run once at boot, in the order listed. + + Scripts are extracted to /etc/rc.d and run as root, one at a time, + at the end of system bootstrap, after the startup configuration has + been applied. A script without a '#!' interpreter line is run by + /bin/sh. Output and exit status are logged to the system log. + + Changes take effect at the next boot."; + + list rc.d { + key name; + ordered-by user; + description "Script to run at boot, in the order listed."; + + leaf name { + type string { + length "1..64"; + pattern '[a-zA-Z0-9_][a-zA-Z0-9_.-]*'; + } + description "Script name, also used for the file in /etc/rc.d. + + The list order determines the run order, all script names are + prefixed with a unique sequence number to ensure the order."; + } + + leaf description { + type string; + description "Free-form description of what the script does."; + } + + leaf enabled { + type boolean; + default true; + description "Run this script at boot. + + Disable to keep the script in the configuration without running it."; + } + + leaf content { + type binary; + mandatory true; + description "Script contents, base64 encoded. + + In the CLI, use 'edit content' in the script context to edit + it as plain text."; + } + } + } + + container defaults { + description "Environment files for system daemons, written to /etc/default. + + Most daemons source /etc/default/NAME at startup for extra command + line options, e.g., PTP4L_ARGS in /etc/default/ptp4l. This allows + tuning daemon behavior beyond what the rest of the configuration + exposes. + + Files are written as-is when the configuration is activated, and a + system service with the same name, if any, is restarted. A file + that shadows one shipped with the system is restored when the + entry is disabled or removed."; + + list default { + key name; + description "File in /etc/default, keyed by file name."; + + leaf name { + type string { + length "1..64"; + pattern '[a-zA-Z0-9_][a-zA-Z0-9_.-]*'; + } + description "File name in /etc/default, usually the daemon name."; + } + + leaf description { + type string; + description "Free-form description of what the file changes."; + } + + leaf enabled { + type boolean; + default true; + description "Install this file in /etc/default. + + Disable to keep the file in the configuration without installing it."; + } + + leaf content { + type binary; + mandatory true; + description "File contents, base64 encoded, typically NAME_ARGS=\"...\" assignments. + + In the CLI, use 'edit content' in the file context to edit it + as plain text."; + } + } + } + } + } + + /* + * Deferred: per-script result of the most recent boot. Requires + * runparts, or a wrapper, to record per-script exit status. + * + * augment "/sys:system-state" { + * container advanced { + * config false; + * container rc.d { + * list script { + * key name; + * leaf name { + * type string; + * } + * leaf status { + * type enumeration { + * enum ok { + * description "Script exited with status zero."; + * } + * enum failed { + * description "Script exited non-zero or was killed by a signal."; + * } + * enum pending { + * description "Configured but not yet run, takes effect at next boot."; + * } + * } + * } + * leaf exit-status { + * type uint8; + * description "Exit status, 128 + signal number if killed by a signal."; + * } + * leaf started { + * type yang:date-and-time; + * } + * leaf duration { + * type uint32; + * units "milliseconds"; + * } + * } + * } + * } + * } + */ + augment "/sys:system/sys:ntp" { leaf stratum-weight { type decimal64 { diff --git a/src/confd/yang/confd/infix-system@2026-09-01.yang b/src/confd/yang/confd/infix-system@2026-09-08.yang similarity index 100% rename from src/confd/yang/confd/infix-system@2026-09-01.yang rename to src/confd/yang/confd/infix-system@2026-09-08.yang diff --git a/src/klish-plugin-infix/xml/infix.xml b/src/klish-plugin-infix/xml/infix.xml index 99f6f88937..60b8f670ae 100644 --- a/src/klish-plugin-infix/xml/infix.xml +++ b/src/klish-plugin-infix/xml/infix.xml @@ -19,6 +19,8 @@ HidePasswords = n EnableNACM = y Oneliners = n + Secret.1 = /ietf-system:system/authentication/user/password + Secret.2 = /ietf-keystore:keystore/symmetric-keys/symmetric-key/cleartext-symmetric-key @@ -205,12 +207,12 @@ configure + edit introduction keybindings netcalc quick tcpdump - text-editor upgrade @@ -240,8 +242,10 @@ pop - - replace config + + + configure + replace config @@ -314,9 +318,9 @@ echo "Public: $pub" - - - /ietf-system:set-current-datetime + + + datetime "$KLISH_PARAM_datetime" @@ -336,9 +340,41 @@ echo "Public: $pub" - - - /infix-dhcp-server:dhcp-server/statistics/clear + + + + datetime -e + + + + + tmp=$(mktemp) || exit 1 + show boot-order > "$tmp" + if ! askline boot-order "$tmp"; then + rm -f "$tmp" + exit 1 + fi + set -- $(cat "$tmp") + rm -f "$tmp" + [ $# -gt 0 ] || exit 1 + args="" + for target in "$@"; do + args="$args boot-order $target" + done + echo "Setting boot order $*" + rpc /infix-system:set-boot-order $args + + + + + + + + + /infix-dhcp-server:dhcp-server/statistics/clear + @@ -1044,23 +1080,14 @@ echo "Public: $pub" - + + edit - - - - - - - - - - diff --git a/src/webui/internal/handlers/configure_advanced.go b/src/webui/internal/handlers/configure_advanced.go new file mode 100644 index 0000000000..0f01e4e1b0 --- /dev/null +++ b/src/webui/internal/handlers/configure_advanced.go @@ -0,0 +1,454 @@ +// SPDX-License-Identifier: MIT + +package handlers + +import ( + "context" + "fmt" + "html/template" + "log" + "net/http" + "strings" + + "infix/webui/internal/restconf" + "infix/webui/internal/schema" +) + +// ─── RESTCONF JSON types (candidate datastore) ──────────────────────────────── + +// cfgAdvancedWrapper models /ietf-system:system down to the infix-system +// advanced container; everything else in system is ignored on decode. +type cfgAdvancedWrapper struct { + System struct { + Advanced cfgAdvancedJSON `json:"infix-system:advanced"` + } `json:"ietf-system:system"` +} + +type cfgAdvancedJSON struct { + RCD cfgRCDJSON `json:"rc.ds"` + Default cfgDefaultJSON `json:"defaults"` +} + +// cfgRCDJSON is the rc.ds container; the rc.d list is ordered-by user. +type cfgRCDJSON struct { + Scripts []cfgAdvEntryJSON `json:"rc.d,omitempty"` +} + +// cfgDefaultJSON is the defaults container; the default list is keyed by name only. +type cfgDefaultJSON struct { + Files []cfgAdvEntryJSON `json:"default,omitempty"` +} + +// cfgAdvEntryJSON is one rc.d script or one /etc/default file; both lists +// share the same leaves. Enabled is a pointer so an unset leaf stays unset +// when an entry is written back. +type cfgAdvEntryJSON struct { + Name string `json:"name"` + Description string `json:"description,omitempty"` + Enabled *bool `json:"enabled,omitempty"` + Content []byte `json:"content"` // YANG binary, base64 on the wire +} + +// ─── Template data ──────────────────────────────────────────────────────────── + +type cfgAdvEntryView struct { + Name string + Description string + Enabled bool + Content string // decoded text +} + +type cfgAdvancedPageData struct { + PageData + Loading bool // true while YANG schema is still downloading + Error string + Scripts []cfgAdvEntryView // list order == execution order + Files []cfgAdvEntryView + Desc map[string]string // leaf name -> YANG description +} + +// ─── Handler ───────────────────────────────────────────────────────────────── + +// ConfigureAdvancedHandler serves the Configure > Advanced page: rc.d boot +// scripts and /etc/default daemon files, backed by the candidate datastore. +type ConfigureAdvancedHandler struct { + Template *template.Template + RC restconf.Fetcher + Schema *schema.Cache +} + +const ( + advancedSchemaPath = "/ietf-system:system/infix-system:advanced" + rcdCandPath = candidatePath + advancedSchemaPath + "/rc.ds" + defaultCandPath = candidatePath + advancedSchemaPath + "/defaults" +) + +func rcdScriptCandPath(name string) string { + return rcdCandPath + "/rc.d=" + restconf.EscapeKey(name) +} + +func defaultFileCandPath(name string) string { + return defaultCandPath + "/default=" + restconf.EscapeKey(name) +} + +// loadAdvanced reads the advanced container from the candidate datastore, +// falling back to running when candidate is uninitialised. The whole +// system container is fetched so the response shape is independent of how +// deep GETs are nested by the server. +func (h *ConfigureAdvancedHandler) loadAdvanced(ctx context.Context) (cfgAdvancedJSON, error) { + var raw cfgAdvancedWrapper + if err := h.RC.Get(ctx, candidatePath+"/ietf-system:system", &raw); err != nil { + if !restconf.IsNotFound(err) { + return cfgAdvancedJSON{}, err + } + if fallErr := h.RC.Get(ctx, "/data/ietf-system:system", &raw); fallErr != nil && !restconf.IsNotFound(fallErr) { + return cfgAdvancedJSON{}, fallErr + } + } + return raw.System.Advanced, nil +} + +// rewriteRCD applies fn to the current rc.ds container and PUTs the result +// back as a whole. The list is ordered-by user, so replacing the container +// is the only way to make the stored order match exactly what fn produced. +func (h *ConfigureAdvancedHandler) rewriteRCD(ctx context.Context, fn func(*cfgRCDJSON) error) error { + adv, err := h.loadAdvanced(ctx) + if err != nil { + return err + } + rcd := adv.RCD + if err := fn(&rcd); err != nil { + return err + } + return h.RC.Put(ctx, rcdCandPath, map[string]any{"infix-system:rc.ds": rcd}) +} + +func (h *ConfigureAdvancedHandler) render(w http.ResponseWriter, r *http.Request, data any) { + tmplName := "configure-advanced.html" + if r.Header.Get("HX-Request") == "true" { + tmplName = "content" + } + if err := h.Template.ExecuteTemplate(w, tmplName, data); err != nil { + log.Printf("template error: %v", err) + http.Error(w, "Internal server error", http.StatusInternalServerError) + } +} + +func advEntryViews(entries []cfgAdvEntryJSON) []cfgAdvEntryView { + views := make([]cfgAdvEntryView, 0, len(entries)) + for _, e := range entries { + views = append(views, cfgAdvEntryView{ + Name: e.Name, + Description: e.Description, + Enabled: e.Enabled == nil || *e.Enabled, + Content: string(e.Content), + }) + } + return views +} + +// Overview renders the Configure > Advanced page. +// GET /configure/advanced +func (h *ConfigureAdvancedHandler) Overview(w http.ResponseWriter, r *http.Request) { + data := cfgAdvancedPageData{ + PageData: newPageData(w, r, "configure-advanced", "Advanced"), + } + + adv, err := h.loadAdvanced(r.Context()) + if err != nil { + log.Printf("configure advanced: %v", err) + data.Error = "Could not read candidate configuration" + } else { + data.Scripts = advEntryViews(adv.RCD.Scripts) + data.Files = advEntryViews(adv.Default.Files) + } + + mgr := h.Schema.Manager() + data.Loading = mgr == nil + if mgr != nil { + rcdPath := advancedSchemaPath + "/rc.ds" + defPath := advancedSchemaPath + "/defaults" + data.Desc = map[string]string{ + "rc.d": schema.DescriptionOf(mgr, rcdPath), + "name": schema.DescriptionOf(mgr, rcdPath+"/rc.d/name"), + "description": schema.DescriptionOf(mgr, rcdPath+"/rc.d/description"), + "s-enabled": schema.DescriptionOf(mgr, rcdPath+"/rc.d/enabled"), + "content": schema.DescriptionOf(mgr, rcdPath+"/rc.d/content"), + "default": schema.DescriptionOf(mgr, defPath), + "f-name": schema.DescriptionOf(mgr, defPath+"/default/name"), + "f-description": schema.DescriptionOf(mgr, defPath+"/default/description"), + "f-enabled": schema.DescriptionOf(mgr, defPath+"/default/enabled"), + "f-content": schema.DescriptionOf(mgr, defPath+"/default/content"), + } + } + + h.render(w, r, data) +} + +// entryFromForm reads the shared add/edit form fields. Content is plain +// text in the form and becomes the YANG binary leaf as-is; CRLF from the +// textarea is normalised so the file lands on the device unchanged. +func entryFromForm(r *http.Request, name string) (cfgAdvEntryJSON, error) { + content := strings.ReplaceAll(r.FormValue("content"), "\r\n", "\n") + if strings.TrimSpace(content) == "" { + return cfgAdvEntryJSON{}, fmt.Errorf("content is required") + } + enabled := r.FormValue("enabled") == "true" + return cfgAdvEntryJSON{ + Name: name, + Description: strings.TrimSpace(r.FormValue("description")), + Enabled: &enabled, + Content: []byte(content), + }, nil +} + +// ─── rc.d scripts ───────────────────────────────────────────────────────────── + +// AddScript appends a script to the end of the list. +// POST /configure/advanced/rc.d/scripts +func (h *ConfigureAdvancedHandler) AddScript(w http.ResponseWriter, r *http.Request) { + if err := r.ParseForm(); err != nil { + http.Error(w, "bad request", http.StatusBadRequest) + return + } + name := strings.TrimSpace(r.FormValue("name")) + if name == "" { + renderSaveError(w, fmt.Errorf("script name is required")) + return + } + script, err := entryFromForm(r, name) + if err != nil { + renderSaveError(w, err) + return + } + err = h.rewriteRCD(r.Context(), func(rcd *cfgRCDJSON) error { + for _, s := range rcd.Scripts { + if s.Name == name { + return fmt.Errorf("script %q already exists", name) + } + } + rcd.Scripts = append(rcd.Scripts, script) + return nil + }) + if err != nil { + log.Printf("configure advanced add script %q: %v", name, err) + renderSaveError(w, err) + return + } + renderSavedRedirect(w, "Script added", "/configure/advanced") +} + +// SaveScript replaces one script in place, keeping its list position. +// POST /configure/advanced/rc.d/scripts/{name} +func (h *ConfigureAdvancedHandler) SaveScript(w http.ResponseWriter, r *http.Request) { + if err := r.ParseForm(); err != nil { + http.Error(w, "bad request", http.StatusBadRequest) + return + } + name := r.PathValue("name") + script, err := entryFromForm(r, name) + if err != nil { + renderSaveError(w, err) + return + } + err = h.rewriteRCD(r.Context(), func(rcd *cfgRCDJSON) error { + for i := range rcd.Scripts { + if rcd.Scripts[i].Name == name { + rcd.Scripts[i] = script + return nil + } + } + return fmt.Errorf("script %q not found", name) + }) + if err != nil { + log.Printf("configure advanced save script %q: %v", name, err) + renderSaveError(w, err) + return + } + renderSaved(w, "Script saved") +} + +// ToggleScript sets the per-script enabled leaf from the table row checkbox. +// POST /configure/advanced/rc.d/scripts/{name}/enabled +func (h *ConfigureAdvancedHandler) ToggleScript(w http.ResponseWriter, r *http.Request) { + if err := r.ParseForm(); err != nil { + http.Error(w, "bad request", http.StatusBadRequest) + return + } + name := r.PathValue("name") + enabled := r.FormValue("enabled") == "true" + err := h.rewriteRCD(r.Context(), func(rcd *cfgRCDJSON) error { + for i := range rcd.Scripts { + if rcd.Scripts[i].Name == name { + rcd.Scripts[i].Enabled = &enabled + return nil + } + } + return fmt.Errorf("script %q not found", name) + }) + if err != nil { + log.Printf("configure advanced toggle script %q: %v", name, err) + renderSaveError(w, err) + return + } + if enabled { + renderSaved(w, "Script enabled") + } else { + renderSaved(w, "Script disabled") + } +} + +// DeleteScript removes a script. +// DELETE /configure/advanced/rc.d/scripts/{name} +func (h *ConfigureAdvancedHandler) DeleteScript(w http.ResponseWriter, r *http.Request) { + name := r.PathValue("name") + if err := h.RC.Delete(r.Context(), rcdScriptCandPath(name)); err != nil && !restconf.IsNotFound(err) { + log.Printf("configure advanced delete script %q: %v", name, err) + renderSaveError(w, err) + return + } + renderSavedRedirect(w, "Script deleted", "/configure/advanced") +} + +// ReorderScripts rewrites the list in the order given by the repeated +// "order" form value, posted by the drag-and-drop table. The submitted set +// must match the stored set exactly; otherwise nothing is written. +// POST /configure/advanced/rc.d/order +func (h *ConfigureAdvancedHandler) ReorderScripts(w http.ResponseWriter, r *http.Request) { + if err := r.ParseForm(); err != nil { + http.Error(w, "bad request", http.StatusBadRequest) + return + } + order := r.Form["order"] + if len(order) == 0 { + renderSaveError(w, fmt.Errorf("script order is required")) + return + } + err := h.rewriteRCD(r.Context(), func(rcd *cfgRCDJSON) error { + if len(order) != len(rcd.Scripts) { + return fmt.Errorf("script list changed, reload the page") + } + byName := make(map[string]cfgAdvEntryJSON, len(rcd.Scripts)) + for _, s := range rcd.Scripts { + byName[s.Name] = s + } + sorted := make([]cfgAdvEntryJSON, 0, len(order)) + for _, name := range order { + s, ok := byName[name] + if !ok { + return fmt.Errorf("script list changed, reload the page") + } + delete(byName, name) + sorted = append(sorted, s) + } + rcd.Scripts = sorted + return nil + }) + if err != nil { + log.Printf("configure advanced reorder: %v", err) + renderSaveError(w, err) + return + } + renderSaved(w, "Script order saved") +} + +// ─── /etc/default files ─────────────────────────────────────────────────────── + +// The file list is keyed by name only, so each entry is written on its own: +// PUT replaces, PATCH merges a leaf, DELETE removes. + +// AddFile creates a new /etc/default file entry. +// POST /configure/advanced/default/files +func (h *ConfigureAdvancedHandler) AddFile(w http.ResponseWriter, r *http.Request) { + if err := r.ParseForm(); err != nil { + http.Error(w, "bad request", http.StatusBadRequest) + return + } + name := strings.TrimSpace(r.FormValue("name")) + if name == "" { + renderSaveError(w, fmt.Errorf("file name is required")) + return + } + file, err := entryFromForm(r, name) + if err != nil { + renderSaveError(w, err) + return + } + adv, err := h.loadAdvanced(r.Context()) + if err != nil { + log.Printf("configure advanced add file %q: %v", name, err) + renderSaveError(w, err) + return + } + for _, f := range adv.Default.Files { + if f.Name == name { + renderSaveError(w, fmt.Errorf("file %q already exists", name)) + return + } + } + body := map[string]any{"infix-system:default": []cfgAdvEntryJSON{file}} + if err := h.RC.Put(r.Context(), defaultFileCandPath(name), body); err != nil { + log.Printf("configure advanced add file %q: %v", name, err) + renderSaveError(w, err) + return + } + renderSavedRedirect(w, "File added", "/configure/advanced") +} + +// SaveFile replaces one /etc/default file entry. +// POST /configure/advanced/default/files/{name} +func (h *ConfigureAdvancedHandler) SaveFile(w http.ResponseWriter, r *http.Request) { + if err := r.ParseForm(); err != nil { + http.Error(w, "bad request", http.StatusBadRequest) + return + } + name := r.PathValue("name") + file, err := entryFromForm(r, name) + if err != nil { + renderSaveError(w, err) + return + } + body := map[string]any{"infix-system:default": []cfgAdvEntryJSON{file}} + if err := h.RC.Put(r.Context(), defaultFileCandPath(name), body); err != nil { + log.Printf("configure advanced save file %q: %v", name, err) + renderSaveError(w, err) + return + } + renderSaved(w, "File saved") +} + +// ToggleFile merges the enabled leaf of one file entry. +// POST /configure/advanced/default/files/{name}/enabled +func (h *ConfigureAdvancedHandler) ToggleFile(w http.ResponseWriter, r *http.Request) { + if err := r.ParseForm(); err != nil { + http.Error(w, "bad request", http.StatusBadRequest) + return + } + name := r.PathValue("name") + enabled := r.FormValue("enabled") == "true" + body := map[string]any{ + "infix-system:default": []map[string]any{{"name": name, "enabled": enabled}}, + } + if err := h.RC.Patch(r.Context(), defaultFileCandPath(name), body); err != nil { + log.Printf("configure advanced toggle file %q: %v", name, err) + renderSaveError(w, err) + return + } + if enabled { + renderSaved(w, "File enabled") + } else { + renderSaved(w, "File disabled") + } +} + +// DeleteFile removes a file entry. +// DELETE /configure/advanced/default/files/{name} +func (h *ConfigureAdvancedHandler) DeleteFile(w http.ResponseWriter, r *http.Request) { + name := r.PathValue("name") + if err := h.RC.Delete(r.Context(), defaultFileCandPath(name)); err != nil && !restconf.IsNotFound(err) { + log.Printf("configure advanced delete file %q: %v", name, err) + renderSaveError(w, err) + return + } + renderSavedRedirect(w, "File deleted", "/configure/advanced") +} diff --git a/src/webui/internal/handlers/configure_advanced_test.go b/src/webui/internal/handlers/configure_advanced_test.go new file mode 100644 index 0000000000..c0ab3afbe6 --- /dev/null +++ b/src/webui/internal/handlers/configure_advanced_test.go @@ -0,0 +1,458 @@ +// SPDX-License-Identifier: MIT + +package handlers + +import ( + "context" + "encoding/base64" + "encoding/json" + "html/template" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" + + "infix/webui/internal/restconf" + "infix/webui/internal/schema" + "infix/webui/internal/security" + "infix/webui/internal/testutil" +) + +var minimalCfgAdvTmpl = template.Must(template.New("configure-advanced.html").Parse( + `{{define "configure-advanced.html"}}{{template "content" .}}{{end}}` + + `{{define "content"}}n={{len .Scripts}}` + + `{{range .Scripts}};{{.Name}}:{{.Enabled}}:{{.Content}}{{end}}` + + `|files={{len .Files}}{{range .Files}};{{.Name}}:{{.Enabled}}:{{.Content}}{{end}}{{end}}`, +)) + +// advRecorder extends recordingFetcher with PATCH recording. +type advRecorder struct { + *recordingFetcher + patchCalls int + patchPath string + patchBody any +} + +func (r *advRecorder) Patch(_ context.Context, path string, body any) error { + r.patchCalls++ + r.patchPath = path + r.patchBody = body + return nil +} + +func newAdvRecorder() *advRecorder { + return &advRecorder{recordingFetcher: &recordingFetcher{MockFetcher: testutil.NewMockFetcher()}} +} + +func advSystemResponse(scripts, files []map[string]any) map[string]any { + return map[string]any{ + "ietf-system:system": map[string]any{ + "hostname": "test", + "infix-system:advanced": map[string]any{ + "rc.ds": map[string]any{"rc.d": scripts}, + "defaults": map[string]any{"default": files}, + }, + }, + } +} + +func advEntry(name, content string) map[string]any { + return map[string]any{ + "name": name, + "content": base64.StdEncoding.EncodeToString([]byte(content)), + } +} + +func newAdvHandler(t *testing.T, rc restconf.Fetcher) *ConfigureAdvancedHandler { + t.Helper() + return &ConfigureAdvancedHandler{ + Template: minimalCfgAdvTmpl, + RC: rc, + Schema: schema.NewCache(rc, t.TempDir()), + } +} + +func newAdvRequest(t *testing.T, method, target string, form url.Values) *http.Request { + t.Helper() + var req *http.Request + if form != nil { + req = httptest.NewRequest(method, target, strings.NewReader(form.Encode())) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + } else { + req = httptest.NewRequest(method, target, nil) + } + ctx := restconf.ContextWithCredentials(req.Context(), restconf.Credentials{ + Username: "admin", + Password: "admin", + }) + ctx = security.WithToken(ctx, "test-csrf-token") + return req.WithContext(ctx) +} + +// wireJSON re-encodes a recorded request body so tests can inspect the +// exact JSON the datastore would have received. +func wireJSON(t *testing.T, body any) string { + t.Helper() + raw, err := json.Marshal(body) + if err != nil { + t.Fatalf("marshal body: %v", err) + } + return string(raw) +} + +func putRCD(t *testing.T, mock *recordingFetcher) cfgRCDJSON { + t.Helper() + var body struct { + RCD cfgRCDJSON `json:"infix-system:rc.ds"` + } + raw := wireJSON(t, mock.lastBody) + if err := json.Unmarshal([]byte(raw), &body); err != nil { + t.Fatalf("unmarshal PUT body: %v; raw: %s", err, raw) + } + return body.RCD +} + +// ─── rc.d scripts ───────────────────────────────────────────────────────────── + +func TestConfigureAdvancedOverview_ScriptsInOrder(t *testing.T) { + mock := testutil.NewMockFetcher() + mock.SetResponse(candidatePath+"/ietf-system:system", advSystemResponse( + []map[string]any{ + advEntry("10-first", "#!/bin/sh\necho one\n"), + { + "name": "20-second", + "enabled": false, + "content": base64.StdEncoding.EncodeToString([]byte("echo two\n")), + }, + }, nil)) + + w := httptest.NewRecorder() + newAdvHandler(t, mock).Overview(w, newAdvRequest(t, http.MethodGet, "/configure/advanced", nil)) + + if w.Code != http.StatusOK { + t.Fatalf("want 200 got %d; body: %s", w.Code, w.Body.String()) + } + want := "n=2;10-first:true:#!/bin/sh\necho one\n;20-second:false:echo two\n|files=0" + if got := w.Body.String(); got != want { + t.Fatalf("body mismatch\nwant: %q\n got: %q", want, got) + } +} + +func TestConfigureAdvancedAddScript_PutsBase64Content(t *testing.T) { + mock := &recordingFetcher{MockFetcher: testutil.NewMockFetcher()} + mock.SetResponse(candidatePath+"/ietf-system:system", advSystemResponse( + []map[string]any{advEntry("10-first", "echo one\n")}, nil)) + + const script = "#!/bin/sh\r\nlogger -t rc.d hello\r\n" + form := url.Values{ + "name": {"20-hello"}, + "description": {"Say hello"}, + "enabled": {"true"}, + "content": {script}, + } + w := httptest.NewRecorder() + newAdvHandler(t, mock).AddScript(w, newAdvRequest(t, http.MethodPost, "/configure/advanced/rc.d/scripts", form)) + + if w.Code != http.StatusNoContent { + t.Fatalf("want 204 got %d; body: %s", w.Code, w.Body.String()) + } + if mock.putCalls != 1 || mock.lastPath != rcdCandPath { + t.Fatalf("want 1 PUT to %q, got %d call(s) to %q", rcdCandPath, mock.putCalls, mock.lastPath) + } + raw := wireJSON(t, mock.lastBody) + wantB64 := base64.StdEncoding.EncodeToString([]byte("#!/bin/sh\nlogger -t rc.d hello\n")) + if !strings.Contains(raw, `"content":"`+wantB64+`"`) { + t.Fatalf("PUT body missing base64 content %q; raw: %s", wantB64, raw) + } + if strings.Contains(raw, `"rc.ds":{"enabled"`) || strings.Contains(raw, `"infix-system:rc.ds":{"enabled"`) { + t.Fatalf("rc.d container must not carry an enabled leaf; raw: %s", raw) + } + rcd := putRCD(t, mock) + if len(rcd.Scripts) != 2 || rcd.Scripts[0].Name != "10-first" || rcd.Scripts[1].Name != "20-hello" { + t.Fatalf("new script must be appended after existing ones, got %+v", rcd.Scripts) + } + if rcd.Scripts[1].Description != "Say hello" || rcd.Scripts[1].Enabled == nil || !*rcd.Scripts[1].Enabled { + t.Fatalf("unexpected new script fields %+v", rcd.Scripts[1]) + } + if got := w.Header().Get("HX-Location"); !strings.Contains(got, `"/configure/advanced"`) { + t.Fatalf("want redirect back to page, got HX-Location %q", got) + } +} + +func TestConfigureAdvancedAddScript_RejectsDuplicate(t *testing.T) { + mock := &recordingFetcher{MockFetcher: testutil.NewMockFetcher()} + mock.SetResponse(candidatePath+"/ietf-system:system", advSystemResponse( + []map[string]any{advEntry("10-first", "echo one\n")}, nil)) + + form := url.Values{"name": {"10-first"}, "content": {"echo again"}} + w := httptest.NewRecorder() + newAdvHandler(t, mock).AddScript(w, newAdvRequest(t, http.MethodPost, "/configure/advanced/rc.d/scripts", form)) + + if w.Code != http.StatusUnprocessableEntity { + t.Fatalf("want 422 got %d", w.Code) + } + if mock.putCalls != 0 { + t.Fatalf("duplicate must not be written, got %d PUT call(s)", mock.putCalls) + } +} + +func TestConfigureAdvancedReorder_RewritesListOrder(t *testing.T) { + mock := &recordingFetcher{MockFetcher: testutil.NewMockFetcher()} + mock.SetResponse(candidatePath+"/ietf-system:system", advSystemResponse( + []map[string]any{advEntry("a", "echo a"), advEntry("b", "echo b"), advEntry("c", "echo c")}, nil)) + + form := url.Values{"order": {"c", "a", "b"}} + w := httptest.NewRecorder() + newAdvHandler(t, mock).ReorderScripts(w, newAdvRequest(t, http.MethodPost, "/configure/advanced/rc.d/order", form)) + + if w.Code != http.StatusOK { + t.Fatalf("want 200 got %d; body: %s", w.Code, w.Body.String()) + } + if mock.putCalls != 1 || mock.lastPath != rcdCandPath { + t.Fatalf("want 1 PUT to %q, got %d call(s) to %q", rcdCandPath, mock.putCalls, mock.lastPath) + } + var got []string + for _, s := range putRCD(t, mock).Scripts { + got = append(got, s.Name) + if len(s.Content) == 0 { + t.Fatalf("script %q lost its content on reorder", s.Name) + } + } + if strings.Join(got, ",") != "c,a,b" { + t.Fatalf("want order c,a,b got %v", got) + } + var trig map[string]string + if err := json.Unmarshal([]byte(w.Header().Get("HX-Trigger")), &trig); err != nil { + t.Fatalf("unmarshal HX-Trigger: %v", err) + } + if !strings.Contains(trig["cfgSaved"], "order saved") { + t.Fatalf("unexpected success message %q", trig["cfgSaved"]) + } +} + +func TestConfigureAdvancedReorder_RejectsMismatchedSet(t *testing.T) { + mock := &recordingFetcher{MockFetcher: testutil.NewMockFetcher()} + mock.SetResponse(candidatePath+"/ietf-system:system", advSystemResponse( + []map[string]any{advEntry("a", "echo a"), advEntry("b", "echo b")}, nil)) + h := newAdvHandler(t, mock) + + for _, order := range [][]string{{"a"}, {"a", "x"}, {"a", "a"}} { + w := httptest.NewRecorder() + h.ReorderScripts(w, newAdvRequest(t, http.MethodPost, "/configure/advanced/rc.d/order", url.Values{"order": order})) + if w.Code != http.StatusUnprocessableEntity { + t.Fatalf("order %v: want 422 got %d", order, w.Code) + } + } + if mock.putCalls != 0 { + t.Fatalf("mismatched order must not be written, got %d PUT call(s)", mock.putCalls) + } +} + +func TestConfigureAdvancedSaveScript_KeepsPosition(t *testing.T) { + mock := &recordingFetcher{MockFetcher: testutil.NewMockFetcher()} + mock.SetResponse(candidatePath+"/ietf-system:system", advSystemResponse( + []map[string]any{advEntry("a", "echo a"), advEntry("b", "echo b"), advEntry("c", "echo c")}, nil)) + + form := url.Values{"description": {"middle"}, "content": {"echo B"}} + req := newAdvRequest(t, http.MethodPost, "/configure/advanced/rc.d/scripts/b", form) + req.SetPathValue("name", "b") + w := httptest.NewRecorder() + newAdvHandler(t, mock).SaveScript(w, req) + + if w.Code != http.StatusOK { + t.Fatalf("want 200 got %d; body: %s", w.Code, w.Body.String()) + } + rcd := putRCD(t, mock) + if len(rcd.Scripts) != 3 || rcd.Scripts[1].Name != "b" { + t.Fatalf("edited script must keep position 2, got %+v", rcd.Scripts) + } + b := rcd.Scripts[1] + if string(b.Content) != "echo B" || b.Description != "middle" || b.Enabled == nil || *b.Enabled { + t.Fatalf("unexpected edited script %+v (content %q)", b, b.Content) + } +} + +func TestConfigureAdvancedDeleteScript(t *testing.T) { + mock := &recordingFetcher{MockFetcher: testutil.NewMockFetcher()} + + req := newAdvRequest(t, http.MethodDelete, "/configure/advanced/rc.d/scripts/10-first", nil) + req.SetPathValue("name", "10-first") + w := httptest.NewRecorder() + newAdvHandler(t, mock).DeleteScript(w, req) + + if w.Code != http.StatusNoContent { + t.Fatalf("want 204 got %d", w.Code) + } + want := rcdCandPath + "/rc.d=10-first" + if len(mock.deletePaths) != 1 || mock.deletePaths[0] != want { + t.Fatalf("want DELETE %q got %v", want, mock.deletePaths) + } +} + +// ─── /etc/default files ─────────────────────────────────────────────────────── + +func TestConfigureAdvancedOverview_DefaultFiles(t *testing.T) { + mock := testutil.NewMockFetcher() + mock.SetResponse(candidatePath+"/ietf-system:system", advSystemResponse(nil, + []map[string]any{ + // Quote-free content: the minimal template renders it in a text + // context where html/template would escape double quotes. + advEntry("ptp4l", "PTP4L_ARGS=--ptp_minor_version=0\n"), + { + "name": "chronyd", + "description": "off", + "enabled": false, + "content": base64.StdEncoding.EncodeToString([]byte("CHRONYD_ARGS=-x\n")), + }, + })) + + w := httptest.NewRecorder() + newAdvHandler(t, mock).Overview(w, newAdvRequest(t, http.MethodGet, "/configure/advanced", nil)) + + if w.Code != http.StatusOK { + t.Fatalf("want 200 got %d; body: %s", w.Code, w.Body.String()) + } + want := "n=0|files=2;ptp4l:true:PTP4L_ARGS=--ptp_minor_version=0\n;chronyd:false:CHRONYD_ARGS=-x\n" + if got := w.Body.String(); got != want { + t.Fatalf("body mismatch\nwant: %q\n got: %q", want, got) + } +} + +func TestConfigureAdvancedAddFile_PutsEntryWithBase64Content(t *testing.T) { + mock := newAdvRecorder() + mock.SetResponse(candidatePath+"/ietf-system:system", advSystemResponse(nil, + []map[string]any{advEntry("chronyd", "CHRONYD_ARGS=\"-x\"")})) + + form := url.Values{ + "name": {"ptp4l"}, + "description": {"Force PTPv2.0"}, + "enabled": {"true"}, + "content": {"PTP4L_ARGS=\"--ptp_minor_version 0\"\r\n"}, + } + w := httptest.NewRecorder() + newAdvHandler(t, mock).AddFile(w, newAdvRequest(t, http.MethodPost, "/configure/advanced/default/files", form)) + + if w.Code != http.StatusNoContent { + t.Fatalf("want 204 got %d; body: %s", w.Code, w.Body.String()) + } + wantPath := defaultCandPath + "/default=ptp4l" + if mock.putCalls != 1 || mock.lastPath != wantPath { + t.Fatalf("want 1 PUT to %q, got %d call(s) to %q", wantPath, mock.putCalls, mock.lastPath) + } + if mock.patchCalls != 0 { + t.Fatalf("add must not PATCH, got %d call(s)", mock.patchCalls) + } + raw := wireJSON(t, mock.lastBody) + wantB64 := base64.StdEncoding.EncodeToString([]byte("PTP4L_ARGS=\"--ptp_minor_version 0\"\n")) + for _, want := range []string{ + `"infix-system:default":[{`, + `"name":"ptp4l"`, + `"description":"Force PTPv2.0"`, + `"enabled":true`, + `"content":"` + wantB64 + `"`, + } { + if !strings.Contains(raw, want) { + t.Fatalf("PUT body missing %s; raw: %s", want, raw) + } + } + if got := w.Header().Get("HX-Location"); !strings.Contains(got, `"/configure/advanced"`) { + t.Fatalf("want redirect back to page, got HX-Location %q", got) + } +} + +func TestConfigureAdvancedAddFile_RejectsDuplicate(t *testing.T) { + mock := newAdvRecorder() + mock.SetResponse(candidatePath+"/ietf-system:system", advSystemResponse(nil, + []map[string]any{advEntry("ptp4l", "PTP4L_ARGS=\"\"")})) + + form := url.Values{"name": {"ptp4l"}, "content": {"PTP4L_ARGS=\"-x\""}} + w := httptest.NewRecorder() + newAdvHandler(t, mock).AddFile(w, newAdvRequest(t, http.MethodPost, "/configure/advanced/default/files", form)) + + if w.Code != http.StatusUnprocessableEntity { + t.Fatalf("want 422 got %d", w.Code) + } + if mock.putCalls != 0 || mock.patchCalls != 0 { + t.Fatalf("duplicate must not be written, got %d PUT / %d PATCH call(s)", mock.putCalls, mock.patchCalls) + } +} + +func TestConfigureAdvancedToggleFile_PatchesEnabledLeaf(t *testing.T) { + mock := newAdvRecorder() + + // Unchecked checkbox: htmx sends no "enabled" value at all. + req := newAdvRequest(t, http.MethodPost, "/configure/advanced/default/files/ptp4l/enabled", url.Values{}) + req.SetPathValue("name", "ptp4l") + w := httptest.NewRecorder() + newAdvHandler(t, mock).ToggleFile(w, req) + + if w.Code != http.StatusOK { + t.Fatalf("want 200 got %d; body: %s", w.Code, w.Body.String()) + } + wantPath := defaultCandPath + "/default=ptp4l" + if mock.patchCalls != 1 || mock.patchPath != wantPath { + t.Fatalf("want 1 PATCH to %q, got %d call(s) to %q", wantPath, mock.patchCalls, mock.patchPath) + } + if mock.putCalls != 0 { + t.Fatalf("toggle must not PUT, got %d call(s)", mock.putCalls) + } + raw := wireJSON(t, mock.patchBody) + if want := `{"infix-system:default":[{"enabled":false,"name":"ptp4l"}]}`; raw != want { + t.Fatalf("PATCH body\nwant: %s\n got: %s", want, raw) + } + if !strings.Contains(w.Header().Get("HX-Trigger"), "File disabled") { + t.Fatalf("unexpected HX-Trigger %q", w.Header().Get("HX-Trigger")) + } + + // Checked: "enabled=true". + req = newAdvRequest(t, http.MethodPost, "/configure/advanced/default/files/ptp4l/enabled", url.Values{"enabled": {"true"}}) + req.SetPathValue("name", "ptp4l") + w = httptest.NewRecorder() + newAdvHandler(t, mock).ToggleFile(w, req) + if raw := wireJSON(t, mock.patchBody); !strings.Contains(raw, `"enabled":true`) { + t.Fatalf("want enabled:true in PATCH body, got %s", raw) + } +} + +func TestConfigureAdvancedSaveFile_PutsEntry(t *testing.T) { + mock := newAdvRecorder() + + form := url.Values{"description": {"tuned"}, "content": {"PTP4L_ARGS=\"-l 7\""}} + req := newAdvRequest(t, http.MethodPost, "/configure/advanced/default/files/ptp4l", form) + req.SetPathValue("name", "ptp4l") + w := httptest.NewRecorder() + newAdvHandler(t, mock).SaveFile(w, req) + + if w.Code != http.StatusOK { + t.Fatalf("want 200 got %d; body: %s", w.Code, w.Body.String()) + } + if mock.putCalls != 1 || mock.lastPath != defaultCandPath+"/default=ptp4l" { + t.Fatalf("want 1 PUT to default=ptp4l, got %d call(s) to %q", mock.putCalls, mock.lastPath) + } + raw := wireJSON(t, mock.lastBody) + wantB64 := base64.StdEncoding.EncodeToString([]byte("PTP4L_ARGS=\"-l 7\"")) + if !strings.Contains(raw, `"content":"`+wantB64+`"`) || !strings.Contains(raw, `"enabled":false`) { + t.Fatalf("unexpected PUT body %s", raw) + } +} + +func TestConfigureAdvancedDeleteFile(t *testing.T) { + mock := &recordingFetcher{MockFetcher: testutil.NewMockFetcher()} + + req := newAdvRequest(t, http.MethodDelete, "/configure/advanced/default/files/ptp4l", nil) + req.SetPathValue("name", "ptp4l") + w := httptest.NewRecorder() + newAdvHandler(t, mock).DeleteFile(w, req) + + if w.Code != http.StatusNoContent { + t.Fatalf("want 204 got %d", w.Code) + } + want := defaultCandPath + "/default=ptp4l" + if len(mock.deletePaths) != 1 || mock.deletePaths[0] != want { + t.Fatalf("want DELETE %q got %v", want, mock.deletePaths) + } + if got := w.Header().Get("HX-Location"); !strings.Contains(got, `"/configure/advanced"`) { + t.Fatalf("want redirect back to page, got HX-Location %q", got) + } +} diff --git a/src/webui/internal/schema/helpers.go b/src/webui/internal/schema/helpers.go index 94d1a85f40..bdb486854c 100644 --- a/src/webui/internal/schema/helpers.go +++ b/src/webui/internal/schema/helpers.go @@ -51,5 +51,44 @@ func DescriptionOf(mgr *Manager, path string) string { if err != nil || node == nil { return "" } - return node.Description + return Reflow(node.Description) +} + +// Reflow joins the hard-wrapped lines of a YANG description into one line +// per paragraph. Paragraphs are separated by a blank line and lines that +// start a list item (- or *) keep their line break. +func Reflow(desc string) string { + var out strings.Builder + var para strings.Builder + + flush := func() { + if para.Len() > 0 { + if out.Len() > 0 { + out.WriteString("\n\n") + } + out.WriteString(para.String()) + para.Reset() + } + } + + for _, line := range strings.Split(desc, "\n") { + line = strings.TrimSpace(line) + switch { + case line == "": + flush() + case strings.HasPrefix(line, "- ") || strings.HasPrefix(line, "* "): + if para.Len() > 0 { + para.WriteString("\n") + } + para.WriteString(line) + case para.Len() > 0: + para.WriteString(" ") + para.WriteString(line) + default: + para.WriteString(line) + } + } + flush() + + return out.String() } diff --git a/src/webui/internal/schema/helpers_test.go b/src/webui/internal/schema/helpers_test.go new file mode 100644 index 0000000000..70c3f674ee --- /dev/null +++ b/src/webui/internal/schema/helpers_test.go @@ -0,0 +1,17 @@ +package schema + +import "testing" + +func TestReflow(t *testing.T) { + in := "Scripts run once at boot.\n\nScripts are extracted to /etc/rc.d\n and run as root.\n\nChanges take\neffect at the next boot." + want := "Scripts run once at boot.\n\nScripts are extracted to /etc/rc.d and run as root.\n\nChanges take effect at the next boot." + if got := Reflow(in); got != want { + t.Fatalf("Reflow() = %q, want %q", got, want) + } + + in = "Options:\n - foo\n - bar\n continued" + want = "Options:\n- foo\n- bar continued" + if got := Reflow(in); got != want { + t.Fatalf("Reflow() list = %q, want %q", got, want) + } +} diff --git a/src/webui/internal/server/server.go b/src/webui/internal/server/server.go index b02bc8a5ce..b682135255 100644 --- a/src/webui/internal/server/server.go +++ b/src/webui/internal/server/server.go @@ -149,6 +149,10 @@ func New( if err != nil { return nil, err } + cfgAdvTmpl, err := template.ParseFS(templateFS, "layouts/*.html", "fragments/configure-toolbar.html", "pages/configure-advanced.html") + if err != nil { + return nil, err + } cfgDiffTmpl, err := template.ParseFS(templateFS, "fragments/config-diff.html") if err != nil { return nil, err @@ -278,6 +282,7 @@ func New( cfgRoutes := &handlers.ConfigureRoutesHandler{Template: cfgRoutesTmpl, RC: rc, Schema: schemaCache} cfgFw := &handlers.ConfigureFirewallHandler{Template: cfgFwTmpl, RC: rc, Schema: schemaCache} cfgHw := &handlers.ConfigureHardwareHandler{Template: cfgHwTmpl, RC: rc, Schema: schemaCache} + cfgAdv := &handlers.ConfigureAdvancedHandler{Template: cfgAdvTmpl, RC: rc, Schema: schemaCache} cfgIf := &handlers.ConfigureInterfacesHandler{Template: cfgIfTmpl, RC: rc, Schema: schemaCache} schemaH := &handlers.SchemaHandler{Cache: schemaCache} dataH := &handlers.DataHandler{RC: rc, Schema: schemaCache} @@ -373,6 +378,16 @@ func New( mux.HandleFunc("POST /configure/system/dns/search", cfgSys.AddDNSSearch) mux.HandleFunc("DELETE /configure/system/dns/search/{domain}", cfgSys.DeleteDNSSearch) mux.HandleFunc("POST /configure/system/preferences", cfgSys.SavePreferences) + mux.HandleFunc("GET /configure/advanced", cfgAdv.Overview) + mux.HandleFunc("POST /configure/advanced/rc.d/order", cfgAdv.ReorderScripts) + mux.HandleFunc("POST /configure/advanced/rc.d/scripts", cfgAdv.AddScript) + mux.HandleFunc("POST /configure/advanced/rc.d/scripts/{name}", cfgAdv.SaveScript) + mux.HandleFunc("POST /configure/advanced/rc.d/scripts/{name}/enabled", cfgAdv.ToggleScript) + mux.HandleFunc("DELETE /configure/advanced/rc.d/scripts/{name}", cfgAdv.DeleteScript) + mux.HandleFunc("POST /configure/advanced/default/files", cfgAdv.AddFile) + mux.HandleFunc("POST /configure/advanced/default/files/{name}", cfgAdv.SaveFile) + mux.HandleFunc("POST /configure/advanced/default/files/{name}/enabled", cfgAdv.ToggleFile) + mux.HandleFunc("DELETE /configure/advanced/default/files/{name}", cfgAdv.DeleteFile) mux.HandleFunc("GET /configure/interfaces", cfgIf.Overview) mux.HandleFunc("POST /configure/interfaces", cfgIf.CreateInterface) mux.HandleFunc("POST /configure/interfaces/wizard/sym-key", cfgIf.WizardCreateSymKey) diff --git a/src/webui/static/css/style.css b/src/webui/static/css/style.css index aafcf2c48d..233d49be57 100644 --- a/src/webui/static/css/style.css +++ b/src/webui/static/css/style.css @@ -2690,7 +2690,7 @@ select.cfg-input { to cap the columns and make the input shrink. */ .info-table .cfg-input { min-width: 0; } .info-table-fixed { table-layout: fixed; } -.cfg-input-mono { font-family: var(--font-mono); font-size: 0.85rem; } +.cfg-input-mono { font-family: var(--font-mono); font-size: 0.85rem; font-variant-ligatures: none; } .cfg-reset-col { width: 1%; white-space: nowrap; padding-left: 0.25rem; } .cfg-section-head { font-size: 0.85rem; font-weight: 600; text-transform: uppercase; letter-spacing: 0.05em; color: var(--text-muted); margin: 0 0 0.4rem; padding-bottom: 0.25rem; border-bottom: 1px solid var(--border); } .cfg-subsection-head { font-size: 0.8rem; font-weight: 600; color: var(--text-muted); margin: 0.5rem 0 0.25rem; } @@ -3434,3 +3434,21 @@ details[open].yt-leaf-item .yt-leaf-name::before { transform: rotate(90deg); } font-size: 0.8125rem; margin: 0.75rem 1rem 0; } + +/* Configure > Advanced: rc.d boot scripts */ +.rcd-handle-col { width: 1.5rem; padding-right: 0 !important; } +.rcd-drag-handle { + display: inline-flex; + align-items: center; + cursor: grab; + user-select: none; + color: var(--fg-muted); + padding: 0.15rem; + border-radius: 3px; +} +.rcd-drag-handle:hover { color: var(--text); background: var(--hover-bg, rgba(0,0,0,0.06)); } +.rcd-drag-handle:active { cursor: grabbing; } +.rcd-row.rcd-dragging { opacity: 0.35; } +.rcd-row.rcd-drop-before > td { box-shadow: 0 -2px 0 var(--primary) inset; } +tbody.rcd-drop-before > tr:last-child > td { box-shadow: 0 2px 0 var(--primary) inset; } +.rcd-content { min-height: 12rem; white-space: pre; overflow-wrap: normal; overflow-x: auto; } diff --git a/src/webui/static/img/icons/README.md b/src/webui/static/img/icons/README.md index 299e7d30ce..2d48ab3716 100644 --- a/src/webui/static/img/icons/README.md +++ b/src/webui/static/img/icons/README.md @@ -36,6 +36,7 @@ untouched. | services.svg | library-big | | software.svg | hard-drive-download | | status-tree.svg | text-search | +| system-advanced.svg| wrench | | system-control.svg| power | | system.svg | settings | | wifi.svg | wifi | diff --git a/src/webui/static/img/icons/system-advanced.svg b/src/webui/static/img/icons/system-advanced.svg new file mode 100644 index 0000000000..6905b6b7e8 --- /dev/null +++ b/src/webui/static/img/icons/system-advanced.svg @@ -0,0 +1,3 @@ + + + diff --git a/src/webui/static/js/app.js b/src/webui/static/js/app.js index 65f5716e2d..57fba9b40a 100644 --- a/src/webui/static/js/app.js +++ b/src/webui/static/js/app.js @@ -2814,3 +2814,147 @@ function renderCfgLog() { links.forEach(function (a) { a.href = url; }); }); })(); + +// ─── Configure > Advanced: rc.d script order drag-and-drop ─────────────────── +// Rows are moved in the DOM on drop and the new order is posted at once; the +// list order in the datastore is the execution order. On failure the rows +// snap back to the last order the server confirmed. +(function () { + function csrf() { + var meta = document.querySelector('meta[name="csrf-token"]'); + return meta ? meta.getAttribute('content') : ''; + } + + function init(scope) { + var tbody = (scope || document).querySelector('#rcd-scripts'); + if (!tbody || tbody.dataset.dndInit) return; + tbody.dataset.dndInit = 'true'; + + function rows() { + return Array.prototype.slice.call(tbody.querySelectorAll('.rcd-row')); + } + function detailOf(row) { + var next = row.nextElementSibling; + return next && next.classList.contains('key-detail-row') ? next : null; + } + function order() { + return rows().map(function (r) { return r.dataset.name; }); + } + function moveRow(row, before) { + var detail = detailOf(row); + tbody.insertBefore(row, before); + if (detail) tbody.insertBefore(detail, row.nextElementSibling); + } + function restore(names) { + var byName = {}; + rows().forEach(function (r) { byName[r.dataset.name] = r; }); + names.forEach(function (n) { if (byName[n]) moveRow(byName[n], null); }); + } + function clearIndicators() { + tbody.classList.remove('rcd-drop-before'); + tbody.querySelectorAll('.rcd-drop-before').forEach(function (el) { + el.classList.remove('rcd-drop-before'); + }); + } + + var confirmed = order(); + var dragging = null; + var insertRef; // row to insert before; undefined = not set, null = append + + tbody.addEventListener('dragstart', function (e) { + var handle = e.target.closest && e.target.closest('.rcd-drag-handle'); + if (!handle) return; + dragging = handle.closest('.rcd-row'); + dragging.classList.add('rcd-dragging'); + e.dataTransfer.effectAllowed = 'move'; + e.dataTransfer.setData('text/plain', dragging.dataset.name); + }); + + tbody.addEventListener('dragend', function () { + if (dragging) dragging.classList.remove('rcd-dragging'); + dragging = null; + insertRef = undefined; + clearIndicators(); + }); + + tbody.addEventListener('dragenter', function (e) { e.preventDefault(); }); + + tbody.addEventListener('dragover', function (e) { + if (!dragging) return; + e.preventDefault(); + e.dataTransfer.dropEffect = 'move'; + var target = e.target.closest('tr'); + if (target && target.classList.contains('key-detail-row')) { + target = target.previousElementSibling; + } + clearIndicators(); + if (!target || !target.classList.contains('rcd-row') || target === dragging) { + insertRef = undefined; + return; + } + var rect = target.getBoundingClientRect(); + if (e.clientY < rect.top + rect.height / 2) { + insertRef = target; + } else { + var after = detailOf(target) || target; + insertRef = after.nextElementSibling; + while (insertRef && !insertRef.classList.contains('rcd-row')) { + insertRef = insertRef.nextElementSibling; + } + } + if (insertRef) insertRef.classList.add('rcd-drop-before'); + else tbody.classList.add('rcd-drop-before'); + }); + + tbody.addEventListener('drop', function (e) { + e.preventDefault(); + if (!dragging || insertRef === undefined) return; + moveRow(dragging, insertRef); + clearIndicators(); + insertRef = undefined; + save(); + }); + + var status = document.getElementById('rcd-order-status'); + function setStatus(text, ok) { + if (!status) return; + status.textContent = text; + status.classList.toggle('saved', !!ok); + if (text) setTimeout(function () { status.textContent = ''; status.classList.remove('saved'); }, 4000); + } + + function save() { + var names = order(); + if (names.join('\n') === confirmed.join('\n')) return; + var params = new URLSearchParams(); + names.forEach(function (n) { params.append('order', n); }); + fetch('/configure/advanced/rc.d/order', { + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + 'X-CSRF-Token': csrf(), + }, + body: params.toString(), + }).then(function (r) { + if (r.ok) { + confirmed = names; + setStatus('✓ Script order saved', true); + document.dispatchEvent(new CustomEvent('cfgSaved', { detail: { value: 'Script order saved' } })); + return; + } + return r.text().then(function (t) { + restore(confirmed); + var msg = t.replace(/<[^>]*>/g, '').trim() || 'Save failed'; + setStatus('✗ ' + msg, false); + document.dispatchEvent(new CustomEvent('cfgError', { detail: { value: msg } })); + }); + }).catch(function () { + restore(confirmed); + setStatus('✗ Save failed', false); + }); + } + } + + document.addEventListener('DOMContentLoaded', function () { init(document); }); + document.addEventListener('htmx:afterSwap', function (evt) { init(evt.target || document); }); +})(); diff --git a/src/webui/templates/layouts/icons.html b/src/webui/templates/layouts/icons.html index 935741a1ca..4bb043ce95 100644 --- a/src/webui/templates/layouts/icons.html +++ b/src/webui/templates/layouts/icons.html @@ -8,6 +8,8 @@ {{define "icon-trash"}}{{end}} +{{define "icon-edit"}}{{end}} +{{define "icon-grip"}}{{end}} {{define "icon-reset"}}{{end}} {{define "icon-menu"}}{{end}} {{define "icon-terminal"}}{{end}} diff --git a/src/webui/templates/layouts/sidebar.html b/src/webui/templates/layouts/sidebar.html index 62adddf0c0..6c16cd1797 100644 --- a/src/webui/templates/layouts/sidebar.html +++ b/src/webui/templates/layouts/sidebar.html @@ -174,7 +174,7 @@