Compare commits
11 Commits
Author | SHA1 | Date | |
---|---|---|---|
d6dca03df1 | |||
6e1cb57e03 | |||
3f2549c746 | |||
91eb83d6e1 | |||
5924705b24 | |||
0f9679d91e | |||
7325ee1c0c | |||
4a12e1ba8f | |||
2df68d3fca | |||
5fd3a9d925 | |||
6bf1d1ccf2 |
@ -1,4 +1,5 @@
|
||||
Dockerfile
|
||||
modd.*
|
||||
tmp/**/*
|
||||
dist/*
|
||||
go.work
|
||||
@ -6,3 +7,4 @@ go.work.sum
|
||||
modd.*conf
|
||||
test-initrd*
|
||||
test-initrd/**/*
|
||||
target
|
||||
|
1
.gitignore
vendored
1
.gitignore
vendored
@ -5,3 +5,4 @@
|
||||
/tmp
|
||||
/go.work
|
||||
/go.work.sum
|
||||
/target
|
||||
|
623
Cargo.lock
generated
Normal file
623
Cargo.lock
generated
Normal file
@ -0,0 +1,623 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "addr2line"
|
||||
version = "0.24.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dfbe277e56a376000877090da837660b4427aad530e3028d44e0bffe4f89a1c1"
|
||||
dependencies = [
|
||||
"gimli",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "adler2"
|
||||
version = "2.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
|
||||
|
||||
[[package]]
|
||||
name = "aho-corasick"
|
||||
version = "1.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anstream"
|
||||
version = "0.6.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "301af1932e46185686725e0fad2f8f2aa7da69dd70bf6ecc44d6b703844a3933"
|
||||
dependencies = [
|
||||
"anstyle",
|
||||
"anstyle-parse",
|
||||
"anstyle-query",
|
||||
"anstyle-wincon",
|
||||
"colorchoice",
|
||||
"is_terminal_polyfill",
|
||||
"utf8parse",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anstyle"
|
||||
version = "1.0.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "862ed96ca487e809f1c8e5a8447f6ee2cf102f846893800b20cebdf541fc6bbd"
|
||||
|
||||
[[package]]
|
||||
name = "anstyle-parse"
|
||||
version = "0.2.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4e7644824f0aa2c7b9384579234ef10eb7efb6a0deb83f9630a49594dd9c15c2"
|
||||
dependencies = [
|
||||
"utf8parse",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anstyle-query"
|
||||
version = "1.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6c8bdeb6047d8983be085bab0ba1472e6dc604e7041dbf6fcd5e71523014fae9"
|
||||
dependencies = [
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anstyle-wincon"
|
||||
version = "3.0.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "403f75924867bb1033c59fbf0797484329750cfbe3c4325cd33127941fabc882"
|
||||
dependencies = [
|
||||
"anstyle",
|
||||
"once_cell_polyfill",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "backtrace"
|
||||
version = "0.3.75"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6806a6321ec58106fea15becdad98371e28d92ccbc7c8f1b3b6dd724fe8f1002"
|
||||
dependencies = [
|
||||
"addr2line",
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"miniz_oxide",
|
||||
"object",
|
||||
"rustc-demangle",
|
||||
"windows-targets",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.9.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1b8e56985ec62d17e9c1001dc89c88ecd7dc08e47eba5ec7c29c7b5eeecde967"
|
||||
|
||||
[[package]]
|
||||
name = "bytes"
|
||||
version = "1.10.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d71b6127be86fdcfddb610f7182ac57211d4b18a3e9c82eb2d17662f2227ad6a"
|
||||
|
||||
[[package]]
|
||||
name = "cfg-if"
|
||||
version = "1.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9555578bc9e57714c812a1f84e4fc5b4d21fcb063490c624de019f7464c91268"
|
||||
|
||||
[[package]]
|
||||
name = "cfg_aliases"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"
|
||||
|
||||
[[package]]
|
||||
name = "colorchoice"
|
||||
version = "1.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75"
|
||||
|
||||
[[package]]
|
||||
name = "either"
|
||||
version = "1.15.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719"
|
||||
|
||||
[[package]]
|
||||
name = "env_filter"
|
||||
version = "0.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "186e05a59d4c50738528153b83b0b0194d3a29507dfec16eccd4b342903397d0"
|
||||
dependencies = [
|
||||
"log",
|
||||
"regex",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "env_logger"
|
||||
version = "0.11.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "13c863f0904021b108aa8b2f55046443e6b1ebde8fd4a15c399893aae4fa069f"
|
||||
dependencies = [
|
||||
"anstream",
|
||||
"anstyle",
|
||||
"env_filter",
|
||||
"jiff",
|
||||
"log",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "equivalent"
|
||||
version = "1.0.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
|
||||
|
||||
[[package]]
|
||||
name = "eyre"
|
||||
version = "0.6.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7cd915d99f24784cdc19fd37ef22b97e3ff0ae756c7e492e9fbfe897d61e2aec"
|
||||
dependencies = [
|
||||
"indenter",
|
||||
"once_cell",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gimli"
|
||||
version = "0.31.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "07e28edb80900c19c28f1072f2e8aeca7fa06b23cd4169cefe1af5aa3260783f"
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.15.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5971ac85611da7067dbfcabef3c70ebb5606018acd9e2a3903a0da507521e0d5"
|
||||
|
||||
[[package]]
|
||||
name = "indenter"
|
||||
version = "0.3.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ce23b50ad8242c51a442f3ff322d56b02f08852c77e4c0b4d3fd684abc89c683"
|
||||
|
||||
[[package]]
|
||||
name = "indexmap"
|
||||
version = "2.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cea70ddb795996207ad57735b50c5982d8844f38ba9ee5f1aedcfb708a2aa11e"
|
||||
dependencies = [
|
||||
"equivalent",
|
||||
"hashbrown",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "init"
|
||||
version = "2.1.0"
|
||||
dependencies = [
|
||||
"env_logger",
|
||||
"eyre",
|
||||
"itertools",
|
||||
"log",
|
||||
"nix",
|
||||
"regex",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serde_yaml",
|
||||
"shell-escape",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "is_terminal_polyfill"
|
||||
version = "1.70.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7943c866cc5cd64cbc25b2e01621d07fa8eb2a1a23160ee81ce38704e97b8ecf"
|
||||
|
||||
[[package]]
|
||||
name = "itertools"
|
||||
version = "0.14.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285"
|
||||
dependencies = [
|
||||
"either",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itoa"
|
||||
version = "1.0.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c"
|
||||
|
||||
[[package]]
|
||||
name = "jiff"
|
||||
version = "0.2.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a194df1107f33c79f4f93d02c80798520551949d59dfad22b6157048a88cca93"
|
||||
dependencies = [
|
||||
"jiff-static",
|
||||
"log",
|
||||
"portable-atomic",
|
||||
"portable-atomic-util",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jiff-static"
|
||||
version = "0.2.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6c6e1db7ed32c6c71b759497fae34bf7933636f75a251b9e736555da426f6442"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.172"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d750af042f7ef4f724306de029d18836c26c1765a54a6a3f094cbd23a7267ffa"
|
||||
|
||||
[[package]]
|
||||
name = "log"
|
||||
version = "0.4.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "13dc2df351e3202783a1fe0d44375f7295ffb4049267b0f3018346dc122a1d94"
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.7.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32a282da65faaf38286cf3be983213fcf1d2e2a58700e808f83f4ea9a4804bc0"
|
||||
|
||||
[[package]]
|
||||
name = "miniz_oxide"
|
||||
version = "0.8.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
|
||||
dependencies = [
|
||||
"adler2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "mio"
|
||||
version = "1.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "78bed444cc8a2160f01cbcf811ef18cac863ad68ae8ca62092e8db51d51c761c"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"wasi",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nix"
|
||||
version = "0.30.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "74523f3a35e05aba87a1d978330aef40f67b0304ac79c1c00b294c9830543db6"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"cfg-if",
|
||||
"cfg_aliases",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "object"
|
||||
version = "0.36.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "62948e14d923ea95ea2c7c86c71013138b66525b86bdc08d2dcc262bdb497b87"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "once_cell"
|
||||
version = "1.21.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d"
|
||||
|
||||
[[package]]
|
||||
name = "once_cell_polyfill"
|
||||
version = "1.70.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a4895175b425cb1f87721b59f0f286c2092bd4af812243672510e1ac53e2e0ad"
|
||||
|
||||
[[package]]
|
||||
name = "pin-project-lite"
|
||||
version = "0.2.16"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b"
|
||||
|
||||
[[package]]
|
||||
name = "portable-atomic"
|
||||
version = "1.11.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f84267b20a16ea918e43c6a88433c2d54fa145c92a811b5b047ccbe153674483"
|
||||
|
||||
[[package]]
|
||||
name = "portable-atomic-util"
|
||||
version = "0.2.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d8a2f0d8d040d7848a709caf78912debcc3f33ee4b3cac47d73d1e1069e83507"
|
||||
dependencies = [
|
||||
"portable-atomic",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.95"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "02b3e5e68a3a1a02aad3ec490a98007cbc13c37cbe84a3cd7b8e406d76e7f778"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.40"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex"
|
||||
version = "1.11.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b544ef1b4eac5dc2db33ea63606ae9ffcfac26c1416a2806ae0bf5f56b201191"
|
||||
dependencies = [
|
||||
"aho-corasick",
|
||||
"memchr",
|
||||
"regex-automata",
|
||||
"regex-syntax",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex-automata"
|
||||
version = "0.4.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "809e8dc61f6de73b46c85f4c96486310fe304c434cfa43669d7b40f711150908"
|
||||
dependencies = [
|
||||
"aho-corasick",
|
||||
"memchr",
|
||||
"regex-syntax",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex-syntax"
|
||||
version = "0.8.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c"
|
||||
|
||||
[[package]]
|
||||
name = "rustc-demangle"
|
||||
version = "0.1.25"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "989e6739f80c4ad5b13e0fd7fe89531180375b18520cc8c82080e4dc4035b84f"
|
||||
|
||||
[[package]]
|
||||
name = "ryu"
|
||||
version = "1.0.20"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f"
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
version = "1.0.219"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5f0e2c6ed6606019b4e29e69dbaba95b11854410e5347d525002456dbbb786b6"
|
||||
dependencies = [
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_derive"
|
||||
version = "1.0.219"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5b0276cf7f2c73365f7157c8123c21cd9a50fbbd844757af28ca1f5925fc2a00"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_json"
|
||||
version = "1.0.140"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "20068b6e96dc6c9bd23e01df8827e6c7e1f2fddd43c21810382803c136b99373"
|
||||
dependencies = [
|
||||
"itoa",
|
||||
"memchr",
|
||||
"ryu",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_yaml"
|
||||
version = "0.9.34+deprecated"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47"
|
||||
dependencies = [
|
||||
"indexmap",
|
||||
"itoa",
|
||||
"ryu",
|
||||
"serde",
|
||||
"unsafe-libyaml",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "shell-escape"
|
||||
version = "0.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "45bb67a18fa91266cc7807181f62f9178a6873bfad7dc788c42e6430db40184f"
|
||||
|
||||
[[package]]
|
||||
name = "signal-hook-registry"
|
||||
version = "1.4.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9203b8055f63a2a00e2f593bb0510367fe707d7ff1e5c872de2f537b339e5410"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "socket2"
|
||||
version = "0.5.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e22376abed350d73dd1cd119b57ffccad95b4e585a7cda43e286245ce23c0678"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "2.0.103"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e4307e30089d6fd6aff212f2da3a1f9e32f3223b1f010fb09b7c95f90f3ca1e8"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tokio"
|
||||
version = "1.45.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "75ef51a33ef1da925cea3e4eb122833cb377c61439ca401b770f54902b806779"
|
||||
dependencies = [
|
||||
"backtrace",
|
||||
"bytes",
|
||||
"libc",
|
||||
"mio",
|
||||
"pin-project-lite",
|
||||
"signal-hook-registry",
|
||||
"socket2",
|
||||
"tokio-macros",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tokio-macros"
|
||||
version = "2.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6e06d43f1345a3bcd39f6a56dbb7dcab2ba47e68e8ac134855e7e2bdbaf8cab8"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512"
|
||||
|
||||
[[package]]
|
||||
name = "unsafe-libyaml"
|
||||
version = "0.2.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861"
|
||||
|
||||
[[package]]
|
||||
name = "utf8parse"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
|
||||
|
||||
[[package]]
|
||||
name = "wasi"
|
||||
version = "0.11.1+wasi-snapshot-preview1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.52.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
|
||||
dependencies = [
|
||||
"windows-targets",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.59.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
|
||||
dependencies = [
|
||||
"windows-targets",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-targets"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
|
||||
dependencies = [
|
||||
"windows_aarch64_gnullvm",
|
||||
"windows_aarch64_msvc",
|
||||
"windows_i686_gnu",
|
||||
"windows_i686_gnullvm",
|
||||
"windows_i686_msvc",
|
||||
"windows_x86_64_gnu",
|
||||
"windows_x86_64_gnullvm",
|
||||
"windows_x86_64_msvc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows_aarch64_gnullvm"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
|
||||
|
||||
[[package]]
|
||||
name = "windows_aarch64_msvc"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_gnu"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_gnullvm"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_msvc"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_gnu"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_gnullvm"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_msvc"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
|
23
Cargo.toml
Normal file
23
Cargo.toml
Normal file
@ -0,0 +1,23 @@
|
||||
[package]
|
||||
name = "init"
|
||||
version = "2.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[profile.release]
|
||||
strip = true
|
||||
panic = "abort"
|
||||
opt-level = "z"
|
||||
lto = true
|
||||
|
||||
[dependencies]
|
||||
env_logger = "0.11.3"
|
||||
eyre = "0.6.12"
|
||||
itertools = "0.14.0"
|
||||
log = "0.4.21"
|
||||
nix = { version = "0.30.1", features = ["feature", "reboot"] }
|
||||
regex = "1.11.1"
|
||||
serde = { version = "1.0.198", features = ["derive"] }
|
||||
serde_json = "1.0.116"
|
||||
serde_yaml = "0.9.34"
|
||||
shell-escape = "0.1.5"
|
||||
tokio = { version = "1.38.0", features = ["rt", "signal", "process", "net", "macros"] }
|
35
Dockerfile
35
Dockerfile
@ -1,32 +1,37 @@
|
||||
from golang:1.21.5-alpine3.19 as build
|
||||
from rust:1.87.0-alpine as rust
|
||||
|
||||
run apk add --no-cache git musl-dev libudev-zero-dev # pkgconfig cryptsetup-dev lvm2-dev clang-dev clang-static
|
||||
|
||||
workdir /src
|
||||
copy go.mod go.sum .
|
||||
run go mod download
|
||||
|
||||
copy . .
|
||||
run go test ./...
|
||||
run go build -o /go/bin/init -trimpath .
|
||||
run --mount=type=cache,id=novit-rs,target=/usr/local/cargo/registry \
|
||||
--mount=type=cache,id=novit-rs-target,sharing=private,target=/src/target \
|
||||
cargo build --release && cp target/release/init /
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
from alpine:3.19.0 as initrd
|
||||
|
||||
run apk add --no-cache xz
|
||||
from alpine:3.22.0 as initrd
|
||||
|
||||
workdir /layer
|
||||
run wget -O- https://dl-cdn.alpinelinux.org/alpine/v3.18/releases/x86_64/alpine-minirootfs-3.18.4-x86_64.tar.gz |tar zxv
|
||||
|
||||
run apk add --no-cache -p . musl lvm2 lvm2-dmeventd udev cryptsetup e2fsprogs btrfs-progs lsblk
|
||||
run rm -rf usr/share/apk var/cache/apk
|
||||
run . /etc/os-release \
|
||||
&& wget -O- https://dl-cdn.alpinelinux.org/alpine/v${VERSION_ID%.*}/releases/x86_64/alpine-minirootfs-${VERSION_ID}-x86_64.tar.gz |tar zxv
|
||||
|
||||
copy --from=build /go/bin/init .
|
||||
run apk add --no-cache --update -p . musl coreutils \
|
||||
lvm2 lvm2-extra lvm2-dmeventd udev cryptsetup \
|
||||
e2fsprogs lsblk openssh-server \
|
||||
&& rm -rf usr/share/apk var/cache/apk etc/motd
|
||||
|
||||
copy etc/sshd_config etc/ssh/sshd_config
|
||||
|
||||
copy --from=rust /init init
|
||||
run cd bin && for cmd in init-version connect-boot bootstrap; do ln -s ../init $cmd; done
|
||||
|
||||
# check viability
|
||||
run chroot /layer /init hello
|
||||
run chroot . init-version
|
||||
|
||||
run find |cpio -H newc -o >/initrd
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
from alpine:3.19.0
|
||||
from alpine:3.22.0
|
||||
copy --from=initrd /initrd /
|
||||
entrypoint ["base64","/initrd"]
|
||||
|
5
Dockerfile.build
Normal file
5
Dockerfile.build
Normal file
@ -0,0 +1,5 @@
|
||||
from rust:1.77.1-alpine as rust
|
||||
|
||||
run apk add --no-cache musl-dev
|
||||
run apk add --no-cache musl lvm2 lvm2-extra lvm2-dmeventd udev cryptsetup e2fsprogs btrfs-progs lsblk
|
||||
|
2
Dockerfile.test
Normal file
2
Dockerfile.test
Normal file
@ -0,0 +1,2 @@
|
||||
from alpine:3.19.0
|
||||
run apk add --no-cache musl lvm2 lvm2-extra lvm2-dmeventd udev cryptsetup e2fsprogs btrfs-progs lsblk
|
@ -1,7 +1,6 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
@ -9,53 +8,14 @@ import (
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
yaml "gopkg.in/yaml.v2"
|
||||
"novit.tech/direktil/pkg/sysfs"
|
||||
|
||||
"novit.tech/direktil/pkg/config/apply"
|
||||
)
|
||||
|
||||
var loopOffset = 0
|
||||
|
||||
func bootV1() {
|
||||
log.Print("-- boot v1 --")
|
||||
|
||||
// find and mount /boot
|
||||
bootMatch := param("boot", "")
|
||||
bootMounted := false
|
||||
if bootMatch != "" {
|
||||
bootFS := param("boot.fs", "vfat")
|
||||
for i := 0; ; i++ {
|
||||
devNames := sysfs.DeviceByProperty("block", bootMatch)
|
||||
|
||||
if len(devNames) == 0 {
|
||||
if i > 30 {
|
||||
fatal("boot partition not found after 30s")
|
||||
}
|
||||
log.Print("boot partition not found, retrying")
|
||||
time.Sleep(1 * time.Second)
|
||||
continue
|
||||
}
|
||||
|
||||
devFile := filepath.Join("/dev", devNames[0])
|
||||
|
||||
log.Print("boot partition found: ", devFile)
|
||||
|
||||
mount(devFile, "/boot", bootFS, bootMountFlags, "")
|
||||
bootMounted = true
|
||||
break
|
||||
}
|
||||
} else {
|
||||
log.Print("Assuming /boot is already populated.")
|
||||
}
|
||||
|
||||
// load config
|
||||
cfgPath := param("config", "/boot/config.yaml")
|
||||
|
||||
layersDir = filepath.Join("/boot", bootVersion, "layers")
|
||||
applyConfig(cfgPath, bootMounted)
|
||||
|
||||
finalizeBoot()
|
||||
}
|
||||
|
||||
func applyConfig(cfgPath string, bootMounted bool) (cfg *configV1) {
|
||||
cfgBytes, err := os.ReadFile(cfgPath)
|
||||
if err != nil {
|
||||
@ -72,10 +32,10 @@ func applyConfig(cfgPath string, bootMounted bool) (cfg *configV1) {
|
||||
fatal("no layers configured!")
|
||||
}
|
||||
|
||||
log.Printf("wanted layers: %q", cfg.Layers)
|
||||
|
||||
layersInMemory := paramBool("layers-in-mem", false)
|
||||
|
||||
log.Info().Strs("layers", cfg.Layers).Bool("in-memory", layersInMemory).Msg("mounting layers")
|
||||
|
||||
const layersInMemDir = "/layers-in-mem"
|
||||
if layersInMemory {
|
||||
mkdir(layersInMemDir, 0700)
|
||||
@ -84,6 +44,8 @@ func applyConfig(cfgPath string, bootMounted bool) (cfg *configV1) {
|
||||
|
||||
lowers := make([]string, len(cfg.Layers))
|
||||
for i, layer := range cfg.Layers {
|
||||
log := log.With().Str("layer", layer).Logger()
|
||||
|
||||
path := layerPath(layer)
|
||||
|
||||
info, err := os.Stat(path)
|
||||
@ -91,10 +53,10 @@ func applyConfig(cfgPath string, bootMounted bool) (cfg *configV1) {
|
||||
fatal(err)
|
||||
}
|
||||
|
||||
log.Printf("layer %s found (%d bytes)", layer, info.Size())
|
||||
log.Info().Int64("size", info.Size()).Msg("layer found")
|
||||
|
||||
if layersInMemory {
|
||||
log.Print(" copying to memory...")
|
||||
log.Info().Msg("copying to memory")
|
||||
targetPath := filepath.Join(layersInMemDir, layer)
|
||||
cp(path, targetPath)
|
||||
path = targetPath
|
||||
@ -126,7 +88,7 @@ func applyConfig(cfgPath string, bootMounted bool) (cfg *configV1) {
|
||||
if bootMounted {
|
||||
if layersInMemory {
|
||||
if err := syscall.Unmount("/boot", 0); err != nil {
|
||||
log.Print("WARNING: failed to unmount /boot: ", err)
|
||||
log.Warn().Err(err).Msg("failed to unmount /boot")
|
||||
time.Sleep(2 * time.Second)
|
||||
}
|
||||
|
||||
@ -135,74 +97,44 @@ func applyConfig(cfgPath string, bootMounted bool) (cfg *configV1) {
|
||||
}
|
||||
}
|
||||
|
||||
// - write configuration
|
||||
log.Print("writing /config.yaml")
|
||||
if err := os.WriteFile("/system/config.yaml", cfgBytes, 0600); err != nil {
|
||||
fatal("failed: ", err)
|
||||
}
|
||||
|
||||
// - write files
|
||||
for _, fileDef := range cfg.Files {
|
||||
log.Print("writing ", fileDef.Path)
|
||||
|
||||
filePath := filepath.Join("/system", fileDef.Path)
|
||||
|
||||
if err := os.MkdirAll(filepath.Dir(filePath), 0755); err != nil {
|
||||
log.Printf("failed to create dir %s: %v", filepath.Dir(fileDef.Path), err)
|
||||
}
|
||||
|
||||
mode := fileDef.Mode
|
||||
if mode == 0 {
|
||||
mode = 0644
|
||||
}
|
||||
|
||||
err = os.WriteFile(filePath, []byte(fileDef.Content), mode)
|
||||
if err != nil {
|
||||
fatalf("failed to write %s: %v", fileDef.Path, err)
|
||||
}
|
||||
}
|
||||
apply.Files(cfg.Files, "/system")
|
||||
|
||||
// - groups
|
||||
for _, group := range cfg.Groups {
|
||||
log.Print("creating group ", group.Name)
|
||||
logEvt := log.Info().Str("group", group.Name)
|
||||
|
||||
opts := make([]string, 0)
|
||||
opts = append(opts /* chroot */, "/system", "groupadd", "-r")
|
||||
if group.Gid != 0 {
|
||||
opts = append(opts, "-g", strconv.Itoa(group.Gid))
|
||||
logEvt.Int("gid", group.Gid)
|
||||
}
|
||||
opts = append(opts, group.Name)
|
||||
|
||||
logEvt.Msg("creating group")
|
||||
run("chroot", opts...)
|
||||
}
|
||||
|
||||
// - user
|
||||
for _, user := range cfg.Users {
|
||||
log.Print("creating user ", user.Name)
|
||||
logEvt := log.Info().Str("user", user.Name)
|
||||
|
||||
opts := make([]string, 0)
|
||||
opts = append(opts /* chroot */, "/system", "useradd", "-r")
|
||||
if user.Gid != 0 {
|
||||
opts = append(opts, "-g", strconv.Itoa(user.Gid))
|
||||
logEvt.Int("gid", user.Gid)
|
||||
}
|
||||
if user.Uid != 0 {
|
||||
opts = append(opts, "-u", strconv.Itoa(user.Uid))
|
||||
logEvt.Int("uid", user.Uid)
|
||||
}
|
||||
opts = append(opts, user.Name)
|
||||
|
||||
logEvt.Msg("creating user")
|
||||
run("chroot", opts...)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func finalizeBoot() {
|
||||
// clean zombies
|
||||
cleanZombies()
|
||||
|
||||
// switch root
|
||||
log.Print("switching root")
|
||||
err := syscall.Exec("/sbin/switch_root", []string{"switch_root",
|
||||
"-c", "/dev/console", "/system", "/sbin/init"}, os.Environ())
|
||||
fatal("switch_root failed: ", err)
|
||||
}
|
@ -6,10 +6,25 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
)
|
||||
|
||||
func askSecret(prompt string) []byte {
|
||||
stdinTTY.EchoOff()
|
||||
var (
|
||||
inputTTYs = new(sync.Map)
|
||||
askingSecret atomic.Bool
|
||||
)
|
||||
|
||||
func registerInput(in *tty) { inputTTYs.Store(in, in) }
|
||||
func unregiterInput(in *tty) { inputTTYs.Delete(in) }
|
||||
|
||||
func askSecret(prompt string) (s []byte) {
|
||||
err := func() (err error) {
|
||||
askingSecret.Store(true)
|
||||
defer askingSecret.Store(false)
|
||||
|
||||
inputTTYs.Range(func(k, v any) (con bool) { v.(*tty).EchoOff(); return true })
|
||||
defer inputTTYs.Range(func(k, v any) (con bool) { v.(*tty).Restore(); return true })
|
||||
|
||||
var (
|
||||
in io.Reader = stdin
|
||||
@ -23,24 +38,19 @@ func askSecret(prompt string) []byte {
|
||||
|
||||
out.Write([]byte(prompt + ": "))
|
||||
|
||||
if stdin != nil {
|
||||
stdout.HideInput()
|
||||
s, err = bufio.NewReader(in).ReadBytes('\n')
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
s, err := bufio.NewReader(in).ReadBytes('\n')
|
||||
|
||||
if stdin != nil {
|
||||
stdout.ShowInput()
|
||||
}
|
||||
|
||||
stdinTTY.Restore()
|
||||
fmt.Println()
|
||||
s = bytes.TrimRight(s, "\r\n")
|
||||
return
|
||||
}()
|
||||
|
||||
if err != nil {
|
||||
fatalf("failed to read from stdin: %v", err)
|
||||
}
|
||||
|
||||
fmt.Println()
|
||||
|
||||
s = bytes.TrimRight(s, "\r\n")
|
||||
return s
|
||||
return
|
||||
}
|
||||
|
8
auth.go
8
auth.go
@ -3,8 +3,8 @@ package main
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"log"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
"golang.org/x/crypto/ssh"
|
||||
|
||||
config "novit.tech/direktil/pkg/bootstrapconfig"
|
||||
@ -23,7 +23,7 @@ func localAuth() bool {
|
||||
}
|
||||
|
||||
if config.CheckPassword(auth.Password, sec) {
|
||||
log.Printf("login with auth %q", auth.Name)
|
||||
log.Info().Msgf("login with auth %q", auth.Name)
|
||||
return true
|
||||
}
|
||||
}
|
||||
@ -41,12 +41,12 @@ func sshCheckPubkey(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions,
|
||||
|
||||
allowedKey, _, _, _, err := ssh.ParseAuthorizedKey([]byte(auth.SSHKey))
|
||||
if err != nil {
|
||||
log.Printf("SSH pubkey for %q invalid: %v", auth.Name, auth.SSHKey)
|
||||
log.Warn().Err(err).Str("user", auth.Name).Str("key", auth.SSHKey).Msg("SSH public key is invalid")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if bytes.Equal(allowedKey.Marshal(), keyBytes) {
|
||||
log.Print("ssh: accepting public key for ", auth.Name)
|
||||
log.Info().Str("user", auth.Name).Msg("ssh: accepting public key")
|
||||
return &ssh.Permissions{
|
||||
Extensions: map[string]string{
|
||||
"pubkey-fp": ssh.FingerprintSHA256(key),
|
||||
|
33
boot-v2.go
33
boot-v2.go
@ -1,20 +1,21 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"os"
|
||||
"os/exec"
|
||||
"syscall"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
"gopkg.in/yaml.v3"
|
||||
|
||||
config "novit.tech/direktil/pkg/bootstrapconfig"
|
||||
)
|
||||
|
||||
func bootV2() {
|
||||
log.Print("-- boot v2 --")
|
||||
log.Info().Msg("-- boot v2 --")
|
||||
|
||||
kernelVersion := unameRelease()
|
||||
log.Print("Linux version ", kernelVersion)
|
||||
log.Info().Str("version", kernelVersion).Msg("Linux")
|
||||
|
||||
cfg := &config.Config{}
|
||||
|
||||
@ -32,15 +33,19 @@ func bootV2() {
|
||||
}
|
||||
}
|
||||
|
||||
log.Print("config loaded")
|
||||
log.Printf("\n\nanti-phishing code: %q\n", cfg.AntiPhishingCode)
|
||||
log.Info().Msg("config loaded")
|
||||
|
||||
if cfg.AntiPhishingCode != "" {
|
||||
log.Info().Str("anti-phishing-code", cfg.AntiPhishingCode).Send()
|
||||
}
|
||||
|
||||
auths = cfg.Auths
|
||||
|
||||
// mount kernel modules
|
||||
if cfg.Modules == "" {
|
||||
log.Print("NOT mounting modules (nothing specified)")
|
||||
log.Warn().Msg("NOT mounting modules (\"modules:\" not specified)")
|
||||
} else {
|
||||
log.Info().Str("from", cfg.Modules).Msg("mounting modules")
|
||||
mountSquahfs(cfg.Modules, "/modules")
|
||||
|
||||
modulesSourcePath := "/modules/lib/modules/" + kernelVersion
|
||||
@ -54,20 +59,18 @@ func bootV2() {
|
||||
}
|
||||
}
|
||||
|
||||
// load basic modules
|
||||
run("modprobe", "unix")
|
||||
|
||||
// devices init
|
||||
log.Info().Msg("starting udevd")
|
||||
err := exec.Command("udevd").Start()
|
||||
if err != nil {
|
||||
fatal("failed to start udevd: ", err)
|
||||
}
|
||||
|
||||
log.Print("udevadm triggers")
|
||||
log.Info().Msg("udevadm triggers")
|
||||
run("udevadm", "trigger", "-c", "add", "-t", "devices")
|
||||
run("udevadm", "trigger", "-c", "add", "-t", "subsystems")
|
||||
|
||||
log.Print("udevadm settle")
|
||||
log.Info().Msg("udevadm settle")
|
||||
run("udevadm", "settle")
|
||||
|
||||
// networks
|
||||
@ -91,3 +94,11 @@ func bootV2() {
|
||||
// finalize
|
||||
finalizeBoot()
|
||||
}
|
||||
|
||||
func finalizeBoot() {
|
||||
// switch root
|
||||
log.Info().Msg("switching root")
|
||||
err := syscall.Exec("/sbin/switch_root", []string{"switch_root",
|
||||
"-c", "/dev/console", "/system", "/sbin/init"}, os.Environ())
|
||||
fatal("switch_root failed: ", err)
|
||||
}
|
||||
|
37
bootstrap.go
37
bootstrap.go
@ -4,11 +4,13 @@ import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
|
||||
config "novit.tech/direktil/pkg/bootstrapconfig"
|
||||
)
|
||||
@ -27,14 +29,14 @@ func bootstrap(cfg *config.Config) {
|
||||
sysCfgPath := filepath.Join(baseDir, "config.yaml")
|
||||
|
||||
if _, err := os.Stat(sysCfgPath); os.IsNotExist(err) {
|
||||
log.Printf("bootstrap %q does not exist", bootVersion)
|
||||
log.Warn().Msgf("bootstrap %q does not exist", bootVersion)
|
||||
|
||||
seed := cfg.Bootstrap.Seed
|
||||
if seed == "" {
|
||||
fatalf("boostrap seed not defined, admin required")
|
||||
}
|
||||
|
||||
log.Printf("seeding bootstrap from %s", seed)
|
||||
log.Info().Str("from", seed).Msgf("seeding bootstrap")
|
||||
|
||||
err = os.MkdirAll(baseDir, 0700)
|
||||
if err != nil {
|
||||
@ -44,9 +46,18 @@ func bootstrap(cfg *config.Config) {
|
||||
bootstrapFile := filepath.Join(baseDir, "bootstrap.tar")
|
||||
|
||||
err = func() (err error) {
|
||||
resp, err := http.Get(seed)
|
||||
var resp *http.Response
|
||||
|
||||
start := time.Now()
|
||||
for time.Since(start) <= time.Minute {
|
||||
resp, err = http.Get(seed)
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
if err != nil {
|
||||
return
|
||||
return fmt.Errorf("failed to fetch bootstrap")
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
@ -72,7 +83,7 @@ func bootstrap(cfg *config.Config) {
|
||||
fatalf("seeding failed: %v", err)
|
||||
}
|
||||
|
||||
log.Print("unpacking bootstrap file")
|
||||
log.Info().Msg("unpacking bootstrap file")
|
||||
run("tar", "xvf", bootstrapFile, "-C", baseDir)
|
||||
}
|
||||
|
||||
@ -80,6 +91,13 @@ func bootstrap(cfg *config.Config) {
|
||||
layersOverride["modules"] = "/modules.sqfs"
|
||||
sysCfg := applyConfig(sysCfgPath, false)
|
||||
|
||||
// load requested modules
|
||||
for _, mod := range sysCfg.Modules {
|
||||
log.Info().Str("module", mod).Msg("loading module")
|
||||
run("modprobe", mod)
|
||||
}
|
||||
|
||||
// localy-generated assets dir
|
||||
localGenDir := filepath.Join(bsDir, "local-gen")
|
||||
|
||||
// vpns are v2+
|
||||
@ -89,7 +107,7 @@ func bootstrap(cfg *config.Config) {
|
||||
|
||||
// mounts are v2+
|
||||
for _, mount := range sysCfg.Mounts {
|
||||
log.Print("mount ", mount.Dev, " to system's ", mount.Path)
|
||||
log.Info().Str("source", mount.Dev).Str("target", mount.Path).Msg("mount")
|
||||
|
||||
path := filepath.Join("/system", mount.Path)
|
||||
|
||||
@ -108,15 +126,16 @@ func bootstrap(cfg *config.Config) {
|
||||
|
||||
// setup root user
|
||||
if ph := sysCfg.RootUser.PasswordHash; ph != "" {
|
||||
log.Print("setting root's password")
|
||||
log.Info().Msg("setting root's password")
|
||||
setUserPass("root", ph)
|
||||
}
|
||||
if ak := sysCfg.RootUser.AuthorizedKeys; len(ak) != 0 {
|
||||
log.Print("setting root's authorized keys")
|
||||
log.Info().Msg("setting root's authorized keys")
|
||||
setAuthorizedKeys(ak)
|
||||
}
|
||||
|
||||
// update-ca-certificates
|
||||
log.Info().Msg("updating CA certificates")
|
||||
run("chroot", "/system", "update-ca-certificates")
|
||||
}
|
||||
|
||||
|
27
build-init
Executable file
27
build-init
Executable file
@ -0,0 +1,27 @@
|
||||
set -ex
|
||||
|
||||
which podman &>/dev/null && docker=podman || docker=docker
|
||||
|
||||
mkdir -p empty
|
||||
$docker build -t nv-rs-build --network=host -f Dockerfile.build empty
|
||||
|
||||
case $1 in
|
||||
release)
|
||||
opts=--release
|
||||
bindir=target/release
|
||||
;;
|
||||
"")
|
||||
bindir=target/debug
|
||||
;;
|
||||
*)
|
||||
echo >&2 "invalid arg: $1"
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
$docker run --rm -i --net=host --user=$UID \
|
||||
nv-rs-build \
|
||||
cargo build $opts
|
||||
|
||||
mkdir -p dist
|
||||
cp $bindir/init dist/
|
9
build.rs
Normal file
9
build.rs
Normal file
@ -0,0 +1,9 @@
|
||||
use std::process::Command;
|
||||
fn main() {
|
||||
let output = Command::new("git")
|
||||
.args(&["rev-parse", "HEAD"])
|
||||
.output()
|
||||
.unwrap();
|
||||
let git_commit = String::from_utf8(output.stdout).unwrap();
|
||||
println!("cargo:rustc-env=GIT_COMMIT={}", git_commit);
|
||||
}
|
1
debug/bootstrap
Symbolic link
1
debug/bootstrap
Symbolic link
@ -0,0 +1 @@
|
||||
../target/debug/init
|
1
debug/connect-boot
Symbolic link
1
debug/connect-boot
Symbolic link
@ -0,0 +1 @@
|
||||
../target/debug/init
|
1
debug/init
Symbolic link
1
debug/init
Symbolic link
@ -0,0 +1 @@
|
||||
../target/debug/init
|
1
debug/init-version
Symbolic link
1
debug/init-version
Symbolic link
@ -0,0 +1 @@
|
||||
../target/debug/init
|
8
etc/sshd_config
Normal file
8
etc/sshd_config
Normal file
@ -0,0 +1,8 @@
|
||||
KbdInteractiveAuthentication no
|
||||
PasswordAuthentication no
|
||||
UsePAM no
|
||||
|
||||
PubkeyAuthentication yes
|
||||
|
||||
PermitRootLogin yes
|
||||
AllowUsers root
|
34
go.mod
34
go.mod
@ -1,29 +1,35 @@
|
||||
module novit.nc/direktil/initrd
|
||||
module novit.tech/direktil/initrd
|
||||
|
||||
require (
|
||||
github.com/creack/pty v1.1.24
|
||||
github.com/freddierice/go-losetup/v2 v2.0.1
|
||||
github.com/kr/pty v1.1.8
|
||||
github.com/jochenvg/go-udev v0.0.0-20240801134859-b65ed646224b
|
||||
github.com/pkg/term v1.1.0
|
||||
golang.org/x/crypto v0.16.0
|
||||
golang.org/x/sys v0.15.0
|
||||
golang.org/x/term v0.15.0
|
||||
golang.zx2c4.com/wireguard/wgctrl v0.0.0-20230429144221-925a1e7659e6
|
||||
github.com/rs/zerolog v1.34.0
|
||||
golang.org/x/crypto v0.38.0
|
||||
golang.org/x/sys v0.33.0
|
||||
golang.org/x/term v0.32.0
|
||||
golang.zx2c4.com/wireguard/wgctrl v0.0.0-20241231184526-a9ab2273dd10
|
||||
gopkg.in/yaml.v2 v2.4.0
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
novit.tech/direktil/pkg v0.0.0-20231217121409-827fa62f58aa
|
||||
novit.tech/direktil/pkg v0.0.0-20240415130406-0d2e181a4ed6
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/cavaliergopher/cpio v1.0.1 // indirect
|
||||
github.com/creack/pty v1.1.21 // indirect
|
||||
github.com/google/go-cmp v0.6.0 // indirect
|
||||
github.com/google/go-cmp v0.7.0 // indirect
|
||||
github.com/jkeiser/iter v0.0.0-20200628201005-c8aa0ae784d1 // indirect
|
||||
github.com/josharian/native v1.1.0 // indirect
|
||||
github.com/mattn/go-colorable v0.1.14 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/mdlayher/genetlink v1.3.2 // indirect
|
||||
github.com/mdlayher/netlink v1.7.2 // indirect
|
||||
github.com/mdlayher/socket v0.5.0 // indirect
|
||||
golang.org/x/net v0.19.0 // indirect
|
||||
golang.org/x/sync v0.5.0 // indirect
|
||||
golang.zx2c4.com/wireguard v0.0.0-20231211153847-12269c276173 // indirect
|
||||
github.com/mdlayher/socket v0.5.1 // indirect
|
||||
golang.org/x/net v0.40.0 // indirect
|
||||
golang.org/x/sync v0.14.0 // indirect
|
||||
golang.zx2c4.com/wireguard v0.0.0-20250521234502-f333402bd9cb // indirect
|
||||
)
|
||||
|
||||
go 1.21
|
||||
go 1.23.1
|
||||
|
||||
toolchain go1.24.3
|
||||
|
114
go.sum
114
go.sum
@ -1,93 +1,86 @@
|
||||
github.com/cavaliergopher/cpio v1.0.1 h1:KQFSeKmZhv0cr+kawA3a0xTQCU4QxXF1vhU7P7av2KM=
|
||||
github.com/cavaliergopher/cpio v1.0.1/go.mod h1:pBdaqQjnvXxdS/6CvNDwIANIFSP0xRKI16PX4xejRQc=
|
||||
github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7DoTY=
|
||||
github.com/creack/pty v1.1.18 h1:n56/Zwd5o6whRC5PMGretI4IdRLlmBXYNjScPaBgsbY=
|
||||
github.com/creack/pty v1.1.18/go.mod h1:MOBLtS5ELjhRRrroQr9kyvTxUAFNvYEK993ew/Vr4O4=
|
||||
github.com/creack/pty v1.1.21 h1:1/QdRyBaHHJP61QkWMXlOIBfsgdDeeKfK8SYVUWJKf0=
|
||||
github.com/creack/pty v1.1.21/go.mod h1:MOBLtS5ELjhRRrroQr9kyvTxUAFNvYEK993ew/Vr4O4=
|
||||
github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
|
||||
github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s=
|
||||
github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE=
|
||||
github.com/freddierice/go-losetup/v2 v2.0.1 h1:wPDx/Elu9nDV8y/CvIbEDz5Xi5Zo80y4h7MKbi3XaAI=
|
||||
github.com/freddierice/go-losetup/v2 v2.0.1/go.mod h1:TEyBrvlOelsPEhfWD5rutNXDmUszBXuFnwT1kIQF4J8=
|
||||
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
|
||||
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
||||
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/jkeiser/iter v0.0.0-20200628201005-c8aa0ae784d1 h1:smvLGU3obGU5kny71BtE/ibR0wIXRUiRFDmSn0Nxz1E=
|
||||
github.com/jkeiser/iter v0.0.0-20200628201005-c8aa0ae784d1/go.mod h1:fP/NdyhRVOv09PLRbVXrSqHhrfQypdZwgE2L4h2U5C8=
|
||||
github.com/jochenvg/go-udev v0.0.0-20240801134859-b65ed646224b h1:Pzf7tldbCVqwl3NnOnTamEWdh/rL41fsoYCn2HdHgRA=
|
||||
github.com/jochenvg/go-udev v0.0.0-20240801134859-b65ed646224b/go.mod h1:IBDUGq30U56w969YNPomhMbRje1GrhUsCh7tHdwgLXA=
|
||||
github.com/josharian/native v1.1.0 h1:uuaP0hAbW7Y4l0ZRQ6C9zfb7Mg1mbFKry/xzDAfmtLA=
|
||||
github.com/josharian/native v1.1.0/go.mod h1:7X/raswPFr05uY3HiLlYeyQntB6OO7E/d2Cu7qoaN2w=
|
||||
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
|
||||
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||
github.com/kr/pty v1.1.8 h1:AkaSdXYQOWeaO3neb8EM634ahkXXe3jYbVh/F9lq+GI=
|
||||
github.com/kr/pty v1.1.8/go.mod h1:O1sed60cT9XZ5uDucP5qwvh+TE3NnUj51EiZO/lmSfw=
|
||||
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
|
||||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||
github.com/mdlayher/genetlink v1.3.1 h1:roBiPnual+eqtRkKX2Jb8UQN5ZPWnhDCGj/wR6Jlz2w=
|
||||
github.com/mdlayher/genetlink v1.3.1/go.mod h1:uaIPxkWmGk753VVIzDtROxQ8+T+dkHqOI0vB1NA9S/Q=
|
||||
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
|
||||
github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
|
||||
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
|
||||
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
|
||||
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mdlayher/genetlink v1.3.2 h1:KdrNKe+CTu+IbZnm/GVUMXSqBBLqcGpRDa0xkQy56gw=
|
||||
github.com/mdlayher/genetlink v1.3.2/go.mod h1:tcC3pkCrPUGIKKsCsp0B3AdaaKuHtaxoJRz3cc+528o=
|
||||
github.com/mdlayher/netlink v1.7.1 h1:FdUaT/e33HjEXagwELR8R3/KL1Fq5x3G5jgHLp/BTmg=
|
||||
github.com/mdlayher/netlink v1.7.1/go.mod h1:nKO5CSjE/DJjVhk/TNp6vCE1ktVxEA8VEh8drhZzxsQ=
|
||||
github.com/mdlayher/netlink v1.7.2 h1:/UtM3ofJap7Vl4QWCPDGXY8d3GIY2UGSDbK+QWmY8/g=
|
||||
github.com/mdlayher/netlink v1.7.2/go.mod h1:xraEF7uJbxLhc5fpHL4cPe221LI2bdttWlU+ZGLfQSw=
|
||||
github.com/mdlayher/socket v0.4.0 h1:280wsy40IC9M9q1uPGcLBwXpcTQDtoGwVt+BNoITxIw=
|
||||
github.com/mdlayher/socket v0.4.0/go.mod h1:xxFqz5GRCUN3UEOm9CZqEJsAbe1C8OwSK46NlmWuVoc=
|
||||
github.com/mdlayher/socket v0.5.0 h1:ilICZmJcQz70vrWVes1MFera4jGiWNocSkykwwoy3XI=
|
||||
github.com/mdlayher/socket v0.5.0/go.mod h1:WkcBFfvyG8QENs5+hfQPl1X6Jpd2yeLIYgrGFmJiJxI=
|
||||
github.com/mdlayher/socket v0.5.1 h1:VZaqt6RkGkt2OE9l3GcC6nZkqD3xKeQLyfleW/uBcos=
|
||||
github.com/mdlayher/socket v0.5.1/go.mod h1:TjPLHI1UgwEv5J1B5q0zTZq12A/6H7nKmtTanQE37IQ=
|
||||
github.com/mikioh/ipaddr v0.0.0-20190404000644-d465c8ab6721 h1:RlZweED6sbSArvlE924+mUcZuXKLBHA35U7LN621Bws=
|
||||
github.com/mikioh/ipaddr v0.0.0-20190404000644-d465c8ab6721/go.mod h1:Ickgr2WtCLZ2MDGd4Gr0geeCH5HybhRJbonOgQpvSxc=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pkg/term v1.1.0 h1:xIAAdCMh3QIAy+5FrE8Ad8XoDhEU4ufwbaSozViP9kk=
|
||||
github.com/pkg/term v1.1.0/go.mod h1:E25nymQcrSllhX42Ok8MRm1+hyBdHY0dCeiKZ9jpNGw=
|
||||
github.com/ulikunitz/xz v0.5.6/go.mod h1:2bypXElzHzzJZwzH67Y6wb67pO62Rzfn7BSiF4ABRW8=
|
||||
github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
|
||||
github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0=
|
||||
github.com/rs/zerolog v1.31.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss=
|
||||
github.com/rs/zerolog v1.34.0 h1:k43nTLIwcTVQAncfCw4KZ2VY6ukYoZaBPNOE8txlOeY=
|
||||
github.com/rs/zerolog v1.34.0/go.mod h1:bJsvje4Z08ROH4Nhs5iH600c3IkWhwp44iRc54W6wYQ=
|
||||
github.com/ulikunitz/xz v0.5.11/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14=
|
||||
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/crypto v0.0.0-20220321153916-2c7772ba3064/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
|
||||
golang.org/x/crypto v0.5.0 h1:U/0M97KRkSFvyD/3FSmdP5W5swImpNgle/EHFhOsQPE=
|
||||
golang.org/x/crypto v0.5.0/go.mod h1:NK/OQwhpMQP3MwtdjgLlYHnH9ebylxKWv3e0fK+mkQU=
|
||||
golang.org/x/crypto v0.16.0 h1:mMMrFzRSCF0GvB7Ne27XVtVAaXLrPmgPC7/v0tkwHaY=
|
||||
golang.org/x/crypto v0.16.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4=
|
||||
golang.org/x/crypto v0.18.0/go.mod h1:R0j02AL6hcrfOiy9T4ZYp/rcWeMxM3L6QYxlOuEG1mg=
|
||||
golang.org/x/crypto v0.38.0 h1:jt+WWG8IZlBnVbomuhg2Mdq0+BBQaHbtqHEFEigjUV8=
|
||||
golang.org/x/crypto v0.38.0/go.mod h1:MvrbAqul58NNYPKnOra203SB9vpuZW0e+RRZV+Ggqjw=
|
||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
||||
golang.org/x/net v0.5.0 h1:GyT4nK/YDHSqa1c4753ouYCDajOYKTja9Xb/OHtgvSw=
|
||||
golang.org/x/net v0.5.0/go.mod h1:DivGGAXEgPSlEBzxGzZI+ZLohi+xUj054jfeKui00ws=
|
||||
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
|
||||
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
|
||||
golang.org/x/net v0.19.0 h1:zTwKpTd2XuCqf8huc7Fo2iSy+4RHPd10s4KzeTnVr1c=
|
||||
golang.org/x/net v0.19.0/go.mod h1:CfAk/cbD4CthTvqiEl8NpboMuiuOYsAr/7NOjZJtv1U=
|
||||
golang.org/x/net v0.40.0 h1:79Xs7wF06Gbdcg4kdCCIQArK11Z1hr5POQ6+fIYHNuY=
|
||||
golang.org/x/net v0.40.0/go.mod h1:y0hY0exeL2Pku80/zKK7tpntoX23cqL3Oa6njdgRtds=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o=
|
||||
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.5.0 h1:60k92dhOjHxJkrqnwsfl8KuaHbn/5dl0lUPUklKo3qE=
|
||||
golang.org/x/sync v0.5.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sync v0.14.0 h1:woo0S4Yywslg6hp4eUFjTVOyKt0RookbpAHG4c1HmhQ=
|
||||
golang.org/x/sync v0.14.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20200909081042-eff7692f9009/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.4.0 h1:Zr2JFtRQNX3BCZ8YtxRE9hNJYC8J6I1MVbMg6owUp18=
|
||||
golang.org/x/sys v0.4.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.15.0 h1:h48lPFYpsTvQJZF4EKyI4aLHaev3CxivZmv7yZig9pc=
|
||||
golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.16.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw=
|
||||
golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/term v0.4.0 h1:O7UWfv5+A2qiuulQk30kVinPoMtoIPeVaKLEgLpVkvg=
|
||||
golang.org/x/term v0.4.0/go.mod h1:9P2UbLfCdcvo3p/nzKvsmas4TnlujnuoV9hGgYzW1lQ=
|
||||
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
|
||||
golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
|
||||
golang.org/x/term v0.15.0 h1:y/Oo/a/q3IXu26lQgl04j/gjuBDOBlx7X6Om1j2CPW4=
|
||||
golang.org/x/term v0.15.0/go.mod h1:BDl952bC7+uMoWR75FIrCDx79TPU9oHkTZ9yRbYOrX0=
|
||||
golang.org/x/term v0.16.0/go.mod h1:yn7UURbUtPyrVJPGPq404EukNFxcm/foM+bV/bfcDsY=
|
||||
golang.org/x/term v0.32.0 h1:DR4lr0TjUs3epypdhTOkMmuF5CDFJ/8pOnbzMZPQ7bg=
|
||||
golang.org/x/term v0.32.0/go.mod h1:uZG1FhGx848Sqfsq4/DlJr3xGGsYMu/L5GW4abiaEPQ=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
|
||||
@ -97,26 +90,15 @@ golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtn
|
||||
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.zx2c4.com/wireguard v0.0.0-20220920152132-bb719d3a6e2c h1:Okh6a1xpnJslG9Mn84pId1Mn+Q8cvpo4HCeeFWHo0cA=
|
||||
golang.zx2c4.com/wireguard v0.0.0-20220920152132-bb719d3a6e2c/go.mod h1:enML0deDxY1ux+B6ANGiwtg0yAJi1rctkTpcHNAVPyg=
|
||||
golang.zx2c4.com/wireguard v0.0.0-20231022001213-2e0774f246fb h1:c5tyN8sSp8jSDxdCCDXVOpJwYXXhmTkNMt+g0zTSOic=
|
||||
golang.zx2c4.com/wireguard v0.0.0-20231022001213-2e0774f246fb/go.mod h1:tkCQ4FQXmpAgYVh++1cq16/dH4QJtmvpRv19DWGAHSA=
|
||||
golang.zx2c4.com/wireguard v0.0.0-20231211153847-12269c276173 h1:/jFs0duh4rdb8uIfPMv78iAJGcPKDeqAFnaLBropIC4=
|
||||
golang.zx2c4.com/wireguard v0.0.0-20231211153847-12269c276173/go.mod h1:tkCQ4FQXmpAgYVh++1cq16/dH4QJtmvpRv19DWGAHSA=
|
||||
golang.zx2c4.com/wireguard/wgctrl v0.0.0-20221104135756-97bc4ad4a1cb h1:9aqVcYEDHmSNb0uOWukxV5lHV09WqiSiCuhEgWNETLY=
|
||||
golang.zx2c4.com/wireguard/wgctrl v0.0.0-20221104135756-97bc4ad4a1cb/go.mod h1:mQqgjkW8GQQcJQsbBvK890TKqUK1DfKWkuBGbOkuMHQ=
|
||||
golang.zx2c4.com/wireguard/wgctrl v0.0.0-20230429144221-925a1e7659e6 h1:CawjfCvYQH2OU3/TnxLx97WDSUDRABfT18pCOYwc2GE=
|
||||
golang.zx2c4.com/wireguard/wgctrl v0.0.0-20230429144221-925a1e7659e6/go.mod h1:3rxYc4HtVcSG9gVaTs2GEBdehh+sYPOwKtyUWEOTb80=
|
||||
golang.zx2c4.com/wireguard v0.0.0-20250521234502-f333402bd9cb h1:whnFRlWMcXI9d+ZbWg+4sHnLp52d5yiIPUxMBSt4X9A=
|
||||
golang.zx2c4.com/wireguard v0.0.0-20250521234502-f333402bd9cb/go.mod h1:rpwXGsirqLqN2L0JDJQlwOboGHmptD5ZD6T2VmcqhTw=
|
||||
golang.zx2c4.com/wireguard/wgctrl v0.0.0-20241231184526-a9ab2273dd10 h1:3GDAcqdIg1ozBNLgPy4SLT84nfcBjr6rhGtXYtrkWLU=
|
||||
golang.zx2c4.com/wireguard/wgctrl v0.0.0-20241231184526-a9ab2273dd10/go.mod h1:T97yPqesLiNrOYxkwmhMI0ZIlJDm+p0PMR8eRVeR5tQ=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=
|
||||
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
|
||||
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
novit.nc/direktil/pkg v0.0.0-20220221171542-fd3ce3a1491b/go.mod h1:zwTVO6U0tXFEaga73megQIBK7yVIKZJVePaIh/UtdfU=
|
||||
novit.tech/direktil/pkg v0.0.0-20230201224712-5e39572dc50e h1:eQFbzcuB4wOSrnOhkcN30hFDCIack40VkIoqVRbWnWc=
|
||||
novit.tech/direktil/pkg v0.0.0-20230201224712-5e39572dc50e/go.mod h1:2Mir5x1eT/e295WeFGzzXa4siunKX4z+rmNPfVsXS0k=
|
||||
novit.tech/direktil/pkg v0.0.0-20231217121409-827fa62f58aa h1:eBk9nQTxIJU5cT8aJVjfRWiUd4sv8YV0kXALbSFOKdI=
|
||||
novit.tech/direktil/pkg v0.0.0-20231217121409-827fa62f58aa/go.mod h1:AYEEjNi7ljJG+V4F4LzxWntfbSs+KnNPO3kqvcEzIU4=
|
||||
novit.tech/direktil/pkg v0.0.0-20240415130406-0d2e181a4ed6 h1:D0TN5GyZ4d88ILpgVZgcZ62027lW8/LLnQSpQyN2yOw=
|
||||
novit.tech/direktil/pkg v0.0.0-20240415130406-0d2e181a4ed6/go.mod h1:zjezU6tELE880oYHs/WAauGBupKIEQQ7KqWTB69RW10=
|
||||
|
90
lvm.go
90
lvm.go
@ -3,15 +3,19 @@ package main
|
||||
import (
|
||||
"bytes"
|
||||
"io/fs"
|
||||
"log"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strconv"
|
||||
"syscall"
|
||||
|
||||
udev "github.com/jochenvg/go-udev"
|
||||
"github.com/rs/zerolog/log"
|
||||
|
||||
"novit.nc/direktil/initrd/lvm"
|
||||
config "novit.tech/direktil/pkg/bootstrapconfig"
|
||||
|
||||
"novit.tech/direktil/initrd/lvm"
|
||||
)
|
||||
|
||||
func sortedKeys[T any](m map[string]T) (keys []string) {
|
||||
@ -25,7 +29,7 @@ func sortedKeys[T any](m map[string]T) (keys []string) {
|
||||
|
||||
func setupLVM(cfg *config.Config) {
|
||||
if len(cfg.LVM) == 0 {
|
||||
log.Print("no LVM VG configured.")
|
||||
log.Info().Msg("no LVM VG configured.")
|
||||
return
|
||||
}
|
||||
|
||||
@ -75,53 +79,73 @@ func setupVG(vg config.LvmVG) {
|
||||
}
|
||||
}
|
||||
|
||||
log := log.With().Str("vg", vg.VG).Logger()
|
||||
|
||||
if devNeeded <= 0 {
|
||||
log.Print("LVM VG ", vg.VG, " has all its devices")
|
||||
log.Info().Msg("LVM VG has all its devices")
|
||||
return
|
||||
}
|
||||
|
||||
if vgExists {
|
||||
log.Printf("LVM VG %s misses %d devices", vg.VG, devNeeded)
|
||||
log.Info().Msgf("LVM VG misses %d devices", devNeeded)
|
||||
} else {
|
||||
log.Printf("LVM VG %s does not exists, creating", vg.VG)
|
||||
log.Info().Msg("LVM VG does not exists, creating")
|
||||
}
|
||||
|
||||
devNames := make([]NameAliases, 0)
|
||||
{
|
||||
devRefs := map[uint64]*NameAliases{}
|
||||
|
||||
enum := new(udev.Udev).NewEnumerate()
|
||||
enum.AddMatchSubsystem("block")
|
||||
|
||||
devs, err := enum.Devices()
|
||||
if err != nil {
|
||||
fatal("udev enumeration failed")
|
||||
}
|
||||
|
||||
for _, dev := range devs {
|
||||
num := dev.Devnum()
|
||||
|
||||
n := dev.PropertyValue("DEVNAME")
|
||||
idx := len(devNames)
|
||||
devNames = append(devNames, nameAlias(n))
|
||||
|
||||
ref := uint64(num.Major())<<8 | uint64(num.Minor())
|
||||
devRefs[ref] = &devNames[idx]
|
||||
}
|
||||
|
||||
devNames := make([]string, 0)
|
||||
err = filepath.Walk("/dev", func(n string, fi fs.FileInfo, err error) error {
|
||||
if fi.Mode().Type() == os.ModeDevice {
|
||||
devNames = append(devNames, n)
|
||||
stat := fi.Sys().(*syscall.Stat_t)
|
||||
ref := stat.Rdev
|
||||
if na := devRefs[ref]; na != nil {
|
||||
na.AddAlias(n)
|
||||
}
|
||||
}
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
fatalf("failed to walk /dev: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
devNames = filter(devNames, func(v string) bool {
|
||||
for _, pv := range pvs.PVs() {
|
||||
if v == pv.Name {
|
||||
return false
|
||||
for _, dev := range devNames {
|
||||
log.Info().Str("name", dev.Name).Any("aliases", dev.Aliases).Msg("found block device")
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
|
||||
m := regexpSelectN(vg.PVs.N, vg.PVs.Regexps, devNames)
|
||||
if len(m) == 0 {
|
||||
log.Printf("no devices match the regexps %v", vg.PVs.Regexps)
|
||||
for _, d := range devNames {
|
||||
log.Print("- ", d)
|
||||
}
|
||||
|
||||
log.Error().Strs("regexps", vg.PVs.Regexps).Msg("no device match the regexps")
|
||||
fatalf("failed to setup VG %s", vg.VG)
|
||||
}
|
||||
|
||||
if vgExists {
|
||||
log.Print("- extending vg to ", m)
|
||||
log.Info().Strs("devices", m).Msg("LVM VG: extending")
|
||||
run("vgextend", append([]string{vg.VG}, m...)...)
|
||||
devNeeded -= len(m)
|
||||
} else {
|
||||
log.Print("- creating vg with devices ", m)
|
||||
log.Info().Strs("devices", m).Msg("LVM VG: creating")
|
||||
run("vgcreate", append([]string{vg.VG}, m...)...)
|
||||
devNeeded -= len(m)
|
||||
}
|
||||
@ -142,17 +166,17 @@ func setupLVs(vg config.LvmVG, createdDevs map[string]string) {
|
||||
|
||||
defaults := vg.Defaults
|
||||
|
||||
for _, lv := range vg.LVs {
|
||||
lvKey := vg.VG + "/" + lv.Name
|
||||
for idx, lv := range vg.LVs {
|
||||
log := log.With().Str("vg", vg.VG).Str("lv", lv.Name).Logger()
|
||||
|
||||
if contains(lvs, func(v lvm.LV) bool {
|
||||
return v.VGName == vg.VG && v.Name == lv.Name
|
||||
}) {
|
||||
log.Printf("LV %s exists", lvKey)
|
||||
log.Info().Msg("LV exists")
|
||||
continue
|
||||
}
|
||||
|
||||
log.Printf("creating LV %s", lvKey)
|
||||
log.Info().Msg("LV does not exist")
|
||||
|
||||
if lv.Raid == nil {
|
||||
lv.Raid = defaults.Raid
|
||||
@ -161,7 +185,7 @@ func setupLVs(vg config.LvmVG, createdDevs map[string]string) {
|
||||
args := make([]string, 0)
|
||||
|
||||
if lv.Name == "" {
|
||||
fatalf("LV has no name")
|
||||
fatalf("LV[%d] has no name", idx)
|
||||
}
|
||||
args = append(args, vg.VG, "--name", lv.Name)
|
||||
|
||||
@ -184,7 +208,7 @@ func setupLVs(vg config.LvmVG, createdDevs map[string]string) {
|
||||
}
|
||||
}
|
||||
|
||||
log.Print("lvcreate args: ", args)
|
||||
log.Info().Strs("args", args).Msg("LV: creating")
|
||||
run("lvcreate", args...)
|
||||
|
||||
dev := "/dev/" + vg.VG + "/" + lv.Name
|
||||
@ -286,12 +310,12 @@ func setupCrypt(devSpecs []config.CryptDev, createdDevs map[string]string) {
|
||||
}
|
||||
|
||||
if !eq {
|
||||
log.Print("passwords don't match")
|
||||
log.Error().Msg("passwords don't match")
|
||||
goto retry
|
||||
}
|
||||
}
|
||||
|
||||
log.Print("formatting encrypted device ", dev)
|
||||
log.Info().Str("dev", dev).Msg("formatting encrypted device")
|
||||
cmd := exec.Command("cryptsetup", "luksFormat", dev, "--key-file=-")
|
||||
cmd.Stdin = bytes.NewBuffer(password)
|
||||
cmd.Stdout = stdout
|
||||
@ -312,7 +336,7 @@ func setupCrypt(devSpecs []config.CryptDev, createdDevs map[string]string) {
|
||||
}
|
||||
}
|
||||
|
||||
log.Print("openning encrypted device ", name, " from ", dev)
|
||||
log.Info().Str("name", name).Str("dev", dev).Msg("openning encrypted device")
|
||||
cmd := exec.Command("cryptsetup", "open", dev, name, "--key-file=-")
|
||||
cmd.Stdin = bytes.NewBuffer(password)
|
||||
cmd.Stdout = stdout
|
||||
@ -364,7 +388,7 @@ func devInitialized(dev string) bool {
|
||||
|
||||
func setupFS(dev, fs string) {
|
||||
if devInitialized(dev) {
|
||||
log.Print("device ", dev, " already formatted")
|
||||
log.Info().Str("dev", dev).Msg("device already formatted")
|
||||
return
|
||||
}
|
||||
|
||||
@ -372,7 +396,7 @@ func setupFS(dev, fs string) {
|
||||
fs = "ext4"
|
||||
}
|
||||
|
||||
log.Print("formatting ", dev, " (", fs, ")")
|
||||
log.Info().Str("dev", dev).Str("fs", fs).Msg("formatting device")
|
||||
args := make([]string, 0)
|
||||
|
||||
switch fs {
|
||||
|
56
main.go
56
main.go
@ -3,7 +3,6 @@ package main
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
@ -12,10 +11,12 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/pkg/term/termios"
|
||||
"github.com/rs/zerolog"
|
||||
"github.com/rs/zerolog/log"
|
||||
"golang.org/x/term"
|
||||
|
||||
"novit.nc/direktil/initrd/colorio"
|
||||
"novit.nc/direktil/initrd/shio"
|
||||
"novit.tech/direktil/initrd/colorio"
|
||||
"novit.tech/direktil/initrd/shio"
|
||||
)
|
||||
|
||||
const (
|
||||
@ -41,11 +42,15 @@ func newPipe() (io.ReadCloser, io.WriteCloser) {
|
||||
}
|
||||
|
||||
func main() {
|
||||
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
|
||||
|
||||
registerInput(newTTY(os.Stdin.Fd()))
|
||||
|
||||
switch baseName := filepath.Base(os.Args[0]); baseName {
|
||||
case "init":
|
||||
runInit()
|
||||
default:
|
||||
log.Fatal("unknown sub-command: ", baseName)
|
||||
log.Fatal().Msgf("unknown sub-command: %q", baseName)
|
||||
}
|
||||
}
|
||||
|
||||
@ -57,18 +62,19 @@ func runInit() {
|
||||
|
||||
runtime.LockOSThread()
|
||||
|
||||
if pid := os.Getpid(); pid != 1 {
|
||||
log.Fatal("init must be PID 1, not ", pid)
|
||||
}
|
||||
|
||||
// move log to shio
|
||||
go io.Copy(os.Stdout, stdout.NewReader())
|
||||
log.SetOutput(stderr)
|
||||
log.Logger = log.Output(zerolog.ConsoleWriter{Out: stderr})
|
||||
|
||||
// check the PID is 1
|
||||
if pid := os.Getpid(); pid != 1 {
|
||||
log.Fatal().Int("pid", pid).Msg("init must be PID 1")
|
||||
}
|
||||
|
||||
// copy os.Stdin to my stdin pipe
|
||||
go io.Copy(stdinPipe, os.Stdin)
|
||||
|
||||
log.Print("Welcome to ", VERSION)
|
||||
log.Info().Msg("Welcome to " + VERSION)
|
||||
|
||||
// essential mounts
|
||||
mount("none", "/proc", "proc", 0, "")
|
||||
@ -78,17 +84,14 @@ func runInit() {
|
||||
|
||||
// get the "boot version"
|
||||
bootVersion = param("version", "current")
|
||||
log.Printf("booting system %q", bootVersion)
|
||||
log.Info().Msgf("booting system %q", bootVersion)
|
||||
|
||||
os.Setenv("PATH", "/usr/bin:/bin:/usr/sbin:/sbin")
|
||||
|
||||
_, err := os.Stat("/config.yaml")
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
bootV1()
|
||||
return
|
||||
}
|
||||
fatal("stat failed: ", err)
|
||||
log.Error().Err(err).Msg("config not found")
|
||||
fatal()
|
||||
}
|
||||
|
||||
bootV2()
|
||||
@ -107,19 +110,20 @@ func layerPath(name string) string {
|
||||
}
|
||||
|
||||
func fatal(v ...interface{}) {
|
||||
log.Print("*** FATAL ***")
|
||||
log.Print(v...)
|
||||
log.Error().Msg("*** FATAL ***")
|
||||
log.Error().Msg(fmt.Sprint(v...))
|
||||
die()
|
||||
}
|
||||
|
||||
func fatalf(pattern string, v ...interface{}) {
|
||||
log.Print("*** FATAL ***")
|
||||
log.Printf(pattern, v...)
|
||||
log.Error().Msg("*** FATAL ***")
|
||||
log.Error().Msgf(pattern, v...)
|
||||
die()
|
||||
}
|
||||
|
||||
func die() {
|
||||
log.SetOutput(os.Stderr)
|
||||
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
|
||||
|
||||
stdout.Close()
|
||||
stdin.Close()
|
||||
stdinPipe.Close()
|
||||
@ -138,13 +142,13 @@ mainLoop:
|
||||
deadline := time.Now().Add(time.Minute)
|
||||
os.Stdin.SetReadDeadline(deadline)
|
||||
|
||||
termios.Tcflush(os.Stdin.Fd(), termios.TCIFLUSH)
|
||||
term.MakeRaw(int(os.Stdin.Fd()))
|
||||
termios.Tcflush(os.Stdin.Fd(), termios.TCIFLUSH)
|
||||
|
||||
b := make([]byte, 1)
|
||||
_, err := os.Stdin.Read(b)
|
||||
if err != nil {
|
||||
log.Print("failed to read from stdin: ", err)
|
||||
log.Error().Err(err).Msg("failed to read from stdin")
|
||||
time.Sleep(5 * time.Second)
|
||||
syscall.Reboot(syscall.LINUX_REBOOT_CMD_RESTART)
|
||||
}
|
||||
@ -184,10 +188,10 @@ mainLoop:
|
||||
}
|
||||
continue mainLoop
|
||||
}
|
||||
log.Print("failed to find a shell!")
|
||||
log.Error().Msg("failed to find a shell!")
|
||||
|
||||
default:
|
||||
log.Printf("unknown choice: %q", string(b))
|
||||
log.Error().Msgf("unknown choice: %q", string(b))
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -212,7 +216,7 @@ func mount(source, target, fstype string, flags uintptr, data string) {
|
||||
if err := syscall.Mount(source, target, fstype, flags, data); err != nil {
|
||||
fatalf("mount %q %q -t %q -o %q failed: %v", source, target, fstype, data, err)
|
||||
}
|
||||
log.Printf("mounted %q", target)
|
||||
log.Info().Str("target", target).Msg("mounted")
|
||||
}
|
||||
|
||||
func cp(srcPath, dstPath string) {
|
||||
|
15
modd.conf
15
modd.conf
@ -1,13 +1,14 @@
|
||||
modd.conf {}
|
||||
|
||||
go.??? **/*.go {
|
||||
prep: go test ./...
|
||||
prep: mkdir -p dist
|
||||
prep: go build -o dist/ ./tools/...
|
||||
**/*.rs Cargo.* {
|
||||
prep: cargo test
|
||||
prep: cargo build
|
||||
prep: debug/init-version
|
||||
}
|
||||
|
||||
dist/init Dockerfile {
|
||||
prep: docker build -t novit-initrd-gen .
|
||||
prep: docker run novit-initrd-gen |base64 -d >dist/initrd.new
|
||||
target/debug/init Dockerfile {
|
||||
prep: docker build --network host -t novit-initrd-gen .
|
||||
prep: docker run --net=host --rm novit-initrd-gen |base64 -d >dist/initrd.new
|
||||
prep: mv dist/initrd.new dist/initrd
|
||||
prep: ls -sh dist/initrd
|
||||
}
|
||||
|
62
network.go
62
network.go
@ -1,47 +1,58 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net"
|
||||
"os/exec"
|
||||
"strings"
|
||||
|
||||
udev "github.com/jochenvg/go-udev"
|
||||
"github.com/rs/zerolog/log"
|
||||
|
||||
config "novit.tech/direktil/pkg/bootstrapconfig"
|
||||
)
|
||||
|
||||
func setupNetworks(cfg *config.Config) {
|
||||
if len(cfg.Networks) == 0 {
|
||||
log.Print("no networks configured.")
|
||||
log.Info().Msg("no networks configured.")
|
||||
return
|
||||
}
|
||||
|
||||
ifNames := make([]string, 0)
|
||||
{
|
||||
ifaces, err := net.Interfaces()
|
||||
if err != nil {
|
||||
fatal("failed")
|
||||
type Iface struct {
|
||||
Name string
|
||||
AliasOf string
|
||||
}
|
||||
for _, iface := range ifaces {
|
||||
ifNames = append(ifNames, iface.Name)
|
||||
|
||||
ifaces := make([]NameAliases, 0)
|
||||
{
|
||||
enum := new(udev.Udev).NewEnumerate()
|
||||
enum.AddMatchSubsystem("net")
|
||||
|
||||
devs, err := enum.Devices()
|
||||
if err != nil {
|
||||
fatal("udev enumeration failed")
|
||||
}
|
||||
|
||||
for _, dev := range devs {
|
||||
iface := nameAliases(dev.Sysname(),
|
||||
dev.PropertyValue("INTERFACE"),
|
||||
dev.PropertyValue("ID_NET_NAME"),
|
||||
dev.PropertyValue("ID_NET_NAME_PATH"),
|
||||
dev.PropertyValue("ID_NET_NAME_MAC"),
|
||||
dev.PropertyValue("ID_NET_NAME_SLOT"),
|
||||
)
|
||||
log.Info().Str("name", iface.Name).Any("aliases", iface.Aliases).Msg("found network device")
|
||||
ifaces = append(ifaces, iface)
|
||||
}
|
||||
}
|
||||
|
||||
assigned := map[string]bool{}
|
||||
|
||||
for _, network := range cfg.Networks {
|
||||
log.Print("setting up network ", network.Name)
|
||||
log := log.With().Str("network", network.Name).Logger()
|
||||
log.Info().Msg("setting up network")
|
||||
|
||||
// compute available names
|
||||
if len(assigned) != 0 {
|
||||
newNames := make([]string, 0, len(ifNames))
|
||||
for _, n := range ifNames {
|
||||
if assigned[n] {
|
||||
continue
|
||||
}
|
||||
newNames = append(newNames, n)
|
||||
}
|
||||
ifNames = newNames
|
||||
}
|
||||
unassigned := filter(ifaces, func(iface NameAliases) bool {
|
||||
return !assigned[iface.Name]
|
||||
})
|
||||
|
||||
// assign envvars
|
||||
envvars := make([]string, 0, 1+len(network.Interfaces))
|
||||
@ -51,19 +62,20 @@ func setupNetworks(cfg *config.Config) {
|
||||
envvar := new(strings.Builder)
|
||||
envvar.WriteString(match.Var)
|
||||
envvar.WriteByte('=')
|
||||
for i, m := range regexpSelectN(match.N, match.Regexps, unassigned) {
|
||||
assigned[m] = true
|
||||
|
||||
for i, m := range regexpSelectN(match.N, match.Regexps, ifNames) {
|
||||
if i != 0 {
|
||||
envvar.WriteByte(' ')
|
||||
}
|
||||
envvar.WriteString(m)
|
||||
assigned[m] = true
|
||||
}
|
||||
|
||||
log.Print("- ", envvar)
|
||||
envvars = append(envvars, envvar.String())
|
||||
}
|
||||
|
||||
log.Info().Strs("env", envvars).Msg("running script")
|
||||
|
||||
cmd := exec.Command("/bin/sh", "-c", network.Script)
|
||||
cmd.Env = envvars
|
||||
cmd.Stdout = stdout
|
||||
|
50
regexp.go
50
regexp.go
@ -1,36 +1,62 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"regexp"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
func regexpSelectN(n int, regexps []string, names []string) (matches []string) {
|
||||
if n <= 0 {
|
||||
matches = make([]string, 0)
|
||||
} else {
|
||||
matches = make([]string, 0, n)
|
||||
type NameAliases struct {
|
||||
Name string
|
||||
Aliases []string
|
||||
}
|
||||
|
||||
func nameAlias(name string) NameAliases {
|
||||
return NameAliases{Name: name, Aliases: []string{name}}
|
||||
}
|
||||
func nameAliases(name string, aliases ...string) NameAliases {
|
||||
na := NameAliases{Name: name, Aliases: make([]string, 0, len(aliases)+1)}
|
||||
na.Aliases = append(na.Aliases, name)
|
||||
for _, alias := range aliases {
|
||||
na.AddAlias(alias)
|
||||
}
|
||||
|
||||
return na
|
||||
}
|
||||
func (na *NameAliases) AddAlias(alias string) {
|
||||
if alias == "" {
|
||||
return
|
||||
}
|
||||
if contains(na.Aliases, func(s string) bool { return s == alias }) {
|
||||
return
|
||||
}
|
||||
na.Aliases = append(na.Aliases, alias)
|
||||
}
|
||||
|
||||
func regexpSelectN(n int, regexps []string, nameAliases []NameAliases) (matches []string) {
|
||||
matches = make([]string, 0)
|
||||
|
||||
res := make([]*regexp.Regexp, 0, len(regexps))
|
||||
for _, reStr := range regexps {
|
||||
re, err := regexp.Compile(reStr)
|
||||
if err != nil {
|
||||
log.Printf("warning: invalid regexp ignored: %q: %v", reStr, err)
|
||||
log.Warn().Err(err).Str("regexp", reStr).Msg("invalid regexp, ignored")
|
||||
continue
|
||||
}
|
||||
res = append(res, re)
|
||||
}
|
||||
|
||||
namesLoop:
|
||||
for _, name := range names {
|
||||
nameAliasesLoop:
|
||||
for _, item := range nameAliases {
|
||||
if len(matches) == n {
|
||||
break
|
||||
}
|
||||
for _, re := range res {
|
||||
if re.MatchString(name) {
|
||||
matches = append(matches, name)
|
||||
continue namesLoop
|
||||
for _, alias := range item.Aliases {
|
||||
if re.MatchString(alias) {
|
||||
matches = append(matches, item.Name)
|
||||
continue nameAliasesLoop
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
2
run-docker
Executable file
2
run-docker
Executable file
@ -0,0 +1,2 @@
|
||||
docker build -t nv-initrd-test -f Dockerfile.test empty
|
||||
docker run -d --name nv-initrd-test -it --privileged -v $PWD:/src --workdir /src/test-initrd nv-initrd-test
|
@ -10,7 +10,8 @@ if ! [ -e $disk2 ]; then
|
||||
qemu-img create -f qcow2 $disk2 10G
|
||||
fi
|
||||
|
||||
exec qemu-system-x86_64 -pidfile qemu.pid -kernel test-kernel -initrd test-initrd.cpio \
|
||||
exec qemu-system-x86_64 -pidfile qemu.pid \
|
||||
-kernel test-kernel -initrd test-initrd.cpio \
|
||||
-smp 2 -m 2048 \
|
||||
-netdev bridge,br=novit,id=eth0 -device virtio-net-pci,netdev=eth0 \
|
||||
-drive file=$disk1,if=virtio \
|
||||
|
@ -5,7 +5,7 @@ import (
|
||||
"io"
|
||||
"sync"
|
||||
|
||||
"novit.nc/direktil/initrd/colorio"
|
||||
"novit.tech/direktil/initrd/colorio"
|
||||
)
|
||||
|
||||
type ShIO struct {
|
||||
|
@ -8,7 +8,7 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
func ExampleOutput() {
|
||||
func Example_output() {
|
||||
done := false
|
||||
defer func() { done = true }()
|
||||
go func() {
|
||||
|
1
src/bootstrap.rs
Normal file
1
src/bootstrap.rs
Normal file
@ -0,0 +1 @@
|
||||
pub mod config;
|
158
src/bootstrap/config.rs
Normal file
158
src/bootstrap/config.rs
Normal file
@ -0,0 +1,158 @@
|
||||
#[derive(Debug, serde::Deserialize, serde::Serialize)]
|
||||
pub struct Config {
|
||||
pub anti_phishing_code: String,
|
||||
|
||||
pub keymap: Option<String>,
|
||||
pub modules: Option<String>,
|
||||
|
||||
pub auths: Vec<Auth>,
|
||||
|
||||
pub networks: Vec<Network>,
|
||||
|
||||
#[serde(default)]
|
||||
pub ssh: SSHServer,
|
||||
|
||||
#[serde(default)]
|
||||
pub pre_lvm_crypt: Vec<CryptDev>,
|
||||
#[serde(default)]
|
||||
pub lvm: Vec<LvmVG>,
|
||||
#[serde(default)]
|
||||
pub crypt: Vec<CryptDev>,
|
||||
|
||||
pub bootstrap: Bootstrap,
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Deserialize, serde::Serialize)]
|
||||
pub struct Auth {
|
||||
pub name: String,
|
||||
#[serde(rename = "sshKey")]
|
||||
pub ssh_key: String,
|
||||
pub password: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Deserialize, serde::Serialize)]
|
||||
pub struct Network {
|
||||
pub name: String,
|
||||
pub interfaces: Vec<NetworkInterface>,
|
||||
pub script: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Deserialize, serde::Serialize)]
|
||||
pub struct NetworkInterface {
|
||||
pub var: String,
|
||||
pub n: usize,
|
||||
pub regexps: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Deserialize, serde::Serialize)]
|
||||
pub struct SSHServer {
|
||||
pub listen: String,
|
||||
pub keys: SSHKeys,
|
||||
}
|
||||
impl Default for SSHServer {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
listen: "[::]:22".to_string(),
|
||||
keys: SSHKeys::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Deserialize, serde::Serialize)]
|
||||
pub struct SSHKeys {
|
||||
dsa: Option<String>,
|
||||
rsa: Option<String>,
|
||||
ecdsa: Option<String>,
|
||||
ed25519: Option<String>,
|
||||
}
|
||||
impl SSHKeys {
|
||||
pub fn iter(&self) -> impl Iterator<Item = &str> {
|
||||
[
|
||||
self.dsa.iter(),
|
||||
self.rsa.iter(),
|
||||
self.ecdsa.iter(),
|
||||
self.ed25519.iter(),
|
||||
]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(String::as_str)
|
||||
}
|
||||
}
|
||||
impl Default for SSHKeys {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
dsa: Some("id_dsa".to_string()),
|
||||
rsa: Some("id_rsa".to_string()),
|
||||
ecdsa: Some("id_ecdsa".to_string()),
|
||||
ed25519: Some("id_ed25519".to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Deserialize, serde::Serialize)]
|
||||
pub struct LvmVG {
|
||||
vg: String,
|
||||
pvs: LvmPV,
|
||||
|
||||
#[serde(default)]
|
||||
defaults: LvmLVDefaults,
|
||||
|
||||
lvs: Vec<LvmLV>,
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Deserialize, serde::Serialize)]
|
||||
pub struct LvmLVDefaults {
|
||||
#[serde(default = "default_fs")]
|
||||
fs: String,
|
||||
raid: Option<Raid>,
|
||||
}
|
||||
impl Default for LvmLVDefaults {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
fs: default_fs(),
|
||||
raid: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn default_fs() -> String {
|
||||
"ext4".to_string()
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Deserialize, serde::Serialize)]
|
||||
pub struct LvmLV {
|
||||
name: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
fs: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
raid: Option<Raid>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
size: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
extents: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Deserialize, serde::Serialize)]
|
||||
pub struct LvmPV {
|
||||
n: i16,
|
||||
regexps: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Deserialize, serde::Serialize)]
|
||||
pub struct CryptDev {
|
||||
name: String,
|
||||
dev: Option<String>,
|
||||
prefix: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Deserialize, serde::Serialize)]
|
||||
pub struct Raid {
|
||||
mirrors: Option<u8>,
|
||||
stripes: Option<u8>,
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Deserialize, serde::Serialize)]
|
||||
pub struct Bootstrap {
|
||||
dev: String,
|
||||
seed: String,
|
||||
}
|
4
src/cmd.rs
Normal file
4
src/cmd.rs
Normal file
@ -0,0 +1,4 @@
|
||||
pub mod bootstrap;
|
||||
pub mod connect_boot;
|
||||
pub mod init;
|
||||
pub mod version;
|
0
src/cmd/bootstrap.rs
Normal file
0
src/cmd/bootstrap.rs
Normal file
0
src/cmd/connect_boot.rs
Normal file
0
src/cmd/connect_boot.rs
Normal file
213
src/cmd/init.rs
Normal file
213
src/cmd/init.rs
Normal file
@ -0,0 +1,213 @@
|
||||
use eyre::{format_err, Result};
|
||||
use log::{error, info, warn};
|
||||
use std::os::unix::fs::symlink;
|
||||
use std::{fs, io, process::Command};
|
||||
|
||||
use crate::{bootstrap::config::Config, cmd::version::version_string};
|
||||
|
||||
mod networks;
|
||||
mod sshd;
|
||||
|
||||
pub fn run() -> Result<()> {
|
||||
if std::process::id() != 1 {
|
||||
return Err(format_err!(
|
||||
"init must run as PID 1, not {}",
|
||||
std::process::id()
|
||||
));
|
||||
}
|
||||
|
||||
info!("Welcome to {}", version_string());
|
||||
|
||||
let uname = nix::sys::utsname::uname()?;
|
||||
let kernel_version = uname.release().to_string_lossy();
|
||||
info!("Linux version {kernel_version}");
|
||||
|
||||
let cfg: Config = retry(|| {
|
||||
let cfg = fs::read("config.yaml").map_err(|e| format_err!("failed to read config: {e}"))?;
|
||||
serde_yaml::from_slice(cfg.as_slice())
|
||||
.map_err(|e| format_err!("failed to parse config: {e}"))
|
||||
});
|
||||
|
||||
info!("config loaded");
|
||||
info!("anti-phishing-code: {}", cfg.anti_phishing_code);
|
||||
|
||||
// mount basic filesystems
|
||||
mount("none", "/proc", "proc", None);
|
||||
mount("none", "/sys", "sysfs", None);
|
||||
mount("none", "/dev", "devtmpfs", None);
|
||||
mount("none", "/dev/pts", "devpts", Some("gid=5,mode=620"));
|
||||
|
||||
// mount modules
|
||||
if let Some(ref modules) = cfg.modules {
|
||||
mount(modules, "/modules", "squashfs", None);
|
||||
|
||||
fs::create_dir_all("/lib/modules")?;
|
||||
let modules_path = &format!("/modules/lib/modules/{kernel_version}");
|
||||
|
||||
if !fs::exists(modules_path)? {
|
||||
let e = format_err!("invalid modules package: {modules_path} should exist");
|
||||
error!("{e}");
|
||||
return Err(e);
|
||||
}
|
||||
|
||||
symlink(modules_path, format!("/lib/modules/{kernel_version}"))?;
|
||||
} else {
|
||||
warn!("modules NOT mounted (not configured)");
|
||||
}
|
||||
|
||||
// init devices
|
||||
info!("initializing devices");
|
||||
start_daemon("udevd", &[]);
|
||||
|
||||
exec("udevadm", &["trigger", "-c", "add", "-t", "devices"]);
|
||||
exec("udevadm", &["trigger", "-c", "add", "-t", "subsystems"]);
|
||||
exec("udevadm", &["settle"]);
|
||||
|
||||
// networks
|
||||
networks::setup(&cfg)?;
|
||||
|
||||
// Wireguard VPN
|
||||
// TODO startVPN()
|
||||
|
||||
// SSH service
|
||||
sshd::start(&cfg);
|
||||
|
||||
// dmcrypt blockdevs
|
||||
// TODO setupCrypt(cfg.PreLVMCrypt, map[string]string{});
|
||||
|
||||
// LVM
|
||||
// TODO setupLVM(cfg);
|
||||
|
||||
// bootstrap the system
|
||||
// TODO bootstrap(cfg);
|
||||
|
||||
// finalize
|
||||
// TODO finalizeBoot();
|
||||
|
||||
exec_shell();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn mount(src: &str, dst: &str, fstype: &str, opts: Option<&str>) {
|
||||
if let Err(e) = fs::create_dir_all(dst) {
|
||||
error!("failed to create dir {dst}: {e}");
|
||||
}
|
||||
|
||||
let mut args = vec![src, dst, "-t", fstype];
|
||||
if let Some(opts) = opts {
|
||||
args.extend(["-o", opts]);
|
||||
}
|
||||
exec("mount", &args);
|
||||
}
|
||||
|
||||
fn start_daemon(prog: &str, args: &[&str]) {
|
||||
let cmd_str = sh_str(prog, args);
|
||||
retry_or_ignore(|| {
|
||||
info!("starting as daemon: {cmd_str}");
|
||||
let mut cmd = Command::new(prog);
|
||||
cmd.args(args);
|
||||
cmd.spawn()?;
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
|
||||
fn exec(prog: &str, args: &[&str]) {
|
||||
let cmd_str = sh_str(prog, args);
|
||||
retry_or_ignore(|| {
|
||||
info!("# {cmd_str}");
|
||||
let mut cmd = Command::new(prog);
|
||||
cmd.args(args);
|
||||
let s = cmd.status()?;
|
||||
if s.success() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(format_err!("command failed: {s}"))
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn retry_or_ignore(mut action: impl FnMut() -> Result<()>) {
|
||||
loop {
|
||||
match action() {
|
||||
Ok(_) => return,
|
||||
Err(e) => {
|
||||
error!("{e}");
|
||||
|
||||
loop {
|
||||
eprint!("[r]etry, [i]gnore, or [s]hell? ");
|
||||
|
||||
let mut line = String::new();
|
||||
io::stdin().read_line(&mut line).unwrap();
|
||||
|
||||
match line.trim() {
|
||||
"r" => break,
|
||||
"i" => return,
|
||||
"s" => {
|
||||
exec_shell();
|
||||
break;
|
||||
}
|
||||
v => {
|
||||
eprintln!("invalid choice: {v:?}");
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn retry<T>(mut action: impl FnMut() -> Result<T>) -> T {
|
||||
loop {
|
||||
match action() {
|
||||
Ok(v) => return v,
|
||||
Err(e) => {
|
||||
error!("{e}");
|
||||
|
||||
loop {
|
||||
eprint!("[r]etry, or [s]hell? ");
|
||||
|
||||
let mut line = String::new();
|
||||
io::stdin().read_line(&mut line).unwrap();
|
||||
|
||||
match line.trim() {
|
||||
"r" => break,
|
||||
"s" => {
|
||||
exec_shell();
|
||||
break;
|
||||
}
|
||||
v => {
|
||||
eprintln!("invalid choice: {v:?}");
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn exec_shell() {
|
||||
let mut child = match Command::new("ash").spawn() {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
error!("failed to exec shell: {e}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let _ = child.wait();
|
||||
}
|
||||
|
||||
fn sh_str(prog: &str, args: &[&str]) -> String {
|
||||
use std::borrow::Cow;
|
||||
|
||||
let mut buf = String::new();
|
||||
|
||||
buf.push_str(&shell_escape::escape(Cow::Borrowed(prog)));
|
||||
|
||||
for &arg in args {
|
||||
buf.push(' ');
|
||||
buf.push_str(&shell_escape::escape(Cow::Borrowed(arg)));
|
||||
}
|
||||
|
||||
buf
|
||||
}
|
93
src/cmd/init/networks.rs
Normal file
93
src/cmd/init/networks.rs
Normal file
@ -0,0 +1,93 @@
|
||||
use itertools::Itertools;
|
||||
use log::{info, warn};
|
||||
use std::collections::BTreeSet as Set;
|
||||
use std::process::Command;
|
||||
|
||||
use super::{format_err, retry_or_ignore, Config, Result};
|
||||
use crate::{
|
||||
udev,
|
||||
utils::{select_n_by_regex, NameAliases},
|
||||
};
|
||||
|
||||
pub fn setup(cfg: &Config) -> Result<()> {
|
||||
if cfg.networks.is_empty() {
|
||||
warn!("no networks configured");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let mut assigned: Set<String> = Set::new();
|
||||
|
||||
for net in &cfg.networks {
|
||||
retry_or_ignore(|| {
|
||||
info!("setting up network {}", net.name);
|
||||
|
||||
let netdevs = get_interfaces()?
|
||||
.filter(|dev| !assigned.contains(dev.name()))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
for dev in &netdevs {
|
||||
info!(
|
||||
"- available network device: {}, aliases [{}]",
|
||||
dev.name(),
|
||||
dev.aliases().join(", ")
|
||||
);
|
||||
}
|
||||
|
||||
let mut cmd = Command::new("ash");
|
||||
cmd.arg("-c");
|
||||
cmd.arg(&net.script);
|
||||
|
||||
let mut selected = Vec::new();
|
||||
|
||||
for iface in &net.interfaces {
|
||||
let var = &iface.var;
|
||||
|
||||
let netdevs = netdevs.iter().filter(|na| !assigned.contains(na.name()));
|
||||
let if_names = select_n_by_regex(iface.n, &iface.regexps, netdevs);
|
||||
|
||||
if if_names.is_empty() {
|
||||
return Err(format_err!("- no interface match for {var:?}"));
|
||||
}
|
||||
|
||||
let value = if_names.join(" ");
|
||||
info!("- {var}={value}");
|
||||
cmd.env(var, value);
|
||||
|
||||
selected.extend(if_names);
|
||||
}
|
||||
|
||||
info!("- running script");
|
||||
let status = cmd.status()?;
|
||||
if !status.success() {
|
||||
return Err(format_err!("setup script failed: {status}"));
|
||||
}
|
||||
|
||||
assigned.extend(selected);
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get_interfaces() -> Result<impl Iterator<Item = NameAliases>> {
|
||||
Ok(udev::get_devices("net")?.into_iter().map(|dev| {
|
||||
let mut na = NameAliases::new(dev.sysname().to_string());
|
||||
|
||||
for (property, value) in dev.properties() {
|
||||
if [
|
||||
"INTERFACE",
|
||||
"ID_NET_NAME",
|
||||
"ID_NET_NAME_PATH",
|
||||
"ID_NET_NAME_MAC",
|
||||
"ID_NET_NAME_SLOT",
|
||||
]
|
||||
.contains(&property)
|
||||
{
|
||||
na.push(value.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
na
|
||||
}))
|
||||
}
|
81
src/cmd/init/sshd.rs
Normal file
81
src/cmd/init/sshd.rs
Normal file
@ -0,0 +1,81 @@
|
||||
use log::{info, warn};
|
||||
use std::fs;
|
||||
use std::io::Write;
|
||||
use std::net;
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
use std::process::{Command, Stdio};
|
||||
use std::thread;
|
||||
|
||||
use super::{retry_or_ignore, Config};
|
||||
|
||||
pub fn start(cfg: &Config) {
|
||||
retry_or_ignore(|| {
|
||||
info!("ssh: writing authorized keys");
|
||||
|
||||
let ssh_dir = "/root/.ssh";
|
||||
let authorized_keys = format!("{ssh_dir}/authorized_keys");
|
||||
|
||||
fs::create_dir_all(ssh_dir)?;
|
||||
fs::set_permissions(ssh_dir, fs::Permissions::from_mode(0o700))?;
|
||||
|
||||
let mut ak = Vec::new();
|
||||
|
||||
for auth in &cfg.auths {
|
||||
writeln!(ak, "{} {}", auth.ssh_key, auth.name)?;
|
||||
}
|
||||
|
||||
fs::write(authorized_keys, ak)?;
|
||||
Ok(())
|
||||
});
|
||||
|
||||
retry_or_ignore(|| {
|
||||
let mut sshd_args = Vec::new();
|
||||
|
||||
sshd_args.extend(["-i", "-E", "/var/log/sshd.log"]);
|
||||
|
||||
for key_path in cfg.ssh.keys.iter() {
|
||||
if !fs::exists(key_path).is_ok_and(|b| b) {
|
||||
info!("ssh: host key not found (ignored): {key_path}");
|
||||
continue;
|
||||
}
|
||||
sshd_args.extend(["-h", key_path]);
|
||||
}
|
||||
|
||||
let sshd_args = sshd_args.into_iter().map(String::from).collect();
|
||||
|
||||
// don't pre-start sshd as it should rarely be useful at this stage, use inetd-style.
|
||||
let listen_addr = cfg.ssh.listen.clone();
|
||||
info!("ssh: starting listener on {listen_addr}");
|
||||
|
||||
let listener = net::TcpListener::bind(listen_addr)?;
|
||||
|
||||
thread::spawn(move || handle_ssh_connections(listener, sshd_args));
|
||||
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
|
||||
fn handle_ssh_connections(listener: net::TcpListener, sshd_args: Vec<String>) {
|
||||
loop {
|
||||
let Ok((stream, remote)) = listener.accept() else {
|
||||
warn!("ssh: listener stopped");
|
||||
break;
|
||||
};
|
||||
|
||||
info!("ssh: new connection from {remote}");
|
||||
|
||||
use std::os::unix::io::{AsRawFd, FromRawFd};
|
||||
let fd = stream.as_raw_fd();
|
||||
|
||||
let mut cmd = Command::new("/usr/sbin/sshd");
|
||||
cmd.args(&sshd_args);
|
||||
|
||||
cmd.stdin(unsafe { Stdio::from_raw_fd(fd) });
|
||||
cmd.stdout(unsafe { Stdio::from_raw_fd(fd) });
|
||||
cmd.stderr(Stdio::null());
|
||||
|
||||
if let Err(e) = cmd.spawn() {
|
||||
warn!("ssh: failed to start server: {e}");
|
||||
};
|
||||
}
|
||||
}
|
12
src/cmd/version.rs
Normal file
12
src/cmd/version.rs
Normal file
@ -0,0 +1,12 @@
|
||||
pub fn run() {
|
||||
println!("{}", version_string());
|
||||
}
|
||||
|
||||
pub fn version_string() -> String {
|
||||
format!(
|
||||
"Direktil {} v{} (git commit {})",
|
||||
env!("CARGO_PKG_NAME"),
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
env!("GIT_COMMIT")
|
||||
)
|
||||
}
|
6
src/lib.rs
Normal file
6
src/lib.rs
Normal file
@ -0,0 +1,6 @@
|
||||
pub mod bootstrap;
|
||||
pub mod cmd;
|
||||
pub mod lsblk;
|
||||
pub mod lvm;
|
||||
pub mod udev;
|
||||
pub mod utils;
|
27
src/lsblk.rs
Normal file
27
src/lsblk.rs
Normal file
@ -0,0 +1,27 @@
|
||||
use std::io;
|
||||
use std::process::Command;
|
||||
|
||||
#[derive(Debug, serde::Deserialize, serde::Serialize)]
|
||||
pub struct Report {
|
||||
pub blockdevices: Vec<BlockDev>,
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Deserialize, serde::Serialize)]
|
||||
pub struct BlockDev {
|
||||
pub name: String,
|
||||
#[serde(rename = "maj:min")]
|
||||
pub maj_min: String,
|
||||
pub rm: bool,
|
||||
pub size: String,
|
||||
pub ro: bool,
|
||||
#[serde(rename = "type")]
|
||||
pub dev_type: String,
|
||||
pub mountpoints: Vec<Option<String>>,
|
||||
#[serde(default)]
|
||||
pub children: Vec<BlockDev>,
|
||||
}
|
||||
|
||||
pub fn report() -> io::Result<Report> {
|
||||
let output = Command::new("lsblk").arg("--json").output()?;
|
||||
Ok(serde_json::from_slice(output.stdout.as_slice()).unwrap())
|
||||
}
|
84
src/lvm.rs
Normal file
84
src/lvm.rs
Normal file
@ -0,0 +1,84 @@
|
||||
use std::io;
|
||||
use std::process::Command;
|
||||
|
||||
#[derive(Debug, serde::Deserialize, serde::Serialize)]
|
||||
struct Report {
|
||||
report: Vec<ReportObj>,
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Deserialize, serde::Serialize)]
|
||||
#[serde(untagged)]
|
||||
enum ReportObj {
|
||||
PV { pv: Vec<PV> },
|
||||
VG { vg: Vec<VG> },
|
||||
LV { lv: Vec<LV> },
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
|
||||
pub struct PV {
|
||||
pub pv_name: String,
|
||||
pub vg_name: String,
|
||||
pub pv_fmt: String,
|
||||
pub pv_attr: String,
|
||||
pub pv_size: String,
|
||||
pub pv_free: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
|
||||
pub struct VG {
|
||||
pub vg_name: String,
|
||||
pub pv_count: String,
|
||||
pub lv_count: String,
|
||||
pub snap_count: String,
|
||||
pub vg_attr: String,
|
||||
pub vg_size: String,
|
||||
pub vg_free: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
|
||||
pub struct LV {
|
||||
lv_name: String,
|
||||
vg_name: String,
|
||||
lv_attr: String,
|
||||
lv_size: String,
|
||||
pool_lv: String,
|
||||
origin: String,
|
||||
data_percent: String,
|
||||
metadata_percent: String,
|
||||
move_pv: String,
|
||||
mirror_log: String,
|
||||
copy_percent: String,
|
||||
convert_lv: String,
|
||||
}
|
||||
|
||||
pub fn pvs() -> io::Result<Vec<PV>> {
|
||||
report_cmd("pvs", |o| match o {
|
||||
ReportObj::PV { pv } => Some(pv),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn vgs() -> io::Result<Vec<VG>> {
|
||||
report_cmd("vgs", |o| match o {
|
||||
ReportObj::VG { vg } => Some(vg),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn lvs() -> io::Result<Vec<LV>> {
|
||||
report_cmd("lvs", |o| match o {
|
||||
ReportObj::LV { lv } => Some(lv),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
fn report_cmd<T>(cmd: &str, find: fn(ReportObj) -> Option<Vec<T>>) -> io::Result<Vec<T>> {
|
||||
let output = Command::new(cmd).arg("--reportformat=json").output()?;
|
||||
let report: Report = serde_json::from_slice(output.stdout.as_slice()).unwrap();
|
||||
Ok(report
|
||||
.report
|
||||
.into_iter()
|
||||
.filter_map(find)
|
||||
.flatten()
|
||||
.collect())
|
||||
}
|
33
src/main.rs
Normal file
33
src/main.rs
Normal file
@ -0,0 +1,33 @@
|
||||
use eyre::Result;
|
||||
use log::error;
|
||||
use std::env;
|
||||
use std::process::exit;
|
||||
|
||||
use init::cmd;
|
||||
|
||||
fn main() -> Result<()> {
|
||||
env_logger::builder()
|
||||
.format_timestamp_millis()
|
||||
.format_target(false)
|
||||
.filter_level(log::LevelFilter::Info)
|
||||
.write_style(env_logger::WriteStyle::Always)
|
||||
.init();
|
||||
|
||||
unsafe {
|
||||
env::set_var("PATH", "/bin:/sbin:/usr/bin:/usr/sbin");
|
||||
}
|
||||
|
||||
let call_name = env::args().next().unwrap_or("init".into());
|
||||
let call_name = (call_name.rsplit_once('/').map(|(_, n)| n)).unwrap_or(call_name.as_str());
|
||||
|
||||
match call_name {
|
||||
"init" => cmd::init::run()?,
|
||||
"init-version" => cmd::version::run(),
|
||||
_ => {
|
||||
error!("invalid call name: {call_name:?}");
|
||||
exit(1);
|
||||
}
|
||||
};
|
||||
|
||||
Ok(())
|
||||
}
|
65
src/udev.rs
Normal file
65
src/udev.rs
Normal file
@ -0,0 +1,65 @@
|
||||
use eyre::Result;
|
||||
use log::error;
|
||||
|
||||
pub struct Device {
|
||||
sysname: String,
|
||||
output: String,
|
||||
}
|
||||
|
||||
impl Device {
|
||||
pub fn sysname(&self) -> &str {
|
||||
self.sysname.as_str()
|
||||
}
|
||||
|
||||
pub fn properties(&self) -> impl Iterator<Item = (&str, &str)> {
|
||||
self.output
|
||||
.lines()
|
||||
.filter_map(|line| line.strip_prefix("E: ")?.split_once('='))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_devices(class: &str) -> Result<Vec<Device>> {
|
||||
let mut devices = Vec::new();
|
||||
|
||||
// none of libudev and udev crates were able to list network devices.
|
||||
// falling back to manual sysfs scanning :(
|
||||
//
|
||||
// Even when given a syspath,
|
||||
// - udev crate failed to see all properties;
|
||||
// - libudev crate segfaulted on the second property (SYSNUM ok, then segfault).
|
||||
// falling back to parsing udevadm output :(
|
||||
//
|
||||
// The best fix would be to check what's wrong with udev crate.
|
||||
|
||||
let entries = std::fs::read_dir(format!("/sys/class/{class}"))?;
|
||||
for entry in entries {
|
||||
let Ok(entry) = entry else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let path = entry.path();
|
||||
let path = path.to_string_lossy();
|
||||
|
||||
let output = std::process::Command::new("udevadm")
|
||||
.args(&["info", &format!("--path={path}")])
|
||||
.stderr(std::process::Stdio::piped())
|
||||
.output()?;
|
||||
|
||||
if !output.status.success() {
|
||||
error!("udevadm fail for {path}");
|
||||
continue;
|
||||
}
|
||||
|
||||
let output = String::from_utf8_lossy(&output.stdout);
|
||||
|
||||
let name = entry.file_name();
|
||||
let dev = Device {
|
||||
sysname: name.to_string_lossy().to_string(),
|
||||
output: output.into_owned(),
|
||||
};
|
||||
|
||||
devices.push(dev);
|
||||
}
|
||||
|
||||
Ok(devices)
|
||||
}
|
61
src/utils.rs
Normal file
61
src/utils.rs
Normal file
@ -0,0 +1,61 @@
|
||||
use log::error;
|
||||
use std::collections::BTreeSet as Set;
|
||||
|
||||
pub struct NameAliases {
|
||||
name: String,
|
||||
aliases: Set<String>,
|
||||
}
|
||||
|
||||
impl NameAliases {
|
||||
pub fn new(name: String) -> Self {
|
||||
Self {
|
||||
name,
|
||||
aliases: Set::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn name(&self) -> &str {
|
||||
self.name.as_str()
|
||||
}
|
||||
pub fn aliases(&self) -> impl Iterator<Item = &str> {
|
||||
self.aliases.iter().map(|s| s.as_str())
|
||||
}
|
||||
|
||||
pub fn iter(&self) -> impl Iterator<Item = &str> {
|
||||
std::iter::once(self.name()).chain(self.aliases())
|
||||
}
|
||||
|
||||
pub fn push(&mut self, alias: String) {
|
||||
if self.name == alias {
|
||||
return;
|
||||
}
|
||||
self.aliases.insert(alias);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn select_n_by_regex<'t>(
|
||||
n: usize,
|
||||
regexs: &Vec<String>,
|
||||
nas: impl Iterator<Item = &'t NameAliases>,
|
||||
) -> Vec<String> {
|
||||
// compile regexs
|
||||
let regexs: Vec<_> = (regexs.iter())
|
||||
.filter_map(|re| {
|
||||
regex::Regex::new(re)
|
||||
.inspect_err(|e| error!("invalid regex ignored: {re:?}: {e}"))
|
||||
.ok()
|
||||
})
|
||||
.collect();
|
||||
|
||||
let matching = |name| regexs.iter().any(|re| re.is_match(name));
|
||||
|
||||
let nas = nas
|
||||
.filter(|na| na.iter().any(matching))
|
||||
.map(|na| na.name().to_string());
|
||||
|
||||
if n <= 0 {
|
||||
nas.collect()
|
||||
} else {
|
||||
nas.take(n).collect()
|
||||
}
|
||||
}
|
66
ssh.go
66
ssh.go
@ -4,15 +4,16 @@ import (
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net"
|
||||
"os"
|
||||
"os/exec"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"github.com/kr/pty"
|
||||
"github.com/creack/pty"
|
||||
"github.com/rs/zerolog/log"
|
||||
"golang.org/x/crypto/ssh"
|
||||
|
||||
config "novit.tech/direktil/pkg/bootstrapconfig"
|
||||
@ -26,20 +27,24 @@ func startSSH(cfg *config.Config) {
|
||||
hostKeyLoaded := false
|
||||
|
||||
for _, format := range []string{"rsa", "dsa", "ecdsa", "ed25519"} {
|
||||
log := log.With().Str("format", format).Logger()
|
||||
|
||||
pkBytes, err := os.ReadFile("/id_" + format)
|
||||
if err != nil {
|
||||
log.Printf("ssh : failed to load %s host key: %v", format, err)
|
||||
log.Error().Err(err).Msg("ssh: failed to load host key")
|
||||
continue
|
||||
}
|
||||
|
||||
pk, err := ssh.ParsePrivateKey(pkBytes)
|
||||
if err != nil {
|
||||
log.Printf("ssh: failed to parse %s host key: %v", format, err)
|
||||
log.Error().Err(err).Msg("ssh: failed to parse host key")
|
||||
continue
|
||||
}
|
||||
|
||||
sshConfig.AddHostKey(pk)
|
||||
hostKeyLoaded = true
|
||||
|
||||
log.Info().Msg("ssh: loaded host key")
|
||||
}
|
||||
|
||||
if !hostKeyLoaded {
|
||||
@ -52,13 +57,13 @@ func startSSH(cfg *config.Config) {
|
||||
fatalf("ssh: failed to listen on %s: %v", sshBind, err)
|
||||
}
|
||||
|
||||
log.Print("SSH server listening on ", sshBind)
|
||||
log.Info().Str("bind-address", sshBind).Msg("SSH server listening")
|
||||
|
||||
go func() {
|
||||
for {
|
||||
conn, err := listener.Accept()
|
||||
if err != nil {
|
||||
log.Print("ssh: accept conn failed: ", err)
|
||||
log.Info().Err(err).Msg("ssh: accept conn failed")
|
||||
continue
|
||||
}
|
||||
|
||||
@ -71,12 +76,12 @@ func sshHandleConn(conn net.Conn, sshConfig *ssh.ServerConfig) {
|
||||
sshConn, chans, reqs, err := ssh.NewServerConn(conn, sshConfig)
|
||||
|
||||
if err != nil {
|
||||
log.Print("ssh: handshake failed: ", err)
|
||||
log.Error().Err(err).Msg("ssh: handshake failed")
|
||||
return
|
||||
}
|
||||
|
||||
remoteAddr := sshConn.User() + "@" + sshConn.RemoteAddr().String()
|
||||
log.Print("ssh: new connection from ", remoteAddr)
|
||||
log.Info().Str("remote", remoteAddr).Msg("ssh: new connection")
|
||||
|
||||
go sshHandleReqs(reqs)
|
||||
go sshHandleChannels(remoteAddr, chans)
|
||||
@ -89,7 +94,7 @@ func sshHandleReqs(reqs <-chan *ssh.Request) {
|
||||
req.Reply(true, nil)
|
||||
|
||||
default:
|
||||
log.Printf("ssh: discarding req: %+v", req)
|
||||
log.Info().Str("type", req.Type).Msg("ssh: discarding request")
|
||||
req.Reply(false, nil)
|
||||
}
|
||||
}
|
||||
@ -104,7 +109,7 @@ func sshHandleChannels(remoteAddr string, chans <-chan ssh.NewChannel) {
|
||||
|
||||
channel, requests, err := newChannel.Accept()
|
||||
if err != nil {
|
||||
log.Print("ssh: failed to accept channel: ", err)
|
||||
log.Error().Err(err).Msg("ssh: failed to accept channel")
|
||||
continue
|
||||
}
|
||||
|
||||
@ -138,7 +143,10 @@ func sshHandleChannel(remoteAddr string, channel ssh.Channel, requests <-chan *s
|
||||
command := string(req.Payload[4 : req.Payload[3]+4])
|
||||
switch command {
|
||||
case "init":
|
||||
if ptyF == nil {
|
||||
go func() {
|
||||
channel.Stderr().Write([]byte("\033[5m\033[31;1m\n\nWARNING: no TTY requested, passwords will be echoed!\n\n\033[0m"))
|
||||
time.Sleep(3 * time.Second)
|
||||
io.Copy(channel, stdout.NewReader())
|
||||
once.Do(closeCh)
|
||||
}()
|
||||
@ -147,6 +155,24 @@ func sshHandleChannel(remoteAddr string, channel ssh.Channel, requests <-chan *s
|
||||
once.Do(closeCh)
|
||||
}()
|
||||
|
||||
} else {
|
||||
stdinTTY := newTTY(ptyF.Fd())
|
||||
if askingSecret.Load() {
|
||||
stdinTTY.EchoOff()
|
||||
}
|
||||
registerInput(stdinTTY)
|
||||
defer unregiterInput(stdinTTY)
|
||||
|
||||
go func() {
|
||||
io.Copy(ttyF, stdout.NewReader())
|
||||
once.Do(closeCh)
|
||||
}()
|
||||
go func() {
|
||||
io.Copy(stdinPipe, ttyF)
|
||||
once.Do(closeCh)
|
||||
}()
|
||||
}
|
||||
|
||||
req.Reply(true, nil)
|
||||
|
||||
case "bootstrap":
|
||||
@ -191,15 +217,6 @@ func sshHandleChannel(remoteAddr string, channel ssh.Channel, requests <-chan *s
|
||||
ttyF = nil
|
||||
}()
|
||||
|
||||
go func() {
|
||||
io.Copy(channel, ptyF)
|
||||
once.Do(closeCh)
|
||||
}()
|
||||
go func() {
|
||||
io.Copy(ptyF, channel)
|
||||
once.Do(closeCh)
|
||||
}()
|
||||
|
||||
req.Reply(true, nil)
|
||||
|
||||
case "pty-req":
|
||||
@ -211,7 +228,7 @@ func sshHandleChannel(remoteAddr string, channel ssh.Channel, requests <-chan *s
|
||||
var err error
|
||||
ptyF, ttyF, err = pty.Open()
|
||||
if err != nil {
|
||||
log.Print("PTY err: ", err)
|
||||
log.Error().Err(err).Msg("ssh: PTY open failed")
|
||||
req.Reply(false, nil)
|
||||
continue
|
||||
}
|
||||
@ -223,6 +240,15 @@ func sshHandleChannel(remoteAddr string, channel ssh.Channel, requests <-chan *s
|
||||
|
||||
req.Reply(true, nil)
|
||||
|
||||
go func() {
|
||||
io.Copy(channel, ptyF)
|
||||
once.Do(closeCh)
|
||||
}()
|
||||
go func() {
|
||||
io.Copy(ptyF, channel)
|
||||
once.Do(closeCh)
|
||||
}()
|
||||
|
||||
case "window-change":
|
||||
w, h := sshParseDims(req.Payload)
|
||||
sshSetWinsize(ptyF.Fd(), w, h)
|
||||
|
@ -26,9 +26,9 @@ networks:
|
||||
- eno.*
|
||||
- enp.*
|
||||
script: |
|
||||
ip a add 2001:41d0:306:168f::1337:2eed/64 dev $iface
|
||||
ip li set $iface up
|
||||
#udhcpc $iface
|
||||
udhcpc -i $iface -b -t1 -T1 -A5 ||
|
||||
ip a add 2001:41d0:306:168f::1337:2eed/64 dev $iface
|
||||
|
||||
pre_lvm_crypt:
|
||||
- dev: /dev/vda
|
||||
|
9
test-initrd/id_ecdsa
Normal file
9
test-initrd/id_ecdsa
Normal file
@ -0,0 +1,9 @@
|
||||
-----BEGIN OPENSSH PRIVATE KEY-----
|
||||
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAaAAAABNlY2RzYS
|
||||
1zaGEyLW5pc3RwMjU2AAAACG5pc3RwMjU2AAAAQQSlevO48OA0/yB8zTP1naijVU3wsB0c
|
||||
4s6Jc/8y7YwNq51/SlieeGeRFcCSke5Z67rNX2JFiv+tsGQB6TczZm/6AAAAqDU5b2c1OW
|
||||
9nAAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBKV687jw4DT/IHzN
|
||||
M/WdqKNVTfCwHRzizolz/zLtjA2rnX9KWJ54Z5EVwJKR7lnrus1fYkWK/62wZAHpNzNmb/
|
||||
oAAAAhANenGXlP1ZPgcyb/+O57MbpGDOZS4e7UNiyvkD8I3hNnAAAACW53cmtAbndyawEC
|
||||
AwQFBg==
|
||||
-----END OPENSSH PRIVATE KEY-----
|
7
test-initrd/id_ed25519
Normal file
7
test-initrd/id_ed25519
Normal file
@ -0,0 +1,7 @@
|
||||
-----BEGIN OPENSSH PRIVATE KEY-----
|
||||
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
|
||||
QyNTUxOQAAACCCMX0zm3Fi7vXWevHuJvzU30l5F06NAC2qloUewVSoDQAAAJDnq/y456v8
|
||||
uAAAAAtzc2gtZWQyNTUxOQAAACCCMX0zm3Fi7vXWevHuJvzU30l5F06NAC2qloUewVSoDQ
|
||||
AAAEDXYq507MsjSN34Qw87guf3d5D4Dt2IrF788CeBcYSNe4IxfTObcWLu9dZ68e4m/NTf
|
||||
SXkXTo0ALaqWhR7BVKgNAAAACW53cmtAbndyawECAwQ=
|
||||
-----END OPENSSH PRIVATE KEY-----
|
@ -1 +0,0 @@
|
||||
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDLo+mv+0GJViwFiK14bAw8j4HYFIGf4I/fpmIqzHohf70TT+cYqAKSHBYV+uYjNLYQib6Ii/thPexeypw73pq7Z7CHvubnFQUiuqJ7lzXeV4146f5eHL76/TvTmKthS4FVFta6SlCOE6unR6q8HM52VSijavtoX3musxugCwhaHmBNOdUJcNIRCIey8QaOztPK05dDrOZhMQJgSST/BRaNrtY0/xRmJo+5TbQeyjyDuQdK2EoS51QMWzsT/LH6drQBgKd8RRHqjEhscfaV2CmdfuVO/liEdW82epMgFCGYtMetP/rs3bPkC90ULxPZSytaz7d5ux1dvSgrPHzX4306k/GP3d6EvOedy4IKAB53J7lebvrRI5pTVPZvd/RsSGGxUIwjf2Y8TF5nbC2d2D5Oauqfevn29veIRh8mq+AsJMnkvUFwVRN+6WDsZ+F82+AGaCKJFNQLYbRKtXW0zzi+wTsnLJNwlpevRf61SCxehSqeVfnc4TDsAGyRa9nSbR8= test@novit.io
|
Binary file not shown.
BIN
test-kernel
BIN
test-kernel
Binary file not shown.
@ -2,7 +2,7 @@ package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"log"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"novit.tech/direktil/pkg/cpiocat"
|
||||
@ -13,6 +13,7 @@ func main() {
|
||||
|
||||
err := cpiocat.Append(os.Stdout, os.Stdin, flag.Args())
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
fmt.Fprintln(os.Stderr, err.Error())
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
@ -3,7 +3,7 @@ package main
|
||||
import (
|
||||
"bytes"
|
||||
"flag"
|
||||
"log"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
@ -14,12 +14,10 @@ func main() {
|
||||
flag.Parse()
|
||||
|
||||
for _, arg := range flag.Args() {
|
||||
log.Print("testing ", arg)
|
||||
fmt.Println("testing", arg)
|
||||
|
||||
cfgBytes, err := os.ReadFile(arg)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
fail(err)
|
||||
|
||||
cfg := config.Config{}
|
||||
|
||||
@ -27,8 +25,13 @@ func main() {
|
||||
dec.KnownFields(true)
|
||||
|
||||
err = dec.Decode(&cfg)
|
||||
fail(err)
|
||||
}
|
||||
}
|
||||
|
||||
func fail(err error) {
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
fmt.Fprintln(os.Stderr, err.Error())
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
25
tty.go
25
tty.go
@ -1,29 +1,25 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
var (
|
||||
stdinTTY = &tty{int(os.Stdin.Fd()), nil}
|
||||
)
|
||||
|
||||
type tty struct {
|
||||
fd int
|
||||
termios *unix.Termios
|
||||
}
|
||||
|
||||
func newTTY(fd uintptr) *tty {
|
||||
termios, _ := unix.IoctlGetTermios(int(fd), unix.TCGETS)
|
||||
return &tty{int(fd), termios}
|
||||
}
|
||||
|
||||
func (t *tty) EchoOff() {
|
||||
termios, err := unix.IoctlGetTermios(t.fd, unix.TCGETS)
|
||||
if err != nil {
|
||||
if t.termios == nil {
|
||||
return
|
||||
}
|
||||
|
||||
t.termios = termios
|
||||
|
||||
newState := *termios
|
||||
newState := *t.termios
|
||||
newState.Lflag &^= unix.ECHO
|
||||
newState.Lflag |= unix.ICANON | unix.ISIG
|
||||
newState.Iflag |= unix.ICRNL
|
||||
@ -31,8 +27,9 @@ func (t *tty) EchoOff() {
|
||||
}
|
||||
|
||||
func (t *tty) Restore() {
|
||||
if t.termios != nil {
|
||||
if t.termios == nil {
|
||||
return
|
||||
}
|
||||
|
||||
unix.IoctlSetTermios(t.fd, unix.TCSETS, t.termios)
|
||||
t.termios = nil
|
||||
}
|
||||
}
|
||||
|
20
vpn.go
20
vpn.go
@ -1,11 +1,11 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
"golang.zx2c4.com/wireguard/wgctrl"
|
||||
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
|
||||
|
||||
@ -13,11 +13,18 @@ import (
|
||||
)
|
||||
|
||||
func setupVPN(vpn config.VPNDef, localGenDir string) {
|
||||
log.Printf("setting up VPN %s", vpn.Name)
|
||||
log := log.With().Str("vpn", vpn.Name).Logger()
|
||||
|
||||
log.Info().Msg("VPN: setting up")
|
||||
|
||||
vpnDir := filepath.Join(localGenDir, vpn.Name)
|
||||
os.MkdirAll(vpnDir, 0750)
|
||||
|
||||
logMsg := log.Info()
|
||||
if vpn.ListenPort != nil {
|
||||
logMsg.Int("ListenPort", *vpn.ListenPort)
|
||||
}
|
||||
|
||||
// public/private key
|
||||
keyFile := filepath.Join(vpnDir, "key")
|
||||
keyBytes, err := os.ReadFile(keyFile)
|
||||
@ -39,7 +46,7 @@ func setupVPN(vpn config.VPNDef, localGenDir string) {
|
||||
fatalf("bad VPN key: %v", err)
|
||||
}
|
||||
|
||||
log.Printf("VPN %s public key is %s", vpn.Name, key.PublicKey().String())
|
||||
logMsg.Stringer("PublicKey", key.PublicKey())
|
||||
|
||||
// pre-shared key
|
||||
pskeyFile := filepath.Join(vpnDir, "pskey")
|
||||
@ -62,7 +69,10 @@ func setupVPN(vpn config.VPNDef, localGenDir string) {
|
||||
fatalf("bad VPN pre-shared key: %v", err)
|
||||
}
|
||||
|
||||
log.Printf("VPN %s pre-shared key is %s", vpn.Name, key.String())
|
||||
{
|
||||
keyStr := key.String()
|
||||
logMsg.Str("PresharedKey", keyStr[0:4]+"..."+keyStr[len(keyStr)-4:])
|
||||
}
|
||||
|
||||
// setup interface
|
||||
cfg := wgtypes.Config{
|
||||
@ -110,12 +120,14 @@ func setupVPN(vpn config.VPNDef, localGenDir string) {
|
||||
}
|
||||
defer wg.Close()
|
||||
|
||||
log.Info().Strs("ips", vpn.IPs).Msg("VPN: creating interface")
|
||||
run("ip", "link", "add", vpn.Name, "type", "wireguard")
|
||||
|
||||
for _, ip := range vpn.IPs {
|
||||
run("ip", "addr", "add", ip, "dev", vpn.Name)
|
||||
}
|
||||
|
||||
logMsg.Msg("VPN: configuring interface")
|
||||
err = wg.ConfigureDevice(vpn.Name, cfg)
|
||||
if err != nil {
|
||||
fatalf("failed to setup VPN %s: %v", vpn.Name, err)
|
||||
|
26
zombies.go
26
zombies.go
@ -1,26 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
func cleanZombies() {
|
||||
return // FIXME noop... udhcpc is a daemon staying alive so we never finish
|
||||
|
||||
var wstatus syscall.WaitStatus
|
||||
|
||||
for {
|
||||
pid, err := syscall.Wait4(-1, &wstatus, 0, nil)
|
||||
switch err {
|
||||
case nil:
|
||||
log.Printf("collected PID %v", pid)
|
||||
|
||||
case syscall.ECHILD:
|
||||
return
|
||||
|
||||
default:
|
||||
log.Printf("unknown error: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user