├── .github ├── dependabot.yml └── workflows │ └── ci.yaml ├── .gitignore ├── Cargo.lock ├── Cargo.toml ├── LICENSES └── MPL-2.0.txt ├── README.md ├── crates ├── disks │ ├── Cargo.toml │ └── src │ │ ├── disk.rs │ │ ├── lib.rs │ │ ├── loopback.rs │ │ ├── mmc.rs │ │ ├── mock.rs │ │ ├── nvme.rs │ │ ├── partition.rs │ │ ├── scsi.rs │ │ ├── sizing.rs │ │ ├── sysfs.rs │ │ └── virt.rs ├── disktester │ ├── Cargo.toml │ └── src │ │ └── main.rs ├── partitioning │ ├── Cargo.toml │ └── src │ │ ├── attributes.rs │ │ ├── blkpg.rs │ │ ├── formatter.rs │ │ ├── lib.rs │ │ ├── loopback.rs │ │ ├── planner.rs │ │ ├── sparsefile.rs │ │ ├── strategy.rs │ │ └── writer.rs ├── provisioning │ ├── Cargo.toml │ ├── src │ │ ├── commands.rs │ │ ├── commands │ │ │ ├── create_partition.rs │ │ │ ├── create_partition_table.rs │ │ │ └── find_disk.rs │ │ ├── lib.rs │ │ └── provisioner.rs │ └── tests │ │ └── use_whole_disk.kdl ├── superblock │ ├── Cargo.toml │ ├── src │ │ ├── btrfs.rs │ │ ├── ext4.rs │ │ ├── f2fs.rs │ │ ├── fat.rs │ │ ├── lib.rs │ │ ├── luks2.rs │ │ ├── luks2 │ │ │ ├── config.rs │ │ │ └── superblock.rs │ │ └── xfs.rs │ └── tests │ │ ├── README.md │ │ ├── btrfs.img.zst │ │ ├── ext4.img.zst │ │ ├── f2fs.img.zst │ │ ├── fat16.img │ │ ├── fat16.img.zst │ │ ├── fat32.img │ │ ├── fat32.img.zst │ │ ├── luks+ext4.img.zst │ │ └── xfs.img.zst └── types │ ├── Cargo.toml │ └── src │ ├── constraints.rs │ ├── errors.rs │ ├── filesystem.rs │ ├── kdl_helpers.rs │ ├── lib.rs │ ├── partition_role.rs │ ├── partition_table.rs │ ├── partition_type.rs │ └── units.rs └── rustfmt.toml /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 2 | 3 | version: 2 4 | updates: 5 | - package-ecosystem: "cargo" 6 | directory: "/" 7 | schedule: 8 | interval: "weekly" 9 | day: "tuesday" 10 | time: "10:00" 11 | timezone: "Europe/London" 12 | groups: 13 | cargo: 14 | patterns: 15 | - "*" 16 | -------------------------------------------------------------------------------- /.github/workflows/ci.yaml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: [ "main" ] 6 | pull_request: 7 | branches: [ "main" ] 8 | schedule: 9 | - cron: '30 2 * * *' 10 | 11 | env: 12 | CARGO_TERM_COLOR: always 13 | 14 | jobs: 15 | build: 16 | runs-on: ubuntu-latest 17 | name: Build & Test Project 18 | 19 | steps: 20 | - name: Checkout source 21 | uses: actions/checkout@v4 22 | 23 | - name: Install Rust 24 | uses: dtolnay/rust-toolchain@stable 25 | with: 26 | components: rustfmt, clippy 27 | 28 | - name: Check Formatting 29 | run: cargo fmt --all -- --check 30 | 31 | - name: Cargo Cache 32 | uses: Swatinem/rust-cache@v2 33 | 34 | - name: Build project 35 | run: cargo build 36 | 37 | - name: Test project 38 | run: cargo test --workspace 39 | 40 | - name: Run clippy 41 | uses: giraffate/clippy-action@v1 42 | with: 43 | reporter: 'github-pr-check' 44 | clippy_flags: --workspace --no-deps 45 | filter_mode: nofilter 46 | github_token: ${{ secrets.GITHUB_TOKEN }} 47 | 48 | typos: 49 | name: Spell Check with Typos 50 | runs-on: ubuntu-latest 51 | 52 | steps: 53 | - uses: actions/checkout@v4 54 | - uses: crate-ci/typos@v1.28.1 55 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | lesparse.img 3 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | resolver = "2" 3 | 4 | default-members = [ 5 | "crates/*", 6 | ] 7 | 8 | members = [ 9 | "crates/*", 10 | ] 11 | 12 | [workspace.dependencies] 13 | gpt = "4.0.0" 14 | linux-raw-sys = "0.9.4" 15 | itertools = "0.14.0" 16 | kdl = "6.3.3" 17 | log = "0.4.21" 18 | miette = "7.5.0" 19 | nix = { version = "0.30.1", features = ["fs", "mount"] } 20 | phf = "0.11" 21 | serde = { version = "1.0" } 22 | serde_json = "1.0" 23 | snafu = "0.8.5" 24 | test-log = "0.2.17" 25 | thiserror = "2.0.3" 26 | uuid = { version = "1.12.1", features = ["v8"] } 27 | zerocopy = "0.8.0" 28 | zstd = "0.13.1" 29 | -------------------------------------------------------------------------------- /LICENSES/MPL-2.0.txt: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at https://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. 374 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # disks-rs 💽 2 | 3 | This project began life in the [blsforme](https://github.com/serpent-os/blsforme) project for Serpent OS. 4 | However as time went on it became clear we needed to extend the capabilities beyond simple topology scanning 5 | and superblocks to support the installer and other use cases. 6 | 7 | Importantly due to using blsforme in moss, and requiring static linking to avoid soname breakage on updates, 8 | we were unable to leverage `libblkid` due to licensing incompatibilities. 9 | 10 | ## Goals 🎯 11 | 12 | Provide safe and sane APIs for dealing with filesystems, block devices and partitioning in Rust. The intent 13 | is to provide a high level API that can be used to build tools like installers, partitioners, and other disk 14 | management tools. 15 | 16 | With support, we will also provide the foundations for a Rust implementation of `libblkid`, while also providing 17 | an alternative to `libparted`. 18 | 19 | Per [issue 3](https://github.com/serpent-os/disks-rs/issues/3) we do eventually plan to extend the superblock support 20 | to have in-tree capabilities for writing filesystems, but this is a long term goal. TLDR generation of complete filesystem 21 | images / rootfs without `euid = 0` requirements. If you want to make this happen faster, then read the next section. 😉 22 | 23 | ## Support Us ❤️ 24 | 25 | [![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/J3J511WM9N) 26 | 27 | [![GitHub Sponsors](https://img.shields.io/github/sponsors/ikeycode?style=for-the-badge&logo=github&label=Sponsor)](https://github.com/sponsors/ikeycode) 28 | 29 | ## Crates 📦 30 | 31 | - `disks` - A simplistic enumeration API built atop `sysfs` for discovering block devices and partitions. 32 | - `superblock` - Pure Rust superblock parsing for various filesystems. Version-specific oddities and more filesystems 33 | will be added over time. 34 | 35 | Currently we support: 36 | 37 | - `luks2` - LUKS2 superblock parsing. 38 | - `ext4` - Ext4 superblock parsing. 39 | - `f2fs` - F2FS superblock parsing. 40 | - `btrfs` - Btrfs superblock parsing. 41 | - `xfs` - XFS superblock parsing. 42 | 43 | - `partitioning` - A partitioning API for manipulating partition tables on block devices. This will be built atop 44 | `disks` and `superblock` to provide a high level API for partitioning. Currently focused on `gpt`. 45 | 46 | - The `loopback` module provides a way to create loopback devices and bind them for testing. 47 | - Notifying the kernel of partition table changes is supported for GPT (BLKPG). 48 | - The `planner` module is provided to assist in planning partitioning operations (undo support included) 49 | - The `strategy` module builds on top of `planner` to facilitate computation of partition layouts including 50 | disk wipe, dual boot scenarios, etc. 51 | 52 | ## License 53 | 54 | `disks-rs` is available under the terms of the [MPL-2.0](https://spdx.org/licenses/MPL-2.0.html) 55 | -------------------------------------------------------------------------------- /crates/disks/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "disks" 3 | version = "0.1.0" 4 | edition = "2021" 5 | description = "A library for working with disks and partitions" 6 | 7 | [dependencies] 8 | regex = "1" 9 | log.workspace = true 10 | -------------------------------------------------------------------------------- /crates/disks/src/disk.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: Copyright © 2025 Serpent OS Developers 2 | // 3 | // SPDX-License-Identifier: MPL-2.0 4 | 5 | use core::fmt; 6 | use std::fs; 7 | use std::{ 8 | ops::Deref, 9 | path::{Path, PathBuf}, 10 | }; 11 | 12 | use crate::SYSFS_DIR; 13 | use crate::{mmc, mock, nvme, partition::Partition, scsi, sysfs, virt}; 14 | 15 | /// Represents the type of disk device. 16 | #[derive(Debug)] 17 | pub enum Disk { 18 | /// SCSI disk device (e.g. sda, sdb) 19 | Scsi(scsi::Disk), 20 | /// MMC disk device (e.g. mmcblk0) 21 | Mmc(mmc::Disk), 22 | /// NVMe disk device (e.g. nvme0n1) 23 | Nvme(nvme::Disk), 24 | /// Virtual disk device 25 | Virtual(virt::Disk), 26 | /// Mock disk for testing 27 | Mock(mock::MockDisk), 28 | } 29 | 30 | impl Deref for Disk { 31 | type Target = BasicDisk; 32 | 33 | // Let disks deref to BasicDisk to eliminate code duplication 34 | fn deref(&self) -> &Self::Target { 35 | match self { 36 | Disk::Mmc(disk) => disk, 37 | Disk::Nvme(disk) => disk, 38 | Disk::Scsi(disk) => disk, 39 | Disk::Virtual(disk) => disk, 40 | Disk::Mock(disk) => disk, 41 | } 42 | } 43 | } 44 | 45 | /// A basic disk representation containing common attributes shared by all disk types. 46 | /// This serves as the base structure that specific disk implementations build upon. 47 | #[derive(Debug, Default)] 48 | pub struct BasicDisk { 49 | /// Device name (e.g. sda, nvme0n1) 50 | pub(crate) name: String, 51 | /// Total number of sectors on the disk 52 | pub(crate) sectors: u64, 53 | /// Path to the device in /dev 54 | pub(crate) device: PathBuf, 55 | /// Optional disk model name 56 | pub(crate) model: Option, 57 | /// Optional disk vendor name 58 | pub(crate) vendor: Option, 59 | /// Partitions 60 | pub(crate) partitions: Vec, 61 | } 62 | 63 | impl fmt::Display for Disk { 64 | // forward Display to BasicDisk 65 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 66 | self.deref().fmt(f) 67 | } 68 | } 69 | 70 | impl fmt::Display for BasicDisk { 71 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 72 | let bytes = self.size(); 73 | let gib = bytes as f64 / 1_073_741_824.0; 74 | 75 | write!(f, "{} ({:.2} GiB)", self.name(), gib)?; 76 | 77 | if let Some(vendor) = self.vendor() { 78 | write!(f, " - {vendor}")?; 79 | } 80 | 81 | if let Some(model) = self.model() { 82 | write!(f, " {model}")?; 83 | } 84 | 85 | Ok(()) 86 | } 87 | } 88 | 89 | impl BasicDisk { 90 | /// Returns the name of the disk device. 91 | pub fn name(&self) -> &str { 92 | &self.name 93 | } 94 | 95 | /// Returns the partitions on the disk. 96 | pub fn partitions(&self) -> &[Partition] { 97 | &self.partitions 98 | } 99 | 100 | /// Helper for MockDisk to modify partitions 101 | pub(crate) fn partitions_mut(&mut self) -> &mut Vec { 102 | &mut self.partitions 103 | } 104 | 105 | /// Returns the path to the disk device in dev. 106 | pub fn device_path(&self) -> &Path { 107 | &self.device 108 | } 109 | 110 | /// Returns the total number of sectors on the disk. 111 | pub fn sectors(&self) -> u64 { 112 | self.sectors 113 | } 114 | 115 | /// Returns the size of the disk in bytes. 116 | pub fn size(&self) -> u64 { 117 | self.sectors() * 512 118 | } 119 | 120 | /// Returns the model name of the disk. 121 | pub fn model(&self) -> Option<&str> { 122 | self.model.as_deref() 123 | } 124 | 125 | /// Returns the vendor name of the disk. 126 | pub fn vendor(&self) -> Option<&str> { 127 | self.vendor.as_deref() 128 | } 129 | } 130 | 131 | /// Trait for initializing different types of disk devices from sysfs. 132 | pub trait DiskInit: Sized { 133 | /// Creates a new disk instance by reading information from the specified sysfs path. 134 | /// 135 | /// # Arguments 136 | /// 137 | /// * `root` - The root sysfs directory path 138 | /// * `name` - The name of the disk device 139 | /// 140 | /// # Returns 141 | /// 142 | /// `Some(Self)` if the disk was successfully initialized, `None` otherwise 143 | fn from_sysfs_path(root: &Path, name: &str) -> Option; 144 | } 145 | 146 | impl DiskInit for BasicDisk { 147 | fn from_sysfs_path(sysroot: &Path, name: &str) -> Option { 148 | let node = sysroot.join(SYSFS_DIR).join(name); 149 | 150 | log::debug!("Initializing disk at sysfs path: {node:?}"); 151 | 152 | // Read the partitions of the disk if any 153 | let mut partitions: Vec<_> = fs::read_dir(&node) 154 | .ok()? 155 | .filter_map(Result::ok) 156 | .filter_map(|e| { 157 | let name = e.file_name().to_string_lossy().to_string(); 158 | Partition::from_sysfs_path(sysroot, &name) 159 | }) 160 | .collect(); 161 | partitions.sort_by_key(|p| p.number); 162 | 163 | let sectors = sysfs::read(&node, "size").unwrap_or(0); 164 | log::debug!("Read {sectors} sectors for disk {name}"); 165 | 166 | let device = PathBuf::from("/dev").join(name); 167 | log::debug!("Device path: {device:?}"); 168 | 169 | let model = sysfs::read(&node, "device/model"); 170 | log::debug!("Model: {model:?}"); 171 | 172 | let vendor = sysfs::read(&node, "device/vendor"); 173 | log::debug!("Vendor: {vendor:?}"); 174 | 175 | Some(Self { 176 | name: name.to_owned(), 177 | sectors, 178 | device, 179 | model, 180 | vendor, 181 | partitions, 182 | }) 183 | } 184 | } 185 | -------------------------------------------------------------------------------- /crates/disks/src/lib.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: Copyright © 2025 Serpent OS Developers 2 | // 3 | // SPDX-License-Identifier: MPL-2.0 4 | 5 | mod disk; 6 | mod sizing; 7 | pub use sizing::*; 8 | 9 | use std::{ 10 | fs, io, 11 | path::{Path, PathBuf}, 12 | }; 13 | 14 | pub use disk::*; 15 | use partition::Partition; 16 | pub mod loopback; 17 | pub mod mmc; 18 | pub mod mock; 19 | pub mod nvme; 20 | pub mod partition; 21 | pub mod scsi; 22 | mod sysfs; 23 | pub mod virt; 24 | 25 | const SYSFS_DIR: &str = "sys/class/block"; 26 | const DEVFS_DIR: &str = "dev"; 27 | 28 | /// A block device on the system which can be either a physical disk or a partition. 29 | #[derive(Debug)] 30 | pub enum BlockDevice { 31 | /// A physical disk device 32 | Disk(Box), 33 | Loopback(Box), 34 | } 35 | 36 | impl BlockDevice { 37 | /// Discovers all block devices present in the system. 38 | /// 39 | /// # Returns 40 | /// 41 | /// A vector of discovered block devices or an IO error if the discovery fails. 42 | pub fn discover() -> io::Result> { 43 | Self::discover_in_sysroot("/") 44 | } 45 | 46 | /// Returns the total number of sectors on the block device. 47 | pub fn sectors(&self) -> u64 { 48 | match self { 49 | BlockDevice::Disk(disk) => disk.sectors(), 50 | BlockDevice::Loopback(device) => device.disk().map_or(0, |d| d.sectors()), 51 | } 52 | } 53 | 54 | /// Returns the total size of the block device in bytes. 55 | pub fn size(&self) -> u64 { 56 | self.sectors() * 512 57 | } 58 | 59 | /// Returns the partitions on the block device. 60 | pub fn partitions(&self) -> &[Partition] { 61 | match self { 62 | BlockDevice::Disk(disk) => disk.partitions(), 63 | BlockDevice::Loopback(device) => device.disk().map_or(&[], |d| d.partitions()), 64 | } 65 | } 66 | 67 | /// Returns the path to the partition with the given index. 68 | /// No attempt is made to verify the existence of the partition. 69 | pub fn partition_path(&self, index: usize) -> PathBuf { 70 | if let BlockDevice::Disk(disk) = self { 71 | match **disk { 72 | Disk::Scsi(_) | Disk::Virtual(_) => { 73 | // Add N to the end of the device name 74 | return disk.device_path().with_file_name(format!("{}{}", disk.name(), index)); 75 | } 76 | Disk::Mock(ref d) if d.parts_prefix => { 77 | return PathBuf::from("/dev").join(format!("{}p{}", disk.name(), index)); 78 | } 79 | Disk::Mock(_) => { 80 | return PathBuf::from("/dev").join(format!("{}{}", disk.name(), index)); 81 | } 82 | _ => {} 83 | } 84 | } 85 | // Add pN to the end of the device name 86 | self.device().with_file_name(format!("{}p{}", self.name(), index)) 87 | } 88 | 89 | /// Creates a mock block device with a specified number of sectors. 90 | pub fn mock_device(disk: mock::MockDisk) -> Self { 91 | BlockDevice::Disk(Box::new(Disk::Mock(disk))) 92 | } 93 | 94 | /// Creates a loopback block device from a file path. 95 | pub fn loopback_device(device: loopback::Device) -> Self { 96 | BlockDevice::Loopback(Box::new(device)) 97 | } 98 | 99 | /// Creates a BlockDevice from a specific device path 100 | /// 101 | /// # Arguments 102 | /// 103 | /// * `device_path` - Path to the block device (e.g. "/dev/sda") 104 | /// 105 | /// # Returns 106 | /// 107 | /// The block device or an IO error if creation fails. 108 | pub fn from_sysfs_path(sysfs_root: impl AsRef, name: impl AsRef) -> io::Result { 109 | let name = name.as_ref(); 110 | let sysfs_dir = sysfs_root.as_ref(); 111 | 112 | if let Some(disk) = scsi::Disk::from_sysfs_path(sysfs_dir, name) { 113 | return Ok(BlockDevice::Disk(Box::new(Disk::Scsi(disk)))); 114 | } else if let Some(disk) = nvme::Disk::from_sysfs_path(sysfs_dir, name) { 115 | return Ok(BlockDevice::Disk(Box::new(Disk::Nvme(disk)))); 116 | } else if let Some(disk) = mmc::Disk::from_sysfs_path(sysfs_dir, name) { 117 | return Ok(BlockDevice::Disk(Box::new(Disk::Mmc(disk)))); 118 | } else if let Some(device) = virt::Disk::from_sysfs_path(sysfs_dir, name) { 119 | return Ok(BlockDevice::Disk(Box::new(Disk::Virtual(device)))); 120 | } else if let Some(device) = loopback::Device::from_sysfs_path(sysfs_dir, name) { 121 | return Ok(BlockDevice::Loopback(Box::new(device))); 122 | } 123 | 124 | Err(io::Error::new(io::ErrorKind::NotFound, "Device not found")) 125 | } 126 | 127 | /// Returns the name of the block device. 128 | pub fn name(&self) -> &str { 129 | match self { 130 | BlockDevice::Disk(disk) => disk.name(), 131 | BlockDevice::Loopback(device) => device.name(), 132 | } 133 | } 134 | 135 | /// Returns the path to the block device in /dev. 136 | pub fn device(&self) -> &Path { 137 | match self { 138 | BlockDevice::Disk(disk) => disk.device_path(), 139 | BlockDevice::Loopback(device) => device.device_path(), 140 | } 141 | } 142 | 143 | /// Discovers block devices in a specified sysroot directory. 144 | /// 145 | /// # Arguments 146 | /// 147 | /// * `sysroot` - Path to the system root directory 148 | /// 149 | /// # Returns 150 | /// 151 | /// A vector of discovered block devices or an IO error if the discovery fails. 152 | pub fn discover_in_sysroot(sysroot: impl AsRef) -> io::Result> { 153 | let sysroot = sysroot.as_ref(); 154 | let sysfs_dir = PathBuf::from(sysroot).join(SYSFS_DIR); 155 | let mut devices = Vec::new(); 156 | 157 | // Iterate over all block devices in sysfs and collect their filenames 158 | let mut entries = fs::read_dir(&sysfs_dir)? 159 | .filter_map(Result::ok) 160 | .filter_map(|e| Some(e.file_name().to_str()?.to_owned())) 161 | .collect::>(); 162 | entries.sort(); 163 | 164 | // For all the discovered block devices, try to create a Disk instance 165 | // At this point we completely ignore partitions. They come later. 166 | for entry in entries { 167 | if let Ok(device) = BlockDevice::from_sysfs_path(sysroot, &entry) { 168 | devices.push(device); 169 | } 170 | } 171 | 172 | Ok(devices) 173 | } 174 | } 175 | 176 | #[cfg(test)] 177 | mod tests { 178 | use super::*; 179 | 180 | #[test] 181 | fn test_discover() { 182 | let devices = BlockDevice::discover().unwrap(); 183 | for device in &devices { 184 | match device { 185 | BlockDevice::Disk(disk) => { 186 | println!("{}: {disk}", disk.name()); 187 | for partition in disk.partitions() { 188 | println!("├─{} {partition}", partition.name); 189 | } 190 | } 191 | BlockDevice::Loopback(device) => { 192 | if let Some(file) = device.file_path() { 193 | if let Some(disk) = device.disk() { 194 | println!("Loopback device: {} (backing file: {})", device.name(), file.display()); 195 | println!("└─Disk: {} ({})", disk.name(), disk.model().unwrap_or("Unknown")); 196 | for partition in disk.partitions() { 197 | println!(" ├─{} {partition}", partition.name); 198 | } 199 | } else { 200 | println!("Loopback device: {} (backing file: {})", device.name(), file.display()); 201 | } 202 | } else { 203 | println!("Loopback device: {}", device.name()); 204 | } 205 | } 206 | } 207 | } 208 | } 209 | 210 | #[test] 211 | fn test_partition_paths() { 212 | // Create a mock SCSI disk 213 | let scsi_disk = mock::MockDisk::new_with_name("sda", 1000, false); 214 | let device = BlockDevice::mock_device(scsi_disk); 215 | assert_eq!(device.partition_path(1).to_str().unwrap(), "/dev/sda1"); 216 | assert_eq!(device.partition_path(2).to_str().unwrap(), "/dev/sda2"); 217 | 218 | // Create a mock NVMe disk 219 | let nvme_disk = mock::MockDisk::new_with_name("nvme0n1", 1000, true); 220 | let device = BlockDevice::mock_device(nvme_disk); 221 | assert_eq!(device.partition_path(1).to_str().unwrap(), "/dev/nvme0n1p1"); 222 | assert_eq!(device.partition_path(2).to_str().unwrap(), "/dev/nvme0n1p2"); 223 | } 224 | } 225 | -------------------------------------------------------------------------------- /crates/disks/src/loopback.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: Copyright © 2025 Serpent OS Developers 2 | // 3 | // SPDX-License-Identifier: MPL-2.0 4 | 5 | //! Loopback device enumeration and handling. 6 | //! 7 | //! Loopback devices in Linux are block devices that map files to block devices. 8 | //! This module handles enumeration and management of these devices, 9 | //! which appear as `/dev/loop*` block devices. 10 | 11 | use std::path::{Path, PathBuf}; 12 | 13 | use crate::{sysfs, BasicDisk, DiskInit, DEVFS_DIR, SYSFS_DIR}; 14 | 15 | /// Represents a loop device. 16 | #[derive(Debug)] 17 | pub struct Device { 18 | /// The device name (e.g. "loop0", "loop1") 19 | name: String, 20 | 21 | /// Path to the device in /dev 22 | device: PathBuf, 23 | 24 | /// Optional backing file path 25 | file: Option, 26 | 27 | /// Optional disk device if the loop device is backed by a disk 28 | disk: Option, 29 | } 30 | 31 | impl Device { 32 | /// Creates a new Device instance from a sysfs path if the device name matches loop device pattern. 33 | /// 34 | /// # Arguments 35 | /// 36 | /// * `sysroot` - The root path of the sysfs filesystem 37 | /// * `name` - The device name to check (e.g. "loop0", "loop1") 38 | /// 39 | /// # Returns 40 | /// 41 | /// * `Some(Device)` if the name matches loop pattern (starts with "loop" followed by numbers) 42 | /// * `None` if the name doesn't match or the device can't be initialized 43 | pub fn from_sysfs_path(sysroot: &Path, name: &str) -> Option { 44 | let matching = name.starts_with("loop") && name[4..].chars().all(char::is_numeric); 45 | let node = sysroot.join(SYSFS_DIR).join(name); 46 | let file = sysfs::read::(&node, "loop/backing_file"); 47 | let disk = file.as_ref().and_then(|_| BasicDisk::from_sysfs_path(sysroot, name)); 48 | if matching { 49 | Some(Self { 50 | name: name.to_owned(), 51 | device: PathBuf::from("/").join(DEVFS_DIR).join(name), 52 | file, 53 | disk, 54 | }) 55 | } else { 56 | None 57 | } 58 | } 59 | 60 | /// Creates a new Device instance from a device path. 61 | pub fn from_device_path(device: &Path) -> Option { 62 | let name = device.file_name()?.to_string_lossy().to_string(); 63 | Self::from_sysfs_path(&PathBuf::from("/"), &name) 64 | } 65 | 66 | /// Returns the device name. 67 | pub fn name(&self) -> &str { 68 | &self.name 69 | } 70 | 71 | /// Returns the device path. 72 | pub fn device_path(&self) -> &Path { 73 | &self.device 74 | } 75 | 76 | /// Returns the backing file path. 77 | pub fn file_path(&self) -> Option<&Path> { 78 | self.file.as_deref() 79 | } 80 | 81 | /// Returns the disk device if the loop device is backed by a disk. 82 | pub fn disk(&self) -> Option<&BasicDisk> { 83 | self.disk.as_ref() 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /crates/disks/src/mmc.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: Copyright © 2025 Serpent OS Developers 2 | // 3 | // SPDX-License-Identifier: MPL-2.0 4 | 5 | //! MMC device enumeration and handling 6 | //! 7 | //! This module provides functionality to enumerate and handle MMC (MultiMediaCard) 8 | //! storage devices by parsing sysfs paths and device names. 9 | 10 | use crate::{BasicDisk, DiskInit}; 11 | use regex::Regex; 12 | use std::{ops::Deref, path::Path, sync::OnceLock}; 13 | 14 | /// Regex pattern to match valid MMC device names (e.g. mmcblk0) 15 | static MMC_PATTERN: OnceLock = OnceLock::new(); 16 | 17 | /// Represents an MMC disk device 18 | #[derive(Debug)] 19 | pub struct Disk(pub BasicDisk); 20 | 21 | impl Deref for Disk { 22 | type Target = BasicDisk; 23 | 24 | fn deref(&self) -> &Self::Target { 25 | &self.0 26 | } 27 | } 28 | 29 | impl DiskInit for Disk { 30 | /// Creates a new MMC disk from a sysfs path and device name 31 | /// 32 | /// # Arguments 33 | /// * `sysroot` - The sysfs root path 34 | /// * `name` - The device name to check 35 | /// 36 | /// # Returns 37 | /// * `Some(Disk)` if the device name matches MMC pattern 38 | /// * `None` if name doesn't match or basic disk creation fails 39 | fn from_sysfs_path(sysroot: &Path, name: &str) -> Option { 40 | let regex = 41 | MMC_PATTERN.get_or_init(|| Regex::new(r"^mmcblk\d+$").expect("Failed to initialise known-working regex")); 42 | if regex.is_match(name) { 43 | Some(Self(BasicDisk::from_sysfs_path(sysroot, name)?)) 44 | } else { 45 | None 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /crates/disks/src/mock.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: Copyright © 2025 Serpent OS Developers 2 | // 3 | // SPDX-License-Identifier: MPL-2.0 4 | 5 | //! Mock disk device for testing. 6 | //! 7 | //! This module provides a mock disk implementation that can be used for testing 8 | //! disk-related functionality without requiring actual hardware devices. 9 | 10 | use std::{ops::Deref, path::PathBuf}; 11 | 12 | use crate::{partition::Partition, BasicDisk}; 13 | 14 | /// Represents a mock disk device. 15 | /// 16 | /// This struct wraps a BasicDisk to provide mock functionality for testing. 17 | #[derive(Debug)] 18 | pub struct MockDisk { 19 | basic_disk: BasicDisk, 20 | pub parts_prefix: bool, 21 | } 22 | 23 | impl Deref for MockDisk { 24 | type Target = BasicDisk; 25 | 26 | fn deref(&self) -> &Self::Target { 27 | &self.basic_disk 28 | } 29 | } 30 | 31 | impl MockDisk { 32 | /// Creates a new mock disk with the specified size in bytes 33 | pub fn new(size_bytes: u64) -> Self { 34 | Self::new_with_name("mock0", size_bytes, false) 35 | } 36 | 37 | pub fn new_with_name(name: &str, size_bytes: u64, parts_prefix: bool) -> Self { 38 | let sectors = size_bytes / 512; 39 | let disk = BasicDisk { 40 | name: name.to_string(), 41 | sectors, 42 | device: PathBuf::from(format!("/dev/{name}")), 43 | model: Some("Mock Device".to_string()), 44 | vendor: Some("Mock Vendor".to_string()), 45 | partitions: Vec::new(), 46 | }; 47 | 48 | Self { 49 | basic_disk: disk, 50 | parts_prefix, 51 | } 52 | } 53 | 54 | /// Add a partition to the mock disk at the specified byte offsets 55 | pub fn add_partition(&mut self, start_bytes: u64, end_bytes: u64) { 56 | let partition_number = self.basic_disk.partitions().len() + 1; 57 | let start = start_bytes / 512; 58 | let end = end_bytes / 512; 59 | 60 | let partition = Partition { 61 | number: partition_number as u32, 62 | start, 63 | end, 64 | size: end - start, 65 | name: format!("mock0p{partition_number}"), 66 | node: PathBuf::from("/sys/class/block/mock0/mock0p1"), 67 | device: PathBuf::from(format!("/dev/mock0p{partition_number}")), 68 | }; 69 | 70 | self.basic_disk.partitions_mut().push(partition); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /crates/disks/src/nvme.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: Copyright © 2025 Serpent OS Developers 2 | // 3 | // SPDX-License-Identifier: MPL-2.0 4 | 5 | //! NVME device enumeration and handling 6 | //! 7 | //! This module provides functionality to enumerate and handle NVMe (Non-Volatile Memory Express) 8 | //! storage devices by parsing sysfs paths and device names. 9 | 10 | use crate::{BasicDisk, DiskInit}; 11 | use regex::Regex; 12 | use std::{ops::Deref, path::Path, sync::OnceLock}; 13 | 14 | /// Regex pattern to match valid NVMe device names (e.g. nvme0n1) 15 | static NVME_PATTERN: OnceLock = OnceLock::new(); 16 | 17 | /// Represents an NVMe disk device 18 | #[derive(Debug)] 19 | pub struct Disk(pub BasicDisk); 20 | 21 | impl Deref for Disk { 22 | type Target = BasicDisk; 23 | 24 | fn deref(&self) -> &Self::Target { 25 | &self.0 26 | } 27 | } 28 | 29 | impl DiskInit for Disk { 30 | /// Creates a new NVMe disk from a sysfs path and device name 31 | /// 32 | /// # Arguments 33 | /// * `sysroot` - The sysfs root path 34 | /// * `name` - The device name to check 35 | /// 36 | /// # Returns 37 | /// * `Some(Disk)` if the device name matches NVMe pattern 38 | /// * `None` if name doesn't match or basic disk creation fails 39 | fn from_sysfs_path(sysroot: &Path, name: &str) -> Option { 40 | let regex = NVME_PATTERN 41 | .get_or_init(|| Regex::new(r"^nvme\d+n\d+$").expect("Failed to initialise known-working regex")); 42 | if regex.is_match(name) { 43 | Some(Self(BasicDisk::from_sysfs_path(sysroot, name)?)) 44 | } else { 45 | None 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /crates/disks/src/partition.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: Copyright © 2025 Serpent OS Developers 2 | // 3 | // SPDX-License-Identifier: MPL-2.0 4 | 5 | use std::fmt; 6 | use std::path::{Path, PathBuf}; 7 | 8 | use crate::{sysfs, DEVFS_DIR, SYSFS_DIR}; 9 | 10 | /// Represents a partition on a disk device 11 | /// - Size in sectors 12 | #[derive(Debug, Default)] 13 | pub struct Partition { 14 | /// Name of the partition 15 | pub name: String, 16 | /// Partition number on the disk 17 | pub number: u32, 18 | /// Starting sector of the partition 19 | pub start: u64, 20 | /// Ending sector of the partition 21 | pub end: u64, 22 | /// Size of partition in sectors 23 | pub size: u64, 24 | /// Path to the partition node in sysfs 25 | pub node: PathBuf, 26 | /// Path to the partition device in /dev 27 | pub device: PathBuf, 28 | } 29 | 30 | impl fmt::Display for Partition { 31 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 32 | write!( 33 | f, 34 | "{name} {size:.2} GiB", 35 | name = self.name, 36 | size = self.size as f64 * 512.0 / (1024.0 * 1024.0 * 1024.0) 37 | ) 38 | } 39 | } 40 | 41 | impl Partition { 42 | /// Creates a new Partition instance from a sysfs path and partition name. 43 | /// 44 | /// # Arguments 45 | /// * `sysroot` - Base path to sysfs 46 | /// * `name` - Name of the partition 47 | /// 48 | /// # Returns 49 | /// * `Some(Partition)` if partition exists and is valid 50 | /// * `None` if partition doesn't exist or is invalid 51 | pub fn from_sysfs_path(sysroot: &Path, name: &str) -> Option { 52 | let node = sysroot.join(SYSFS_DIR).join(name); 53 | let partition_no: u32 = sysfs::read(&node, "partition")?; 54 | let start = sysfs::read(&node, "start")?; 55 | let size = sysfs::read(&node, "size")?; 56 | Some(Self { 57 | name: name.to_owned(), 58 | number: partition_no, 59 | start, 60 | size, 61 | end: start + size, 62 | node, 63 | device: sysroot.join(DEVFS_DIR).join(name), 64 | }) 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /crates/disks/src/scsi.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: Copyright © 2025 Serpent OS Developers 2 | // 3 | // SPDX-License-Identifier: MPL-2.0 4 | 5 | //! SCSI device enumeration and handling. 6 | //! 7 | //! In modern Linux systems, all libata devices are exposed as SCSI devices through 8 | //! the SCSI subsystem. This module handles enumeration and management of these devices, 9 | //! which appear as `/dev/sd*` block devices. 10 | 11 | use std::{ops::Deref, path::Path}; 12 | 13 | use crate::{BasicDisk, DiskInit}; 14 | 15 | /// Represents a SCSI disk device. 16 | /// 17 | /// This struct wraps a BasicDisk to provide SCSI-specific functionality. 18 | #[derive(Debug)] 19 | pub struct Disk(pub BasicDisk); 20 | 21 | impl Deref for Disk { 22 | type Target = BasicDisk; 23 | 24 | fn deref(&self) -> &Self::Target { 25 | &self.0 26 | } 27 | } 28 | 29 | impl DiskInit for Disk { 30 | /// Creates a new Disk instance from a sysfs path if the device name matches SCSI naming pattern. 31 | /// 32 | /// # Arguments 33 | /// 34 | /// * `sysroot` - The root path of the sysfs filesystem 35 | /// * `name` - The device name to check (e.g. "sda", "sdb") 36 | /// 37 | /// # Returns 38 | /// 39 | /// * `Some(Disk)` if the name matches SCSI pattern (starts with "sd" followed by letters) 40 | /// * `None` if the name doesn't match or the device can't be initialized 41 | fn from_sysfs_path(sysroot: &Path, name: &str) -> Option { 42 | let matching = name.starts_with("sd") && name[2..].chars().all(char::is_alphabetic); 43 | if matching { 44 | Some(Self(BasicDisk::from_sysfs_path(sysroot, name)?)) 45 | } else { 46 | None 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /crates/disks/src/sizing.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: Copyright © 2025 Serpent OS Developers 2 | // SPDX-FileCopyrightText: Copyright © 2025 AerynOS Developers 3 | // 4 | // SPDX-License-Identifier: MPL-2.0 5 | 6 | /// Format a size in bytes into a human readable string 7 | /// Format a byte size into a human-readable string with appropriate units 8 | /// 9 | /// # Examples 10 | /// 11 | /// ``` 12 | /// use disks::format_size; 13 | /// assert_eq!(format_size(1500), "1.5KiB"); 14 | /// assert_eq!(format_size(1500000), "1.4MiB"); 15 | /// ``` 16 | pub fn format_size(size: u64) -> String { 17 | const KB: f64 = 1024.0; 18 | const MB: f64 = KB * 1024.0; 19 | const GB: f64 = MB * 1024.0; 20 | const TB: f64 = GB * 1024.0; 21 | 22 | let size = size as f64; 23 | if size >= TB { 24 | format!("{:.1}TiB", size / TB) 25 | } else if size >= GB { 26 | format!("{:.1}GiB", size / GB) 27 | } else if size >= MB { 28 | format!("{:.1}MiB", size / MB) 29 | } else if size >= KB { 30 | format!("{:.1}KiB", size / KB) 31 | } else { 32 | format!("{size}B") 33 | } 34 | } 35 | 36 | /// Format a disk position as a percentage and absolute size 37 | /// Format a disk position as both a percentage and absolute size 38 | /// 39 | /// This is useful for displaying partition locations in a user-friendly way. 40 | /// 41 | /// # Examples 42 | /// 43 | /// ``` 44 | /// use disks::format_position; 45 | /// let total = 1000; 46 | /// assert_eq!(format_position(500, total), "50% (500B)"); 47 | /// ``` 48 | pub fn format_position(pos: u64, total: u64) -> String { 49 | format!("{}% ({})", (pos as f64 / total as f64 * 100.0) as u64, format_size(pos)) 50 | } 51 | 52 | /// Check if a value is already aligned to the given boundary 53 | pub fn is_aligned(value: u64, alignment: u64) -> bool { 54 | value % alignment == 0 55 | } 56 | 57 | /// Align up to the nearest multiple of alignment, unless already aligned 58 | pub fn align_up(value: u64, alignment: u64) -> u64 { 59 | match value % alignment { 60 | 0 => value, 61 | remainder if remainder > (alignment / 2) => value + (alignment - remainder), 62 | remainder => value - remainder, 63 | } 64 | } 65 | 66 | /// Align down to the nearest multiple of alignment, unless already aligned 67 | pub fn align_down(value: u64, alignment: u64) -> u64 { 68 | match value % alignment { 69 | 0 => value, 70 | remainder if remainder < (alignment / 2) => value - remainder, 71 | remainder => value + (alignment - remainder), 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /crates/disks/src/sysfs.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: Copyright © 2025 Serpent OS Developers 2 | // 3 | // SPDX-License-Identifier: MPL-2.0 4 | 5 | //! Helper functions for interacting with Linux sysfs interfaces 6 | 7 | use std::{fs, path::Path, str::FromStr}; 8 | 9 | /// Reads a value from a sysfs node and attempts to parse it to type T 10 | /// 11 | /// # Arguments 12 | /// 13 | /// * `node` - Fully qualified path to specific sysfs node 14 | /// * `key` - Name of the sysfs attribute to read 15 | /// 16 | /// # Returns 17 | /// 18 | /// * `Some(T)` if the value was successfully read and parsed 19 | /// * `None` if the file could not be read or parsed 20 | /// 21 | /// # Type Parameters 22 | /// 23 | /// * `T` - Target type that implements FromStr for parsing the raw value 24 | pub(crate) fn read(node: &Path, key: &str) -> Option 25 | where 26 | T: FromStr, 27 | { 28 | fs::read_to_string(node.join(key)).ok()?.trim().parse().ok() 29 | } 30 | -------------------------------------------------------------------------------- /crates/disks/src/virt.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: Copyright © 2025 Serpent OS Developers 2 | // 3 | // SPDX-License-Identifier: MPL-2.0 4 | 5 | //! Virtual disk device enumeration and handling. 6 | //! 7 | //! In Linux systems, virtual disk devices are exposed through 8 | //! the block subsystem. This module handles enumeration and management of these devices, 9 | //! which appear as `/dev/vd*` block devices. 10 | 11 | use std::{ops::Deref, path::Path}; 12 | 13 | use crate::{BasicDisk, DiskInit}; 14 | 15 | /// Represents a virtual disk device. 16 | /// 17 | /// This struct wraps a BasicDisk to provide virtual disk-specific functionality. 18 | #[derive(Debug)] 19 | pub struct Disk(pub BasicDisk); 20 | 21 | impl Deref for Disk { 22 | type Target = BasicDisk; 23 | 24 | fn deref(&self) -> &Self::Target { 25 | &self.0 26 | } 27 | } 28 | 29 | impl DiskInit for Disk { 30 | /// Creates a new Disk instance from a sysfs path if the device name matches virtual disk naming pattern. 31 | /// 32 | /// # Arguments 33 | /// 34 | /// * `sysroot` - The root path of the sysfs filesystem 35 | /// * `name` - The device name to check (e.g. "vda", "vdb") 36 | /// 37 | /// # Returns 38 | /// 39 | /// * `Some(Disk)` if the name matches virtual disk pattern (starts with "vd" followed by letters) 40 | /// * `None` if the name doesn't match or the device can't be initialized 41 | fn from_sysfs_path(sysroot: &Path, name: &str) -> Option { 42 | let matching = name.starts_with("vd") && name[2..].chars().all(char::is_alphabetic); 43 | if matching { 44 | Some(Self(BasicDisk::from_sysfs_path(sysroot, name)?)) 45 | } else { 46 | None 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /crates/disktester/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "disktester" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | [dependencies] 7 | disks = { path = "../disks" } 8 | partitioning = { path = "../partitioning" } 9 | provisioning = { path = "../provisioning" } 10 | -------------------------------------------------------------------------------- /crates/disktester/src/main.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: Copyright © 2025 Serpent OS Developers 2 | // 3 | // SPDX-License-Identifier: MPL-2.0 4 | 5 | use std::path::{Path, PathBuf}; 6 | 7 | use disks::BlockDevice; 8 | use partitioning::{blkpg, loopback, sparsefile, writer::DiskWriter, Formatter}; 9 | use provisioning::{Parser, Provisioner, StrategyDefinition}; 10 | 11 | /// Loads provisioning strategies from a configuration file 12 | /// 13 | /// # Arguments 14 | /// * `path` - Path to the provisioning configuration file 15 | /// 16 | /// # Returns 17 | /// * `Result>` - Vector of loaded strategy definitions 18 | fn load_provisioning(path: impl Into) -> Result, Box> { 19 | let p = path.into(); 20 | let parser = Parser::new_for_path(p)?; 21 | Ok(parser.strategies) 22 | } 23 | 24 | /// Applies partitioning strategies to a block device 25 | /// 26 | /// # Arguments 27 | /// * `whence` - Path to the block device to partition 28 | /// 29 | /// # Returns 30 | /// * `Result<()>` - Success or error status 31 | fn apply_partitioning(whence: &Path) -> Result<(), Box> { 32 | // Initialize provisioner and load strategies 33 | let mut prov = Provisioner::new(); 34 | let strategies = load_provisioning("crates/provisioning/tests/use_whole_disk.kdl")?; 35 | for strategy in &strategies { 36 | prov.add_strategy(strategy); 37 | } 38 | 39 | // Set up block device 40 | let device = disks::loopback::Device::from_device_path(whence).ok_or("Not a loop device")?; 41 | let blk = BlockDevice::loopback_device(device); 42 | prov.push_device(&blk); 43 | 44 | // Generate and validate partitioning plans 45 | let plans = prov.plan(); 46 | for plan in &plans { 47 | eprintln!("Plan: {}", plan.strategy.name); 48 | } 49 | let plan = plans.first().ok_or("No plans")?; 50 | 51 | // Apply partitioning changes 52 | for (disk, device_plan) in plan.device_assignments.iter() { 53 | eprintln!("strategy for {} is now: {}", disk, device_plan.strategy.describe()); 54 | eprintln!("After: {}", device_plan.planner.describe_changes()); 55 | 56 | let disk_writer = DiskWriter::new(device_plan.device, &device_plan.planner); 57 | disk_writer.simulate()?; 58 | eprintln!("Simulation passed"); 59 | disk_writer.write()?; 60 | } 61 | 62 | // Sync partition table changes 63 | blkpg::sync_gpt_partitions(whence)?; 64 | 65 | let mut formatters = plan 66 | .filesystems 67 | .iter() 68 | .map(|(device, fs)| { 69 | let formatter = Formatter::new(fs.clone()).force(); 70 | formatter.format(device) 71 | }) 72 | .collect::>(); 73 | 74 | for operation in formatters.iter_mut() { 75 | match operation.output() { 76 | Ok(output) => { 77 | let stdout = str::from_utf8(&output.stdout).expect("Invalid UTF-8"); 78 | if output.status.success() { 79 | eprintln!("Format success: {stdout}"); 80 | } else { 81 | let stderr = str::from_utf8(&output.stderr).expect("Invalid UTF-8"); 82 | eprintln!("Format error: {stderr}"); 83 | } 84 | eprintln!("Format output: {stdout}"); 85 | } 86 | Err(e) => { 87 | eprintln!("Format error: {e}"); 88 | } 89 | } 90 | } 91 | 92 | eprintln!("Format operations: {formatters:?}"); 93 | 94 | for (role, device) in plan.role_mounts.iter() { 95 | eprintln!("To mount: {:?} as {:?} (`{}`)", device, role, role.as_path()); 96 | } 97 | 98 | Ok(()) 99 | } 100 | 101 | /// Main entry point - creates and partitions a loopback device 102 | fn main() -> Result<(), Box> { 103 | // Create sparse file and attach loopback device 104 | sparsefile::create("lesparse.img", 32 * 1024 * 1024 * 1024)?; 105 | let l = loopback::LoopDevice::create()?; 106 | l.attach("lesparse.img")?; 107 | 108 | eprintln!("Loopback device: {:?}", &l.path); 109 | 110 | // Apply partitioning and handle errors 111 | let whence = PathBuf::from(&l.path); 112 | if let Err(e) = apply_partitioning(&whence) { 113 | eprintln!("Error applying partitioning: {e}"); 114 | } 115 | 116 | // Clean up loopback device 117 | l.detach()?; 118 | 119 | Ok(()) 120 | } 121 | -------------------------------------------------------------------------------- /crates/partitioning/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "partitioning" 3 | version = "0.1.0" 4 | edition = "2021" 5 | description = "A library for working directly with partitions" 6 | 7 | [dependencies] 8 | disks = { path = "../disks" } 9 | types = { path = "../types" } 10 | thiserror.workspace = true 11 | log.workspace = true 12 | gpt.workspace = true 13 | nix.workspace = true 14 | uuid.workspace = true 15 | linux-raw-sys = { workspace = true, features = ["loop_device", "ioctl"] } 16 | 17 | [dev-dependencies] 18 | test-log.workspace = true 19 | -------------------------------------------------------------------------------- /crates/partitioning/src/attributes.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: Copyright © 2025 AerynOS Developers 2 | // 3 | // SPDX-License-Identifier: MPL-2.0 4 | 5 | use gpt::partition_types; 6 | use types::{Filesystem, PartitionRole}; 7 | use uuid::Uuid; 8 | 9 | /// Represents the table attributes of a GPT partition 10 | #[derive(Debug, Clone)] 11 | pub struct GptAttributes { 12 | /// The type GUID that identifies the partition type 13 | pub type_guid: partition_types::Type, 14 | /// Optional name for the partition 15 | pub name: Option, 16 | /// Optional UUID for the partition 17 | pub uuid: Option, 18 | } 19 | 20 | impl Default for GptAttributes { 21 | fn default() -> Self { 22 | Self { 23 | type_guid: partition_types::BASIC, 24 | name: None, 25 | uuid: None, 26 | } 27 | } 28 | } 29 | 30 | /// Represents attributes specific to different partition table types 31 | #[derive(Debug, Clone)] 32 | pub enum TableAttributes { 33 | /// GPT partition attributes 34 | Gpt(GptAttributes), 35 | //Mbr(MbrAttributes), 36 | } 37 | 38 | impl TableAttributes { 39 | /// Returns a reference to the GPT attributes if this is a GPT partition 40 | /// 41 | /// # Returns 42 | /// - `Some(&GptAttributes)` if this is a GPT partition 43 | /// - `None` if this is not a GPT partition 44 | pub fn as_gpt(&self) -> Option<&GptAttributes> { 45 | match self { 46 | TableAttributes::Gpt(attr) => Some(attr), 47 | } 48 | } 49 | } 50 | 51 | /// Represents the attributes of a partition 52 | #[derive(Debug, Clone)] 53 | pub struct PartitionAttributes { 54 | pub table: TableAttributes, 55 | pub role: Option, 56 | pub filesystem: Option, 57 | } 58 | -------------------------------------------------------------------------------- /crates/partitioning/src/blkpg.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: Copyright © 2025 Serpent OS Developers 2 | // 3 | // SPDX-License-Identifier: MPL-2.0 4 | 5 | use disks::{BasicDisk, DiskInit}; 6 | use log::{debug, error, info}; 7 | use std::{ 8 | fs::File, 9 | io, 10 | os::fd::{AsFd, AsRawFd}, 11 | path::{Path, PathBuf}, 12 | }; 13 | use thiserror::Error; 14 | 15 | pub use gpt; 16 | use linux_raw_sys::ioctl::BLKPG; 17 | use nix::libc; 18 | 19 | /// Errors that can occur during partition operations 20 | #[derive(Error, Debug)] 21 | pub enum Error { 22 | /// IO operation error 23 | #[error("IO error: {0}")] 24 | Io(#[from] io::Error), 25 | /// GPT-specific error 26 | #[error("GPT error: {0}")] 27 | Gpt(#[from] gpt::GptError), 28 | } 29 | 30 | /// Represents a block device partition for IOCTL operations 31 | #[repr(C)] 32 | struct BlkpgPartition { 33 | start: i64, 34 | length: i64, 35 | pno: i32, 36 | devname: [u8; 64], 37 | volname: [u8; 64], 38 | } 39 | 40 | /// IOCTL structure for partition operations 41 | #[repr(C)] 42 | struct BlkpgIoctl { 43 | op: i32, 44 | flags: i32, 45 | datalen: i32, 46 | data: *mut BlkpgPartition, 47 | } 48 | 49 | const BLKPG_ADD_PARTITION: i32 = 1; 50 | const BLKPG_DEL_PARTITION: i32 = 2; 51 | 52 | /// Adds a new partition to the specified block device 53 | /// 54 | /// # Arguments 55 | /// * `fd` - File descriptor for the block device 56 | /// * `partition_number` - Number to assign to the new partition 57 | /// * `start` - Starting offset in bytes 58 | /// * `length` - Length of partition in bytes 59 | /// 60 | /// # Returns 61 | /// `io::Result<()>` indicating success or failure 62 | pub(crate) fn add_partition(fd: F, partition_number: i32, start: i64, length: i64) -> io::Result<()> 63 | where 64 | F: AsRawFd, 65 | { 66 | debug!("Initiating partition addition - Number: {partition_number}, Start: {start}, Length: {length}"); 67 | let mut part = BlkpgPartition { 68 | start, 69 | length, 70 | pno: partition_number, 71 | devname: [0; 64], 72 | volname: [0; 64], 73 | }; 74 | 75 | let mut ioctl = BlkpgIoctl { 76 | op: BLKPG_ADD_PARTITION, 77 | flags: 0, 78 | datalen: std::mem::size_of::() as i32, 79 | data: &mut part, 80 | }; 81 | 82 | let res = unsafe { libc::ioctl(fd.as_raw_fd(), BLKPG as _, &mut ioctl) }; 83 | if res < 0 { 84 | let err = io::Error::last_os_error(); 85 | error!("Partition creation failed: {err}"); 86 | return Err(err); 87 | } 88 | info!("Successfully created partition {partition_number}"); 89 | Ok(()) 90 | } 91 | 92 | /// Deletes a partition from the specified block device 93 | /// 94 | /// # Arguments 95 | /// * `fd` - File descriptor for the block device 96 | /// * `partition_number` - Number of the partition to delete 97 | /// 98 | /// # Returns 99 | /// `io::Result<()>` indicating success or failure 100 | pub(crate) fn delete_partition(fd: F, partition_number: i32) -> io::Result<()> 101 | where 102 | F: AsRawFd, 103 | { 104 | info!("Initiating deletion of partition {partition_number}"); 105 | let mut part = BlkpgPartition { 106 | start: 0, 107 | length: 0, 108 | pno: partition_number, 109 | devname: [0; 64], 110 | volname: [0; 64], 111 | }; 112 | 113 | let mut ioctl = BlkpgIoctl { 114 | op: BLKPG_DEL_PARTITION, 115 | flags: 0, 116 | datalen: std::mem::size_of::() as i32, 117 | data: &mut part, 118 | }; 119 | 120 | let res = unsafe { libc::ioctl(fd.as_raw_fd(), BLKPG as _, &mut ioctl) }; 121 | if res < 0 { 122 | let err = io::Error::last_os_error(); 123 | error!("Failed to delete partition {partition_number}: {err}"); 124 | return Err(err); 125 | } 126 | info!("Successfully removed partition {partition_number}"); 127 | Ok(()) 128 | } 129 | 130 | /// Removes all kernel partitions for the specified block device 131 | /// 132 | /// # Arguments 133 | /// * `path` - Path to the block device 134 | /// 135 | /// # Returns 136 | /// `Result<(), Error>` indicating success or partition operation failure 137 | pub fn remove_kernel_partitions>(path: P) -> Result<(), Error> { 138 | debug!("Beginning partition cleanup process for {:?}", path.as_ref()); 139 | let file = File::open(&path)?; 140 | 141 | // Find the disk for enumeration purposes 142 | let base_name = path 143 | .as_ref() 144 | .file_name() 145 | .ok_or(Error::Io(io::Error::from(io::ErrorKind::InvalidInput)))? 146 | .to_string_lossy() 147 | .to_string(); 148 | let disk = BasicDisk::from_sysfs_path(&PathBuf::from("/"), &base_name) 149 | .ok_or(Error::Io(io::Error::from(io::ErrorKind::InvalidInput)))?; 150 | 151 | for partition in disk.partitions() { 152 | let _ = delete_partition(file.as_raw_fd(), partition.number as i32); 153 | } 154 | 155 | info!("Successfully removed all kernel partitions"); 156 | Ok(()) 157 | } 158 | 159 | /// Creates kernel partitions based on the current GPT table 160 | /// 161 | /// # Arguments 162 | /// * `path` - Path to the block device 163 | /// 164 | /// # Returns 165 | /// `Result<(), Error>` indicating success or partition operation failure 166 | pub fn create_kernel_partitions>(path: P) -> Result<(), Error> { 167 | info!("Creating kernel partitions from GPT for {:?}", path.as_ref()); 168 | let file = File::open(&path)?; 169 | 170 | // Read GPT table 171 | debug!("Reading GPT partition table"); 172 | let gpt = gpt::GptConfig::new().writable(false).open(&path)?; 173 | let partitions = gpt.partitions(); 174 | let block_size = 512; 175 | info!("Located {} partitions (block size: {})", partitions.len(), block_size); 176 | 177 | // Add partitions from GPT 178 | debug!("Beginning partition creation from GPT table"); 179 | for (i, partition) in partitions.iter() { 180 | add_partition( 181 | file.as_fd(), 182 | *i as i32, 183 | partition.first_lba as i64 * block_size, 184 | (partition.last_lba - partition.first_lba + 1) as i64 * block_size, 185 | )?; 186 | } 187 | 188 | info!("GPT partition creation completed successfully"); 189 | Ok(()) 190 | } 191 | 192 | /// Updates kernel partition representations to match the GPT table 193 | /// 194 | /// # Arguments 195 | /// * `path` - Path to the block device 196 | /// 197 | /// # Returns 198 | /// `Result<(), Error>` indicating success or partition operation failure 199 | pub fn sync_gpt_partitions>(path: P) -> Result<(), Error> { 200 | info!("Initiating GPT partition synchronization for {:?}", path.as_ref()); 201 | 202 | remove_kernel_partitions(&path)?; 203 | create_kernel_partitions(&path)?; 204 | 205 | info!("GPT partition synchronization completed successfully"); 206 | Ok(()) 207 | } 208 | -------------------------------------------------------------------------------- /crates/partitioning/src/formatter.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: Copyright © 2025 AerynOS Developers 2 | // 3 | // SPDX-License-Identifier: MPL-2.0 4 | 5 | use std::{path::Path, process::Command}; 6 | 7 | use types::Filesystem; 8 | 9 | /// Trait for generating filesystem-specific formatting commands and arguments 10 | pub trait FilesystemExt { 11 | /// Returns the appropriate mkfs command for the filesystem 12 | fn mkfs_command(&self) -> &str; 13 | 14 | /// Returns the command-line arguments for setting UUID, if applicable 15 | fn uuid_arg(&self) -> Vec; 16 | 17 | /// Returns the command-line arguments for setting filesystem label, if applicable 18 | fn label_arg(&self) -> Vec; 19 | 20 | /// Returns the force format argument if applicable 21 | fn force_arg(&self) -> Vec; 22 | } 23 | 24 | impl FilesystemExt for Filesystem { 25 | fn mkfs_command(&self) -> &str { 26 | match self { 27 | Filesystem::Fat32 { .. } => "mkfs.fat", 28 | Filesystem::Standard { filesystem_type, .. } => match filesystem_type { 29 | types::StandardFilesystemType::F2fs => "mkfs.f2fs", 30 | types::StandardFilesystemType::Ext4 => "mkfs.ext4", 31 | types::StandardFilesystemType::Xfs => "mkfs.xfs", 32 | types::StandardFilesystemType::Swap => "mkswap", 33 | }, 34 | } 35 | } 36 | 37 | fn uuid_arg(&self) -> Vec { 38 | match self { 39 | Filesystem::Fat32 { volume_id, .. } => { 40 | if let Some(id) = volume_id { 41 | vec!["-i".to_string(), id.to_string()] 42 | } else { 43 | vec![] 44 | } 45 | } 46 | Filesystem::Standard { 47 | filesystem_type, uuid, .. 48 | } => { 49 | if let Some(uuid) = uuid { 50 | match filesystem_type { 51 | types::StandardFilesystemType::Ext4 => vec!["-U".to_string(), uuid.to_string()], 52 | types::StandardFilesystemType::F2fs => vec!["-U".to_string(), uuid.to_string()], 53 | types::StandardFilesystemType::Xfs => vec!["-m".to_string(), format!("uuid={}", uuid)], 54 | types::StandardFilesystemType::Swap => vec!["-U".to_string(), uuid.to_string()], 55 | } 56 | } else { 57 | vec![] 58 | } 59 | } 60 | } 61 | } 62 | 63 | fn label_arg(&self) -> Vec { 64 | match self { 65 | Filesystem::Fat32 { label, .. } => { 66 | if let Some(label) = label { 67 | vec!["-n".to_string(), label.to_string()] 68 | } else { 69 | vec![] 70 | } 71 | } 72 | Filesystem::Standard { 73 | filesystem_type, label, .. 74 | } => { 75 | if let Some(label) = label { 76 | match filesystem_type { 77 | types::StandardFilesystemType::Ext4 => vec!["-L".to_string(), label.to_string()], 78 | types::StandardFilesystemType::F2fs => vec!["-l".to_string(), label.to_string()], 79 | types::StandardFilesystemType::Xfs => vec!["-L".to_string(), label.to_string()], 80 | types::StandardFilesystemType::Swap => vec!["-L".to_string(), label.to_string()], 81 | } 82 | } else { 83 | vec![] 84 | } 85 | } 86 | } 87 | } 88 | 89 | fn force_arg(&self) -> Vec { 90 | match self { 91 | Filesystem::Fat32 { .. } => vec![], 92 | Filesystem::Standard { filesystem_type, .. } => match filesystem_type { 93 | types::StandardFilesystemType::F2fs => vec!["-f".to_string()], 94 | types::StandardFilesystemType::Ext4 => vec!["-F".to_string()], 95 | types::StandardFilesystemType::Xfs => vec!["-f".to_string()], 96 | types::StandardFilesystemType::Swap => vec!["-f".to_string()], 97 | }, 98 | } 99 | } 100 | } 101 | 102 | /// Struct for formatting filesystems on devices 103 | pub struct Formatter { 104 | pub filesystem: Filesystem, 105 | pub force: bool, 106 | } 107 | 108 | impl Formatter { 109 | /// Creates a new Formatter for the given filesystem 110 | pub fn new(filesystem: Filesystem) -> Self { 111 | Self { 112 | filesystem, 113 | force: false, 114 | } 115 | } 116 | 117 | /// Forces the format operation 118 | pub fn force(self) -> Self { 119 | Self { force: true, ..self } 120 | } 121 | 122 | /// Returns a Command configured to format the given device with the filesystem 123 | pub fn format(&self, device: &Path) -> Command { 124 | let mut cmd = Command::new(self.filesystem.mkfs_command()); 125 | 126 | cmd.args(self.filesystem.uuid_arg()); 127 | cmd.args(self.filesystem.label_arg()); 128 | if self.force { 129 | cmd.args(self.filesystem.force_arg()); 130 | } 131 | 132 | cmd.arg(device); 133 | cmd 134 | } 135 | } 136 | 137 | #[cfg(test)] 138 | mod tests { 139 | use super::*; 140 | use uuid::Uuid; 141 | 142 | #[test] 143 | fn test_fat32_args() { 144 | let fs = Filesystem::Fat32 { 145 | label: Some("BOOT".to_string()), 146 | volume_id: Some(1234), 147 | }; 148 | 149 | assert_eq!(fs.mkfs_command(), "mkfs.fat"); 150 | assert_eq!(fs.uuid_arg(), vec!["-i", "1234"]); 151 | assert_eq!(fs.label_arg(), vec!["-n", "BOOT"]); 152 | } 153 | 154 | #[test] 155 | fn test_ext4_args() { 156 | let uuid = Uuid::new_v4(); 157 | let fs = Filesystem::Standard { 158 | filesystem_type: types::StandardFilesystemType::Ext4, 159 | label: Some("root".to_string()), 160 | uuid: Some(uuid.to_string()), 161 | }; 162 | 163 | assert_eq!(fs.mkfs_command(), "mkfs.ext4"); 164 | assert_eq!(fs.uuid_arg(), vec!["-U".to_string(), uuid.to_string()]); 165 | assert_eq!(fs.label_arg(), vec!["-L", "root"]); 166 | } 167 | 168 | #[test] 169 | fn test_xfs_args() { 170 | let uuid = Uuid::new_v4(); 171 | let fs = Filesystem::Standard { 172 | filesystem_type: types::StandardFilesystemType::Xfs, 173 | label: Some("data".to_string()), 174 | uuid: Some(uuid.to_string()), 175 | }; 176 | 177 | assert_eq!(fs.mkfs_command(), "mkfs.xfs"); 178 | assert_eq!(fs.uuid_arg(), vec!["-m".to_string(), format!("uuid={uuid}")]); 179 | assert_eq!(fs.label_arg(), vec!["-L", "data"]); 180 | } 181 | } 182 | -------------------------------------------------------------------------------- /crates/partitioning/src/lib.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: Copyright © 2025 Serpent OS Developers 2 | // 3 | // SPDX-License-Identifier: MPL-2.0 4 | 5 | pub mod blkpg; 6 | pub mod loopback; 7 | pub mod sparsefile; 8 | 9 | mod attributes; 10 | pub use attributes::*; 11 | 12 | mod formatter; 13 | pub use formatter::*; 14 | 15 | pub use gpt; 16 | 17 | pub mod planner; 18 | pub mod strategy; 19 | 20 | pub mod writer; 21 | -------------------------------------------------------------------------------- /crates/partitioning/src/loopback.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: Copyright © 2025 Serpent OS Developers 2 | // 3 | // SPDX-License-Identifier: MPL-2.0 4 | 5 | use std::{ 6 | fs, io, 7 | os::fd::{AsRawFd, OwnedFd}, 8 | }; 9 | 10 | use linux_raw_sys::loop_device::{LOOP_CLR_FD, LOOP_CTL_GET_FREE, LOOP_SET_FD, LOOP_SET_STATUS64}; 11 | use log::{debug, error, info}; 12 | use nix::libc; 13 | 14 | /// Represents a loop device that can be used to mount files as block devices 15 | pub struct LoopDevice { 16 | /// File descriptor for the loop device 17 | fd: OwnedFd, 18 | /// Path to the loop device (e.g. /dev/loop0) 19 | pub path: String, 20 | } 21 | 22 | impl LoopDevice { 23 | /// Creates a new loop device by obtaining the next available device number 24 | /// from /dev/loop-control and opening the corresponding device file. 25 | /// 26 | /// # Returns 27 | /// `io::Result` containing the new loop device on success 28 | pub fn create() -> io::Result { 29 | use std::fs::OpenOptions; 30 | 31 | debug!("Opening loop control device"); 32 | let ctrl = OpenOptions::new().read(true).write(true).open("/dev/loop-control")?; 33 | 34 | // Get next free loop device number 35 | let devno = unsafe { libc::ioctl(ctrl.as_raw_fd(), LOOP_CTL_GET_FREE as _) }; 36 | if devno < 0 { 37 | error!("Failed to acquire free loop device number"); 38 | return Err(io::Error::last_os_error()); 39 | } 40 | 41 | let path = format!("/dev/loop{devno}"); 42 | debug!("Creating new loop device at {path}"); 43 | let fd = OpenOptions::new().read(true).write(true).open(&path)?.into(); 44 | 45 | info!("Successfully initialized loop device {path}"); 46 | Ok(LoopDevice { fd, path }) 47 | } 48 | 49 | /// Attaches a backing file to this loop device, allowing the file to be 50 | /// accessed as a block device. 51 | /// 52 | /// # Arguments 53 | /// * `backing_file` - Path to the file to attach 54 | /// 55 | /// # Returns 56 | /// `io::Result<()>` indicating success or failure 57 | pub fn attach(&self, backing_file: &str) -> io::Result<()> { 58 | debug!("Attempting to attach backing file {} to {}", backing_file, self.path); 59 | let f = fs::OpenOptions::new().read(true).write(true).open(backing_file)?; 60 | 61 | let file_fd = f.as_raw_fd(); 62 | let our_fd = self.fd.as_raw_fd(); 63 | let res = unsafe { libc::ioctl(our_fd, LOOP_SET_FD as _, file_fd) }; 64 | 65 | if res < 0 { 66 | error!("Failed to attach backing file {backing_file} - OS error"); 67 | return Err(io::Error::last_os_error()); 68 | } 69 | 70 | // Force loop device to immediately update by setting empty status 71 | let info: linux_raw_sys::loop_device::loop_info64 = unsafe { std::mem::zeroed() }; 72 | let res = unsafe { libc::ioctl(our_fd, LOOP_SET_STATUS64 as _, &info) }; 73 | if res < 0 { 74 | error!("Failed to update loop device status - device may be in inconsistent state"); 75 | return Err(io::Error::last_os_error()); 76 | } 77 | 78 | info!("Successfully attached backing file {backing_file} to loop device"); 79 | Ok(()) 80 | } 81 | 82 | /// Detaches the current backing file from this loop device. 83 | /// 84 | /// # Returns 85 | /// `io::Result<()>` indicating success or failure 86 | pub fn detach(&self) -> io::Result<()> { 87 | debug!("Initiating detachment of backing file from {}", self.path); 88 | let res = unsafe { libc::ioctl(self.fd.as_raw_fd(), LOOP_CLR_FD as _, 0) }; 89 | if res < 0 { 90 | error!("Failed to detach backing file from {} - OS error", self.path); 91 | return Err(io::Error::last_os_error()); 92 | } 93 | 94 | info!("Successfully detached backing file from loop device {}", self.path); 95 | Ok(()) 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /crates/partitioning/src/sparsefile.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: Copyright © 2025 Serpent OS Developers 2 | // 3 | // SPDX-License-Identifier: MPL-2.0 4 | 5 | use log::{debug, info}; 6 | use std::{fs, io, path::Path}; 7 | 8 | /// Creates a sparse file at the specified path with the given size. 9 | /// 10 | /// # Arguments 11 | /// * `path` - Path where the sparse file should be created 12 | /// * `size` - Size in bytes for the sparse file 13 | /// 14 | /// # Returns 15 | /// `io::Result<()>` indicating success or failure 16 | pub fn create

(path: P, size: u64) -> io::Result<()> 17 | where 18 | P: AsRef, 19 | { 20 | debug!("Creating sparse file at {:?}", path.as_ref()); 21 | 22 | let file = fs::OpenOptions::new() 23 | .write(true) 24 | .create(true) 25 | .truncate(true) 26 | .open(&path)?; 27 | 28 | debug!("Setting file size to {size} bytes"); 29 | file.set_len(size)?; 30 | 31 | info!( 32 | "Successfully created sparse file of {} bytes at {:?}", 33 | size, 34 | path.as_ref() 35 | ); 36 | Ok(()) 37 | } 38 | -------------------------------------------------------------------------------- /crates/partitioning/src/strategy.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: Copyright © 2025 Serpent OS Developers 2 | // 3 | // SPDX-License-Identifier: MPL-2.0 4 | //! High-level partition allocation strategies 5 | //! 6 | //! This module provides an abstraction layer for common disk partitioning patterns. 7 | //! Rather than manually planning individual partition changes, consumers can: 8 | //! 9 | //! 1. Choose a high-level strategy (e.g. initialize whole disk, use largest free space) 10 | //! 2. Define their partition requirements (exact sizes, minimums, ranges) 11 | //! 3. Let the strategy handle the details of planning the actual changes 12 | //! 13 | //! Example: 14 | //! ```no_run 15 | //! use partitioning::strategy::{Strategy, AllocationStrategy, PartitionRequest, SizeRequirement}; 16 | //! 17 | //! // Create strategy for fresh installation 18 | //! let mut strategy = Strategy::new(AllocationStrategy::InitializeWholeDisk); 19 | //! 20 | //! // Request needed partitions 21 | //! strategy.add_request(PartitionRequest { 22 | //! size: SizeRequirement::Exact(512 * 1024 * 1024), // 512MB EFI partition 23 | //! attributes: None, 24 | //! }); 25 | //! strategy.add_request(PartitionRequest { 26 | //! size: SizeRequirement::Remaining, // Rest for root 27 | //! attributes: None, 28 | //! }); 29 | //! ``` 30 | 31 | use crate::planner::{PlanError, Planner}; 32 | 33 | use crate::planner::Region; 34 | use crate::PartitionAttributes; 35 | 36 | /// Strategy for allocating partitions 37 | #[derive(Debug, Clone)] 38 | pub enum AllocationStrategy { 39 | /// Initialize a clean partition layout using the entire disk. 40 | /// This will remove all existing partitions and create a new layout. 41 | InitializeWholeDisk, 42 | /// Use largest available free region on existing table 43 | LargestFree, 44 | /// Use first free region that fits on existing table 45 | FirstFit, 46 | /// Use specific region on existing table 47 | SpecificRegion(Region), 48 | } 49 | 50 | /// Defines how to size a partition within its allocated region 51 | #[derive(Debug, Clone)] 52 | pub enum SizeRequirement { 53 | /// Exact size in bytes 54 | Exact(u64), 55 | /// Minimum size in bytes, using more if available 56 | AtLeast(u64), 57 | /// Between min and max bytes 58 | Range { min: u64, max: u64 }, 59 | /// Use all remaining space 60 | Remaining, 61 | } 62 | 63 | /// A partition request for the strategy to plan 64 | #[derive(Debug, Clone)] 65 | pub struct PartitionRequest { 66 | pub size: SizeRequirement, 67 | pub attributes: Option, 68 | } 69 | 70 | /// Handles planning partition layouts according to specific strategies 71 | #[derive(Debug, Clone)] 72 | pub struct Strategy { 73 | allocation: AllocationStrategy, 74 | requests: Vec, 75 | } 76 | 77 | impl Strategy { 78 | /// Create a new strategy using the specified allocation method 79 | pub fn new(allocation: AllocationStrategy) -> Self { 80 | Self { 81 | allocation, 82 | requests: Vec::new(), 83 | } 84 | } 85 | 86 | /// Add a partition request to this strategy 87 | pub fn add_request(&mut self, request: PartitionRequest) { 88 | self.requests.push(request); 89 | } 90 | 91 | /// Find available free regions on the disk 92 | fn find_free_regions(&self, planner: &Planner) -> Vec { 93 | let mut regions = Vec::new(); 94 | let (mut current, disk_size) = planner.offsets(); 95 | 96 | // Sort existing partitions by start position 97 | let mut layout = planner.current_layout(); 98 | layout.sort_by_key(|r| r.start); 99 | 100 | // Find gaps between partitions 101 | for region in layout { 102 | if region.start > current { 103 | regions.push(Region::new(current, region.start)); 104 | } 105 | current = region.end; 106 | } 107 | 108 | // Add final region if there's space after last partition 109 | if current < disk_size { 110 | regions.push(Region::new(current, disk_size)); 111 | } 112 | 113 | regions 114 | } 115 | 116 | /// Get a human readable description of this strategy 117 | pub fn describe(&self) -> String { 118 | use disks::format_size; 119 | 120 | let mut desc = match &self.allocation { 121 | AllocationStrategy::InitializeWholeDisk => "Initialize new partition layout on entire disk".to_string(), 122 | AllocationStrategy::LargestFree => "Use largest free region".to_string(), 123 | AllocationStrategy::FirstFit => "Use first available region".to_string(), 124 | AllocationStrategy::SpecificRegion(r) => format!("Use specific region: {}", r.describe(r.end - r.start)), 125 | }; 126 | 127 | if !self.requests.is_empty() { 128 | desc.push_str("\nRequested partitions:\n"); 129 | for (i, req) in self.requests.iter().enumerate() { 130 | let size_desc = match &req.size { 131 | SizeRequirement::Exact(size) => format!("exactly {}", format_size(*size)), 132 | SizeRequirement::AtLeast(min) => format!("at least {}", format_size(*min)), 133 | SizeRequirement::Range { min, max } => { 134 | format!("between {} and {}", format_size(*min), format_size(*max)) 135 | } 136 | SizeRequirement::Remaining => "remaining space".to_string(), 137 | }; 138 | desc.push_str(&format!(" {}: {}\n", i + 1, size_desc)); 139 | } 140 | } 141 | desc 142 | } 143 | 144 | /// Apply this strategy to a planner 145 | /// This will plan the necessary partition changes to fulfill the requirements 146 | /// Returns an error if the strategy cannot be applied due to insufficient space 147 | /// or other constraints 148 | pub fn apply(&self, planner: &mut Planner) -> Result<(), PlanError> { 149 | // Determine the target region for our partitions 150 | let target = match &self.allocation { 151 | AllocationStrategy::InitializeWholeDisk => { 152 | // Clear existing partitions and start fresh 153 | planner.plan_initialize_disk()?; 154 | let (start, end) = planner.offsets(); 155 | Region::new(start, end) 156 | } 157 | AllocationStrategy::LargestFree => { 158 | let free_regions = self.find_free_regions(planner); 159 | free_regions 160 | .iter() 161 | .max_by_key(|r| r.size()) 162 | .cloned() 163 | .ok_or(PlanError::NoFreeRegions)? 164 | } 165 | AllocationStrategy::FirstFit => { 166 | let free_regions = self.find_free_regions(planner); 167 | free_regions.first().cloned().ok_or(PlanError::NoFreeRegions)? 168 | } 169 | AllocationStrategy::SpecificRegion(region) => region.clone(), 170 | }; 171 | 172 | let mut current = target.start; 173 | let mut remaining = target.end - target.start; 174 | 175 | let mut flexible_requests = Vec::new(); 176 | let mut total_fixed = 0u64; 177 | let mut min_flexible = 0u64; 178 | 179 | // First pass: Calculate space requirements 180 | for (current_idx, request) in self.requests.iter().enumerate() { 181 | match &request.size { 182 | SizeRequirement::Exact(size) => total_fixed += size, 183 | SizeRequirement::AtLeast(min) => { 184 | min_flexible += min; 185 | flexible_requests.push((current_idx, *min, None)); 186 | } 187 | SizeRequirement::Range { min, max } => { 188 | min_flexible += min; 189 | flexible_requests.push((current_idx, *min, Some(*max))); 190 | } 191 | SizeRequirement::Remaining => { 192 | flexible_requests.push((current_idx, 0, None)); 193 | } 194 | } 195 | } 196 | 197 | // Verify we have enough space for minimum requirements 198 | if total_fixed + min_flexible > remaining { 199 | return Err(PlanError::RegionOutOfBounds { 200 | start: current, 201 | end: current + total_fixed + min_flexible, 202 | }); 203 | } 204 | 205 | // First pass: allocate exact size partitions 206 | for request in &self.requests { 207 | if let SizeRequirement::Exact(size) = request.size { 208 | planner.plan_add_partition_with_attributes(current, current + size, request.attributes.clone())?; 209 | current += size; 210 | remaining -= size; 211 | } 212 | } 213 | 214 | // Second pass: allocate flexible partitions 215 | let mut remaining_flexible = flexible_requests.len(); 216 | for (idx, min, max_opt) in &flexible_requests { 217 | remaining_flexible -= 1; 218 | 219 | // First verify we have enough space for minimum requirement 220 | if *min > remaining { 221 | // Clean up any changes we made since we can't complete all requests 222 | while planner.has_changes() { 223 | planner.undo(); 224 | } 225 | return Err(PlanError::RegionOutOfBounds { 226 | start: current, 227 | end: current + min, 228 | }); 229 | } 230 | 231 | let size = if remaining_flexible == 0 { 232 | // Last flexible partition gets all remaining space 233 | let size = remaining; 234 | if let Some(max) = max_opt { 235 | size.min(*max).max(*min) 236 | } else { 237 | size.max(*min) 238 | } 239 | } else { 240 | // Other flexible partitions get fair share plus minimum 241 | let share = remaining / (remaining_flexible + 1) as u64; 242 | let size = min + share; 243 | if let Some(max) = max_opt { 244 | size.min(*max) 245 | } else { 246 | size 247 | } 248 | }; 249 | 250 | match planner.plan_add_partition_with_attributes( 251 | current, 252 | current + size, 253 | self.requests.get(*idx).and_then(|r| r.attributes.clone()), 254 | ) { 255 | Ok(_) => { 256 | current += size; 257 | remaining -= size; 258 | } 259 | Err(e) => { 260 | // Clean up any changes we made since we can't complete all requests 261 | while planner.has_changes() { 262 | planner.undo(); 263 | } 264 | return Err(e); 265 | } 266 | } 267 | } 268 | 269 | Ok(()) 270 | } 271 | } 272 | 273 | #[cfg(test)] 274 | mod tests { 275 | use super::*; 276 | use crate::planner::Planner; 277 | use disks::{mock::MockDisk, BlockDevice}; 278 | use test_log::test; 279 | 280 | const MB: u64 = 1024 * 1024; 281 | const GB: u64 = 1024 * MB; 282 | 283 | // Common partition sizes for Linux installations 284 | const EFI_SIZE: u64 = 512 * MB; // Standard EFI partition size 285 | const BOOT_SIZE: u64 = GB; // /boot partition size 286 | const SWAP_MIN: u64 = 4 * GB; // Minimum swap size 287 | const SWAP_MAX: u64 = 8 * GB; // Maximum swap size 288 | const ROOT_MIN: u64 = 20 * GB; // Minimum root partition size 289 | const ROOT_MAX: u64 = 100 * GB; // Maximum root partition size 290 | 291 | /// Creates a root partition request that uses remaining space with a minimum size 292 | fn root_partition() -> PartitionRequest { 293 | PartitionRequest { 294 | size: SizeRequirement::AtLeast(ROOT_MIN), 295 | attributes: None, 296 | } 297 | } 298 | 299 | /// Creates a root partition request capped at 100GB, suitable for layouts with home partition 300 | fn capped_root_partition() -> PartitionRequest { 301 | PartitionRequest { 302 | size: SizeRequirement::Range { 303 | min: ROOT_MIN, 304 | max: ROOT_MAX, 305 | }, 306 | attributes: None, 307 | } 308 | } 309 | 310 | /// Creates a standard EFI system partition request 311 | fn efi_partition() -> PartitionRequest { 312 | PartitionRequest { 313 | size: SizeRequirement::Exact(EFI_SIZE), 314 | attributes: None, 315 | } 316 | } 317 | 318 | /// Creates a /boot partition request 319 | fn boot_partition() -> PartitionRequest { 320 | PartitionRequest { 321 | size: SizeRequirement::Exact(BOOT_SIZE), 322 | attributes: None, 323 | } 324 | } 325 | 326 | /// Creates a swap partition request that scales with system RAM 327 | fn swap_partition() -> PartitionRequest { 328 | PartitionRequest { 329 | size: SizeRequirement::Range { 330 | min: SWAP_MIN, 331 | max: SWAP_MAX, 332 | }, 333 | attributes: None, 334 | } 335 | } 336 | 337 | /// Creates a home partition request that uses all remaining space 338 | fn home_partition() -> PartitionRequest { 339 | PartitionRequest { 340 | size: SizeRequirement::Remaining, 341 | attributes: None, 342 | } 343 | } 344 | fn create_test_disk() -> MockDisk { 345 | MockDisk::new(500 * GB) 346 | } 347 | 348 | #[test] 349 | fn test_uefi_clean_install() { 350 | // Test case: Clean UEFI installation with separate /home 351 | let disk = create_test_disk(); 352 | let mut planner = Planner::new(&BlockDevice::mock_device(disk)); 353 | let mut strategy = Strategy::new(AllocationStrategy::InitializeWholeDisk); 354 | 355 | // Standard UEFI layout with separate /home 356 | strategy.add_request(efi_partition()); 357 | strategy.add_request(boot_partition()); 358 | strategy.add_request(swap_partition()); 359 | strategy.add_request(capped_root_partition()); 360 | strategy.add_request(home_partition()); 361 | 362 | eprintln!("\nUEFI Clean Install Strategy:\n{}", strategy.describe()); 363 | assert!(strategy.apply(&mut planner).is_ok()); 364 | eprintln!("{}", planner.describe_changes()); 365 | 366 | let layout = planner.current_layout(); 367 | assert_eq!(layout.len(), 5); 368 | // Verify partition order and basic size requirements 369 | assert!(layout[0].size() >= EFI_SIZE); 370 | assert!(layout[1].size() >= BOOT_SIZE); 371 | assert!(layout[2].size() >= SWAP_MIN); 372 | assert!(layout[3].size() >= ROOT_MIN); 373 | } 374 | 375 | #[test] 376 | fn test_dual_boot_install() { 377 | // Test case: Installation alongside existing Windows 378 | let mut disk = create_test_disk(); 379 | 380 | // Simulate existing Windows layout: 381 | // 100MB EFI + 16MB MSR + 200GB Windows + Free Space 382 | disk.add_partition(0, 100 * MB); // EFI 383 | disk.add_partition(100 * MB, 116 * MB); // MSR 384 | disk.add_partition(116 * MB, 200 * GB); // Windows 385 | 386 | let mut planner = Planner::new(&BlockDevice::mock_device(disk)); 387 | let mut strategy = Strategy::new(AllocationStrategy::LargestFree); 388 | 389 | // Standard Linux layout using remaining space 390 | strategy.add_request(swap_partition()); 391 | strategy.add_request(root_partition()); 392 | 393 | eprintln!("\nDual Boot Strategy:\n{}", strategy.describe()); 394 | assert!(strategy.apply(&mut planner).is_ok()); 395 | eprintln!("{}", planner.describe_changes()); 396 | 397 | let layout = planner.current_layout(); 398 | assert_eq!(layout.len(), 5); // 3 Windows + 2 Linux partitions 399 | } 400 | 401 | #[test] 402 | fn test_minimal_server_install() { 403 | // Test case: Minimal server installation with single root partition 404 | let disk = create_test_disk(); 405 | let mut planner = Planner::new(&BlockDevice::mock_device(disk)); 406 | let mut strategy = Strategy::new(AllocationStrategy::InitializeWholeDisk); 407 | 408 | // Simple layout - just boot and root 409 | strategy.add_request(boot_partition()); 410 | strategy.add_request(PartitionRequest { 411 | size: SizeRequirement::Remaining, 412 | attributes: None, 413 | }); 414 | 415 | eprintln!("\nMinimal Server Strategy:\n{}", strategy.describe()); 416 | assert!(strategy.apply(&mut planner).is_ok()); 417 | eprintln!("{}", planner.describe_changes()); 418 | 419 | let layout = planner.current_layout(); 420 | assert_eq!(layout.len(), 2); 421 | } 422 | 423 | #[test] 424 | fn test_insufficient_space() { 425 | let disk = MockDisk::new(10 * GB); // Intentionally small disk 426 | let mut planner = Planner::new(&BlockDevice::mock_device(disk)); 427 | let mut strategy = Strategy::new(AllocationStrategy::InitializeWholeDisk); 428 | 429 | // Try to allocate more than available 430 | strategy.add_request(PartitionRequest { 431 | size: SizeRequirement::Exact(20 * GB), 432 | attributes: None, 433 | }); 434 | 435 | assert!(strategy.apply(&mut planner).is_err()); 436 | } 437 | 438 | #[test] 439 | fn test_flexible_partition_overflow() { 440 | let disk = MockDisk::new(10 * GB); 441 | let mut planner = Planner::new(&BlockDevice::mock_device(disk)); 442 | let mut strategy = Strategy::new(AllocationStrategy::InitializeWholeDisk); 443 | 444 | // Request more than available in flexible partitions 445 | strategy.add_request(PartitionRequest { 446 | size: SizeRequirement::AtLeast(6 * GB), 447 | attributes: None, 448 | }); 449 | strategy.add_request(PartitionRequest { 450 | size: SizeRequirement::AtLeast(6 * GB), 451 | attributes: None, 452 | }); 453 | 454 | // Should fail because total minimum (12GB) exceeds disk size (10GB) 455 | let result = strategy.apply(&mut planner); 456 | assert!(matches!(result, Err(PlanError::RegionOutOfBounds { .. }))); 457 | assert!(!planner.has_changes()); 458 | } 459 | 460 | #[test] 461 | fn test_partial_partition_creation() { 462 | let disk = MockDisk::new(8 * GB); 463 | let mut planner = Planner::new(&BlockDevice::mock_device(disk)); 464 | let mut strategy = Strategy::new(AllocationStrategy::InitializeWholeDisk); 465 | 466 | // Request sequence where first two would fit but third won't 467 | strategy.add_request(PartitionRequest { 468 | size: SizeRequirement::Range { min: GB, max: 2 * GB }, 469 | attributes: None, 470 | }); 471 | strategy.add_request(PartitionRequest { 472 | size: SizeRequirement::Range { 473 | min: 2 * GB, 474 | max: 4 * GB, 475 | }, 476 | attributes: None, 477 | }); 478 | strategy.add_request(PartitionRequest { 479 | size: SizeRequirement::Range { 480 | min: 25 * GB, 481 | max: 120 * GB, 482 | }, 483 | attributes: None, 484 | }); 485 | 486 | // Should fail and undo partial changes 487 | let result = strategy.apply(&mut planner); 488 | assert!(matches!(result, Err(PlanError::RegionOutOfBounds { .. }))); 489 | assert!(!planner.has_changes(), "Partial changes should be undone"); 490 | } 491 | } 492 | -------------------------------------------------------------------------------- /crates/partitioning/src/writer.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: Copyright © 2025 Serpent OS Developers 2 | // SPDX-FileCopyrightText: Copyright © 2025 AerynOS Developers 3 | // 4 | // SPDX-License-Identifier: MPL-2.0 5 | 6 | use std::{ 7 | fs, 8 | io::{self, Seek, Write}, 9 | }; 10 | 11 | use disks::BlockDevice; 12 | use gpt::{mbr, partition_types, GptConfig}; 13 | use thiserror::Error; 14 | 15 | use crate::{ 16 | blkpg, 17 | planner::{Change, Planner}, 18 | GptAttributes, 19 | }; 20 | const SECTOR_SIZE: u64 = 512; 21 | 22 | /// Errors that can occur when writing changes to disk 23 | #[derive(Debug, Error)] 24 | pub enum WriteError { 25 | // A blkpg error 26 | #[error("error syncing partitions: {0}")] 27 | Blkpg(#[from] blkpg::Error), 28 | 29 | /// A partition ID was used multiple times 30 | #[error("Duplicate partition ID: {0}")] 31 | DuplicatePartitionId(u32), 32 | 33 | /// Error from GPT library 34 | #[error("GPT error: {0}")] 35 | Gpt(#[from] gpt::GptError), 36 | 37 | /// Error from MBR handling 38 | #[error("GPT error: {0}")] 39 | Mbr(#[from] gpt::mbr::MBRError), 40 | 41 | /// Underlying I/O error 42 | #[error("I/O error: {0}")] 43 | IoError(#[from] std::io::Error), 44 | } 45 | 46 | /// A writer that applies the layouts from the Planner to the disk. 47 | pub struct DiskWriter<'a> { 48 | /// The block device to write to 49 | pub device: &'a BlockDevice, 50 | /// The planner containing the changes to apply 51 | pub planner: &'a Planner, 52 | } 53 | 54 | /// Zero out a specific region of the disk 55 | fn zero_region(writer: &mut W, offset: u64, size: u64) -> io::Result<()> { 56 | let zeros = [0u8; 65_536]; 57 | writer.seek(std::io::SeekFrom::Start(offset))?; 58 | let chunks = (size / 65_536) as usize; 59 | for _ in 0..chunks { 60 | writer.write_all(&zeros)?; 61 | } 62 | // Handle any remaining bytes 63 | let remainder = size % 65_536; 64 | if remainder > 0 { 65 | writer.write_all(&zeros[..remainder as usize])?; 66 | } 67 | writer.flush()?; 68 | Ok(()) 69 | } 70 | 71 | /// Zero out disk headers by wiping first 2MiB of the disk 72 | fn zero_disk_headers(writer: &mut W) -> io::Result<()> { 73 | // Clear first 2MiB to wipe all common boot structures 74 | zero_region(writer, 0, 2 * 1024 * 1024) 75 | } 76 | 77 | /// Zero out up to 2MiB of a partition by writing 32 * 64KiB blocks 78 | /// Zero out up to 2MiB of a region by writing 32 * 64KiB blocks 79 | fn zero_partition_prefix(writer: &mut W, offset: u64, size: u64) -> io::Result<()> { 80 | let to_zero = std::cmp::min(size, 2 * 1024 * 1024); // 2MiB max 81 | zero_region(writer, offset, to_zero) 82 | } 83 | 84 | impl<'a> DiskWriter<'a> { 85 | /// Create a new DiskWriter. 86 | pub fn new(device: &'a BlockDevice, planner: &'a Planner) -> Self { 87 | Self { device, planner } 88 | } 89 | 90 | /// Simulate changes without writing to disk 91 | pub fn simulate(&self) -> Result<(), WriteError> { 92 | let mut device = fs::OpenOptions::new() 93 | .read(true) 94 | .write(false) 95 | .open(self.device.device())?; 96 | self.validate_changes()?; 97 | self.apply_changes(&mut device, false)?; 98 | Ok(()) 99 | } 100 | 101 | /// Actually write changes to disk 102 | pub fn write(&self) -> Result<(), WriteError> { 103 | let mut device = fs::OpenOptions::new() 104 | .read(true) 105 | .write(true) 106 | .open(self.device.device())?; 107 | 108 | self.validate_changes()?; 109 | self.apply_changes(&mut device, true)?; 110 | device.flush()?; 111 | Ok(()) 112 | } 113 | 114 | /// Validate all planned changes before applying them by checking: 115 | /// - Device size matches the planned size 116 | /// - No duplicate partition IDs exist 117 | fn validate_changes(&self) -> Result<(), WriteError> { 118 | // Verify partition IDs don't conflict 119 | let mut used_ids = std::collections::HashSet::new(); 120 | for change in self.planner.changes() { 121 | match change { 122 | Change::AddPartition { partition_id, .. } => { 123 | if !used_ids.insert(*partition_id) { 124 | return Err(WriteError::DuplicatePartitionId(*partition_id)); 125 | } 126 | } 127 | Change::DeletePartition { partition_id, .. } => { 128 | used_ids.remove(partition_id); 129 | } 130 | } 131 | } 132 | 133 | Ok(()) 134 | } 135 | 136 | /// Apply the changes to disk by: 137 | /// - Creating or opening the GPT table 138 | /// - Applying each change in sequence 139 | fn apply_changes(&self, device: &mut fs::File, writable: bool) -> Result<(), WriteError> { 140 | // Remove known partitions pre wipe 141 | if writable { 142 | blkpg::remove_kernel_partitions(self.device.device())?; 143 | } 144 | 145 | let mut zero_regions = vec![]; 146 | 147 | let mut gpt_table = if self.planner.wipe_disk() { 148 | if writable { 149 | // Zero out headers including potential ISO structures 150 | zero_disk_headers(device)?; 151 | 152 | // Convert total bytes to LBA sectors, subtract 1 as per GPT spec 153 | let total_lba = self.device.size() / SECTOR_SIZE; 154 | let mbr = mbr::ProtectiveMBR::with_lb_size( 155 | u32::try_from(total_lba.saturating_sub(1)).unwrap_or(0xFF_FF_FF_FF), 156 | ); 157 | eprintln!("size is {}", self.device.size()); 158 | mbr.overwrite_lba0(device)?; 159 | } 160 | 161 | let mut c = GptConfig::default() 162 | .writable(writable) 163 | .logical_block_size(gpt::disk::LogicalBlockSize::Lb512) 164 | .create_from_device(device, None)?; 165 | 166 | if writable { 167 | c.write_inplace()?; 168 | } 169 | c 170 | } else { 171 | GptConfig::default().writable(writable).open_from_device(device)? 172 | }; 173 | 174 | let layout = self.planner.current_layout(); 175 | let changes = self.planner.changes(); 176 | 177 | eprintln!("Changes: {changes:?}"); 178 | 179 | for change in changes { 180 | match change { 181 | Change::DeletePartition { 182 | partition_id, 183 | original_index, 184 | } => { 185 | if let Some(id) = gpt_table.remove_partition(*partition_id) { 186 | println!("Deleted partition {partition_id} (index {original_index}): {id:?}"); 187 | } 188 | } 189 | Change::AddPartition { 190 | start, 191 | end, 192 | partition_id, 193 | attributes, 194 | } => { 195 | // Convert byte offsets to LBA sectors 196 | let start_lba = *start / SECTOR_SIZE; 197 | let size_bytes = *end - *start; 198 | let size_lba = size_bytes / SECTOR_SIZE; 199 | let (part_type, part_name) = match attributes.as_ref().and_then(|a| a.table.as_gpt()) { 200 | Some(GptAttributes { type_guid, name, .. }) => { 201 | (type_guid.clone(), name.clone().unwrap_or_default()) 202 | } 203 | None => (partition_types::BASIC, "".to_string()), 204 | }; 205 | 206 | eprintln!( 207 | "Converting partition: bytes {}..{} to LBA {}..{}", 208 | start, 209 | end, 210 | start_lba, 211 | start_lba + size_lba 212 | ); 213 | let id = 214 | gpt_table.add_partition_at(&part_name, *partition_id, start_lba, size_lba, part_type, 0)?; 215 | println!("Added partition {partition_id}: {id:?}"); 216 | // Store start and size for zeroing 217 | if writable { 218 | zero_regions.push((*start, *end)); 219 | } 220 | } 221 | } 222 | } 223 | 224 | eprintln!("### GPT is now: {gpt_table:?}"); 225 | 226 | for region in layout.iter() { 227 | eprintln!( 228 | "Region at: {:?}", 229 | region.partition_id.map(|i| self.device.partition_path(i as usize)) 230 | ); 231 | } 232 | 233 | // Consume and sync the GPT table 234 | if writable { 235 | let original = gpt_table.write()?; 236 | original.sync_all()?; 237 | 238 | for (start, end) in zero_regions { 239 | zero_partition_prefix(original, start, end - start)?; 240 | } 241 | 242 | blkpg::create_kernel_partitions(self.device.device())?; 243 | } 244 | 245 | Ok(()) 246 | } 247 | } 248 | -------------------------------------------------------------------------------- /crates/provisioning/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "provisioning" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | [dev-dependencies] 7 | miette = { workspace = true, features = ["fancy"] } 8 | 9 | [dependencies] 10 | disks = { path = "../disks" } 11 | partitioning = { path = "../partitioning" } 12 | types = { path = "../types", features = ["kdl"] } 13 | kdl = { workspace = true, features = ["span"] } 14 | miette = { workspace = true } 15 | itertools = { workspace = true } 16 | phf = { workspace = true, features = ["macros"] } 17 | test-log.workspace = true 18 | thiserror.workspace = true 19 | log.workspace = true 20 | uuid.workspace = true 21 | -------------------------------------------------------------------------------- /crates/provisioning/src/commands.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: Copyright © 2025 Serpent OS Developers 2 | // SPDX-FileCopyrightText: Copyright © 2025 AerynOS Developers 3 | // 4 | // SPDX-License-Identifier: MPL-2.0 5 | 6 | use crate::Context; 7 | 8 | mod create_partition; 9 | mod create_partition_table; 10 | mod find_disk; 11 | 12 | /// A command 13 | #[derive(Debug)] 14 | pub enum Command { 15 | CreatePartition(Box), 16 | CreatePartitionTable(Box), 17 | FindDisk(Box), 18 | } 19 | 20 | /// Command execution function 21 | type CommandExec = for<'a> fn(Context<'a>) -> Result; 22 | 23 | /// Map of command names to functions 24 | static COMMANDS: phf::Map<&'static str, CommandExec> = phf::phf_map! { 25 | "find-disk" => find_disk::parse, 26 | "create-partition" => create_partition::parse, 27 | "create-partition-table" => create_partition_table::parse, 28 | }; 29 | 30 | /// Parse a command from a node if possible 31 | pub(crate) fn parse_command(context: Context<'_>) -> Result { 32 | let name = context.node.name().value(); 33 | let func = COMMANDS.get(name).ok_or_else(|| crate::UnsupportedNode { 34 | at: context.node.span(), 35 | name: name.into(), 36 | })?; 37 | 38 | func(context) 39 | } 40 | -------------------------------------------------------------------------------- /crates/provisioning/src/commands/create_partition.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: Copyright © 2025 Serpent OS Developers 2 | // SPDX-FileCopyrightText: Copyright © 2025 AerynOS Developers 3 | // 4 | // SPDX-License-Identifier: MPL-2.0 5 | 6 | use partitioning::{gpt::partition_types, GptAttributes, PartitionAttributes, TableAttributes}; 7 | 8 | use crate::{ 9 | get_kdl_entry, get_kdl_property, get_property_str, Constraints, Context, Filesystem, FromKdlProperty, FromKdlType, 10 | PartitionRole, PartitionTypeGuid, PartitionTypeKDL, 11 | }; 12 | 13 | /// Command to create a partition 14 | #[derive(Debug)] 15 | pub struct Command { 16 | /// The disk ID to create the partition on 17 | pub disk: String, 18 | 19 | /// The reference ID of the partition 20 | pub id: String, 21 | 22 | /// The role, if any, of the partition 23 | pub role: Option, 24 | 25 | /// The GUID of the partition type 26 | pub partition_type: Option, 27 | 28 | /// Constraints for the partition 29 | pub constraints: Constraints, 30 | 31 | /// The filesystem to format the partition with 32 | pub filesystem: Option, 33 | } 34 | 35 | impl Command { 36 | pub fn attributes(&self) -> PartitionAttributes { 37 | PartitionAttributes { 38 | table: TableAttributes::Gpt(GptAttributes { 39 | type_guid: match &self.partition_type { 40 | Some(p) => p.as_guid(), 41 | None => partition_types::BASIC, 42 | }, 43 | name: self.partition_type.as_ref().map(|p| p.to_string()), 44 | uuid: None, 45 | }), 46 | role: self.role.clone(), 47 | filesystem: self.filesystem.clone(), 48 | } 49 | } 50 | } 51 | 52 | /// Generate a command to create a partition 53 | pub(crate) fn parse(context: Context<'_>) -> Result { 54 | let disk = get_property_str(context.node, "disk")?; 55 | let id = get_property_str(context.node, "id")?; 56 | let role = if let Ok(role) = get_kdl_property(context.node, "role") { 57 | Some(PartitionRole::from_kdl_property(role)?) 58 | } else { 59 | None 60 | }; 61 | 62 | let mut constraints = Constraints::default(); 63 | let mut partition_type = None; 64 | let mut filesystem = None; 65 | 66 | for child in context.node.iter_children() { 67 | match child.name().value() { 68 | "constraints" => constraints = Constraints::from_kdl_node(child)?, 69 | "type" => { 70 | partition_type = match PartitionTypeKDL::from_kdl_type(get_kdl_entry(child, &0)?)? { 71 | PartitionTypeKDL::GUID => Some(PartitionTypeGuid::from_kdl_node(child)?), 72 | } 73 | } 74 | "filesystem" => filesystem = Some(Filesystem::from_kdl_node(child)?), 75 | _ => { 76 | return Err(crate::UnsupportedNode { 77 | at: child.span(), 78 | name: child.name().value().into(), 79 | } 80 | .into()) 81 | } 82 | } 83 | } 84 | 85 | if matches!(constraints, Constraints::Invalid) { 86 | return Err(crate::InvalidArguments { 87 | at: context.node.span(), 88 | advice: Some("create-partition [disk=] [role=] [constraints=] [type=(GUID)] - you must provide constraints".into()), 89 | } 90 | .into()); 91 | } 92 | 93 | Ok(super::Command::CreatePartition(Box::new(Command { 94 | disk, 95 | id, 96 | role, 97 | constraints, 98 | partition_type, 99 | filesystem, 100 | }))) 101 | } 102 | -------------------------------------------------------------------------------- /crates/provisioning/src/commands/create_partition_table.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: Copyright © 2025 Serpent OS Developers 2 | // 3 | // SPDX-License-Identifier: MPL-2.0 4 | 5 | use crate::{get_kdl_property, FromKdlProperty, PartitionTableType}; 6 | use crate::{get_property_str, Context}; 7 | 8 | /// Command to create a partition table 9 | #[derive(Debug)] 10 | pub struct Command { 11 | /// The type of partition table to create 12 | pub table_type: PartitionTableType, 13 | pub disk: String, 14 | } 15 | 16 | /// Generate a command to create a partition table 17 | pub(crate) fn parse(context: Context<'_>) -> Result { 18 | let kind = get_kdl_property(context.node, "type")?; 19 | let table_type = PartitionTableType::from_kdl_property(kind)?; 20 | let disk = get_property_str(context.node, "disk")?; 21 | 22 | Ok(super::Command::CreatePartitionTable(Box::new(Command { 23 | table_type, 24 | disk, 25 | }))) 26 | } 27 | -------------------------------------------------------------------------------- /crates/provisioning/src/commands/find_disk.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: Copyright © 2025 Serpent OS Developers 2 | // 3 | // SPDX-License-Identifier: MPL-2.0 4 | 5 | use itertools::Itertools; 6 | 7 | use crate::{Constraints, Context}; 8 | 9 | #[derive(Debug)] 10 | pub struct Command { 11 | pub name: String, 12 | pub constraints: Option, 13 | } 14 | 15 | /// Generate a command to find a disk 16 | pub(crate) fn parse(context: Context<'_>) -> Result { 17 | let arguments = context 18 | .node 19 | .entries() 20 | .iter() 21 | .filter(|e| e.is_empty() || e.name().is_none()) 22 | .collect_vec(); 23 | 24 | let name = match arguments.len() { 25 | 0 => { 26 | return Err(crate::InvalidArguments { 27 | at: context.node.span(), 28 | advice: Some("find-disk - you must provide a name to store the object".into()), 29 | } 30 | .into()) 31 | } 32 | 1 => arguments[0].value().as_string().ok_or(crate::InvalidType { 33 | at: arguments[0].span(), 34 | expected_type: crate::KdlType::String, 35 | })?, 36 | _ => { 37 | return Err(crate::InvalidArguments { 38 | at: context.node.span(), 39 | advice: Some("find-disk - only one positional argument supported".into()), 40 | } 41 | .into()) 42 | } 43 | }; 44 | 45 | let constraints = 46 | if let Some(constraints) = context.node.iter_children().find(|n| n.name().value() == "constraints") { 47 | Some(Constraints::from_kdl_node(constraints)?) 48 | } else { 49 | None 50 | }; 51 | 52 | Ok(super::Command::FindDisk(Box::new(Command { 53 | name: name.to_owned(), 54 | constraints, 55 | }))) 56 | } 57 | -------------------------------------------------------------------------------- /crates/provisioning/src/lib.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: Copyright © 2025 Serpent OS Developers 2 | // 3 | // SPDX-License-Identifier: MPL-2.0 4 | 5 | use std::{fs, path::Path, sync::Arc}; 6 | 7 | use itertools::{Either, Itertools}; 8 | use kdl::{KdlDocument, KdlNode}; 9 | use miette::{Diagnostic, NamedSource, Severity}; 10 | 11 | mod provisioner; 12 | pub use provisioner::*; 13 | 14 | mod commands; 15 | use commands::*; 16 | 17 | pub use types::*; 18 | 19 | /// Command evaluation context 20 | pub struct Context<'a> { 21 | /// The node being parsed 22 | pub(crate) node: &'a KdlNode, 23 | } 24 | 25 | /// A strategy definition 26 | #[derive(Debug)] 27 | pub struct StrategyDefinition { 28 | /// The name of the strategy 29 | pub name: String, 30 | 31 | /// A brief summary of the strategy 32 | pub summary: String, 33 | 34 | /// The strategy that this strategy inherits from 35 | pub inherits: Option, 36 | 37 | /// The commands to execute 38 | pub commands: Vec, 39 | } 40 | 41 | /// A parser for provisioning strategies 42 | #[derive(Debug)] 43 | pub struct Parser { 44 | pub strategies: Vec, 45 | } 46 | 47 | impl Parser { 48 | /// Create a new parser from a file path 49 | pub fn new_for_path

(file: P) -> Result 50 | where 51 | P: AsRef, 52 | { 53 | let file = file.as_ref(); 54 | let name = file.to_string_lossy(); 55 | let txt = fs::read_to_string(file).map_err(|e| ParseError { 56 | src: NamedSource::new(&name, Arc::new("".to_string())), 57 | diagnostics: vec![e.into()], 58 | })?; 59 | Self::new(&name, &txt) 60 | } 61 | 62 | /// Create a new parser from a string 63 | pub fn new(name: &str, contents: &str) -> Result { 64 | let source = Arc::new(contents.to_string()); 65 | let ns = NamedSource::new(name, source).with_language("KDL"); 66 | let mut errors = vec![]; 67 | 68 | // Parse the document and collect any errors 69 | let d = KdlDocument::parse_v2(ns.inner()).map_err(|e| ParseError { 70 | src: ns.clone(), 71 | diagnostics: vec![e.into()], 72 | })?; 73 | 74 | let mut strategies = vec![]; 75 | 76 | for node in d.nodes() { 77 | match node.name().value() { 78 | "strategy" => match Self::parse_strategy(node) { 79 | Ok(strategy) => strategies.push(strategy), 80 | Err(e) => errors.extend(e), 81 | }, 82 | _ => { 83 | errors.push( 84 | UnsupportedNode { 85 | at: node.span(), 86 | name: node.name().to_string(), 87 | } 88 | .into(), 89 | ); 90 | } 91 | } 92 | } 93 | 94 | if !errors.is_empty() { 95 | return Err(ParseError { 96 | src: ns, 97 | diagnostics: errors, 98 | }); 99 | } 100 | 101 | Ok(Self { strategies }) 102 | } 103 | 104 | // Parse a strategy node 105 | fn parse_strategy(node: &KdlNode) -> Result> { 106 | let mut errors = vec![]; 107 | let name = match get_property_str(node, "name") { 108 | Ok(name) => name, 109 | Err(e) => { 110 | errors.push(e); 111 | Default::default() 112 | } 113 | }; 114 | let summary = match get_property_str(node, "summary") { 115 | Ok(summary) => summary, 116 | Err(e) => { 117 | errors.push(e); 118 | Default::default() 119 | } 120 | }; 121 | let inherits = if node.entry("inherits").is_some() { 122 | match get_property_str(node, "inherits") { 123 | Ok(inherits) => Some(inherits), 124 | Err(e) => { 125 | errors.push(e); 126 | None 127 | } 128 | } 129 | } else { 130 | None 131 | }; 132 | 133 | // Collect all failures in this strategy 134 | let (commands, child_errors): (Vec<_>, Vec<_>) = 135 | node.iter_children() 136 | .partition_map(|node| match parse_command(Context { node }) { 137 | Ok(cmd) => Either::Left(cmd), 138 | Err(e) => Either::Right(e), 139 | }); 140 | 141 | errors.extend(child_errors); 142 | 143 | let fatal_errors = errors 144 | .iter() 145 | .filter(|e| matches!(e.severity().unwrap_or(Severity::Error), Severity::Error)); 146 | 147 | // If we have any fatal errors, bail out 148 | // TODO: Add an error sink to allow bubbling up of warnings/diagnostics 149 | // for tooling integration 150 | if fatal_errors.clone().next().is_some() { 151 | return Err(errors); 152 | } 153 | 154 | let strategy = StrategyDefinition { 155 | name, 156 | summary, 157 | inherits, 158 | commands, 159 | }; 160 | 161 | Ok(strategy) 162 | } 163 | } 164 | 165 | #[cfg(test)] 166 | mod tests { 167 | use crate::Parser; 168 | 169 | #[test] 170 | //#[should_panic] 171 | fn test_basic() -> miette::Result<()> { 172 | let _p = Parser::new_for_path("tests/use_whole_disk.kdl")?; 173 | eprintln!("p: {_p:?}"); 174 | Ok(()) 175 | } 176 | } 177 | -------------------------------------------------------------------------------- /crates/provisioning/src/provisioner.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: Copyright © 2025 Serpent OS Developers 2 | // SPDX-FileCopyrightText: Copyright © 2025 AerynOS Developers 3 | // 4 | // SPDX-License-Identifier: MPL-2.0 5 | 6 | use std::{collections::HashMap, path::PathBuf}; 7 | 8 | use disks::BlockDevice; 9 | use log::{debug, trace, warn}; 10 | use partitioning::{ 11 | planner::{Planner, PARTITION_ALIGNMENT}, 12 | strategy::{AllocationStrategy, PartitionRequest, SizeRequirement, Strategy}, 13 | }; 14 | use types::{Filesystem, PartitionRole}; 15 | 16 | use crate::{commands::Command, Constraints, StrategyDefinition}; 17 | 18 | /// Provisioner 19 | pub struct Provisioner<'a> { 20 | /// Pool of devices 21 | devices: Vec<&'a BlockDevice>, 22 | 23 | /// Strategy configurations 24 | configs: HashMap, 25 | } 26 | 27 | /// Compiled plan 28 | pub struct Plan<'a> { 29 | pub strategy: &'a StrategyDefinition, 30 | pub device_assignments: HashMap>, 31 | 32 | // Global mount points 33 | pub role_mounts: HashMap, 34 | 35 | // Filesystems to be formatted 36 | pub filesystems: HashMap, 37 | } 38 | 39 | #[derive(Debug, Clone)] 40 | pub struct DevicePlan<'a> { 41 | pub device: &'a BlockDevice, 42 | pub planner: Planner, 43 | pub strategy: Strategy, 44 | } 45 | 46 | impl Default for Provisioner<'_> { 47 | fn default() -> Self { 48 | Self::new() 49 | } 50 | } 51 | 52 | impl<'a> Provisioner<'a> { 53 | /// Create a new provisioner 54 | pub fn new() -> Self { 55 | debug!("Creating new provisioner"); 56 | Self { 57 | devices: Vec::new(), 58 | configs: HashMap::new(), 59 | } 60 | } 61 | 62 | /// Add a strategy configuration 63 | pub fn add_strategy(&mut self, config: &'a StrategyDefinition) { 64 | debug!("Adding strategy: {}", config.name); 65 | self.configs.insert(config.name.clone(), config); 66 | } 67 | 68 | // Add a device to the provisioner pool 69 | pub fn push_device(&mut self, device: &'a BlockDevice) { 70 | debug!("Adding device to pool: {device:?}"); 71 | self.devices.push(device) 72 | } 73 | 74 | // Build an inheritance chain for a strategy 75 | fn strategy_parents<'b>(&'b self, strategy: &'b StrategyDefinition) -> Vec<&'b StrategyDefinition> { 76 | trace!("Building inheritance chain for strategy: {}", strategy.name); 77 | let mut chain = vec![]; 78 | if let Some(parent) = &strategy.inherits { 79 | if let Some(parent) = self.configs.get(parent) { 80 | chain.extend(self.strategy_parents(parent)); 81 | } 82 | } 83 | chain.push(strategy); 84 | chain 85 | } 86 | 87 | /// Attempt all strategies on the pool of devices 88 | pub fn plan(&self) -> Vec { 89 | trace!("Planning device provisioning"); 90 | let mut plans = Vec::new(); 91 | for strategy in self.configs.values() { 92 | debug!("Attempting strategy: {}", strategy.name); 93 | self.create_plans_for_strategy(strategy, &mut HashMap::new(), &mut plans); 94 | } 95 | debug!("Generated {} plans", plans.len()); 96 | plans 97 | } 98 | 99 | fn create_plans_for_strategy<'b>( 100 | &'b self, 101 | strategy: &'b StrategyDefinition, 102 | device_assignments: &mut HashMap>, 103 | plans: &mut Vec>, 104 | ) { 105 | trace!("Creating plans for strategy: {}", strategy.name); 106 | let chain = self.strategy_parents(strategy); 107 | 108 | for command in chain.iter().flat_map(|s| &s.commands) { 109 | match command { 110 | Command::FindDisk(command) => { 111 | // Skip if already assigned 112 | if device_assignments.contains_key(&command.name) { 113 | trace!("Disk {} already assigned, skipping", command.name); 114 | continue; 115 | } 116 | 117 | // Find matching devices that haven't been assigned yet 118 | let matching_devices: Vec<_> = self 119 | .devices 120 | .iter() 121 | .filter(|d| match command.constraints.as_ref() { 122 | Some(Constraints::AtLeast(n)) => d.size() >= *n, 123 | Some(Constraints::Exact(n)) => d.size() == *n, 124 | Some(Constraints::Range { min, max }) => d.size() >= *min && d.size() <= *max, 125 | _ => true, 126 | }) 127 | .filter(|d| { 128 | !device_assignments.values().any(|assigned| { 129 | std::ptr::eq(assigned.device as *const BlockDevice, **d as *const BlockDevice) 130 | }) 131 | }) 132 | .collect(); 133 | 134 | debug!("Found {} matching devices for {}", matching_devices.len(), command.name); 135 | 136 | // Branch for each matching device 137 | for device in matching_devices { 138 | trace!("Creating plan branch for device: {device:?}"); 139 | let mut new_assignments = device_assignments.clone(); 140 | new_assignments.insert( 141 | command.name.clone(), 142 | DevicePlan { 143 | device, 144 | planner: Planner::new(device) 145 | .with_start_offset(PARTITION_ALIGNMENT) 146 | .with_end_offset(device.size() - PARTITION_ALIGNMENT), 147 | strategy: Strategy::new(AllocationStrategy::LargestFree), 148 | }, 149 | ); 150 | self.create_plans_for_strategy(strategy, &mut new_assignments, plans); 151 | } 152 | 153 | return; 154 | } 155 | Command::CreatePartitionTable(command) => { 156 | if let Some(device_plan) = device_assignments.get_mut(&command.disk) { 157 | debug!("Creating partition table on disk {}", command.disk); 158 | device_plan.strategy = Strategy::new(AllocationStrategy::InitializeWholeDisk); 159 | } else { 160 | warn!("Could not find disk {} to create partition table", command.disk); 161 | } 162 | } 163 | Command::CreatePartition(command) => { 164 | if let Some(device_plan) = device_assignments.get_mut(&command.disk) { 165 | debug!("Adding partition request for disk {}", command.disk); 166 | device_plan.strategy.add_request(PartitionRequest { 167 | size: match &command.constraints { 168 | Constraints::AtLeast(n) => SizeRequirement::AtLeast(*n), 169 | Constraints::Exact(n) => SizeRequirement::Exact(*n), 170 | Constraints::Range { min, max } => SizeRequirement::Range { min: *min, max: *max }, 171 | _ => SizeRequirement::Remaining, 172 | }, 173 | attributes: Some(command.attributes()), 174 | }); 175 | } else { 176 | warn!("Could not find disk {} to create partition", command.disk); 177 | } 178 | } 179 | } 180 | } 181 | 182 | let mut role_mounts = HashMap::new(); 183 | let mut filesystems = HashMap::new(); 184 | 185 | // OK lets now apply any mutations to the device assignments 186 | for (disk_name, device_plan) in device_assignments.iter_mut() { 187 | debug!("Applying device plan for disk {disk_name}"); 188 | if let Err(e) = device_plan.strategy.apply(&mut device_plan.planner) { 189 | warn!("Failed to apply strategy for disk {disk_name}: {e:?}"); 190 | } 191 | for region in device_plan.planner.current_layout().iter() { 192 | if let Some(id) = region.partition_id { 193 | let device_path = device_plan.device.partition_path(id as usize); 194 | if let Some(attributes) = region.attributes.as_ref() { 195 | if let Some(role) = attributes.role.as_ref() { 196 | role_mounts.insert(role.clone(), device_path.clone()); 197 | } 198 | if let Some(fs) = attributes.filesystem.as_ref() { 199 | filesystems.insert(device_path, fs.clone()); 200 | } 201 | } 202 | } 203 | } 204 | } 205 | 206 | // All commands processed successfully - create a plan 207 | debug!("Creating final plan for strategy {}", strategy.name); 208 | plans.push(Plan { 209 | strategy, 210 | role_mounts, 211 | filesystems, 212 | device_assignments: device_assignments.clone(), 213 | }); 214 | } 215 | } 216 | 217 | #[cfg(test)] 218 | mod tests { 219 | use disks::mock::MockDisk; 220 | use test_log::test; 221 | 222 | use crate::Parser; 223 | 224 | use super::*; 225 | 226 | #[test] 227 | fn test_use_whole_disk() { 228 | let test_strategies = Parser::new_for_path("tests/use_whole_disk.kdl").unwrap(); 229 | let def = test_strategies.strategies; 230 | let device = BlockDevice::mock_device(MockDisk::new(150 * 1024 * 1024 * 1024)); 231 | let mut provisioner = Provisioner::new(); 232 | provisioner.push_device(&device); 233 | for def in def.iter() { 234 | provisioner.add_strategy(def); 235 | } 236 | 237 | let plans = provisioner.plan(); 238 | assert_eq!(plans.len(), 1); 239 | 240 | let plan = &plans[0]; 241 | assert_eq!(plan.device_assignments.len(), 1); 242 | 243 | for plan in plans { 244 | eprintln!("Plan: {}", plan.strategy.name); 245 | for (disk, device_plan) in plan.device_assignments.iter() { 246 | println!("strategy for {disk} is now: {}", device_plan.strategy.describe()); 247 | println!("After: {}", device_plan.planner.describe_changes()); 248 | } 249 | } 250 | } 251 | } 252 | -------------------------------------------------------------------------------- /crates/provisioning/tests/use_whole_disk.kdl: -------------------------------------------------------------------------------- 1 | strategy name="whole_disk" summary="Wipe and use an entire disk" { 2 | // Find a disk with the given constraints and then label it 3 | // We may find "any disk" 4 | // The result is stored in "root_disk" (disk=..) 5 | find-disk "root_disk" { 6 | constraints { 7 | min (GiB)30 8 | } 9 | } 10 | 11 | // Create a partition table. Defaults to GPT 12 | create-partition-table type="gpt" disk="root_disk" 13 | 14 | // Create the ESP 15 | create-partition disk="root_disk" role="boot" id="esp" { 16 | constraints { 17 | min (GiB)1 18 | max (GiB)2 19 | } 20 | type (GUID)"efi-system-partition" 21 | filesystem { 22 | type "fat32" 23 | label "ESP" 24 | } 25 | } 26 | 27 | // Create xbootldr 28 | create-partition disk="root_disk" role="extended-boot" id="xbootldr" { 29 | constraints { 30 | min (GiB)2 31 | max (GiB)4 32 | } 33 | type (GUID) "linux-extended-boot" 34 | filesystem { 35 | type "fat32" 36 | label "XBOOTLDR" 37 | } 38 | } 39 | 40 | // Create a partition for rootfs 41 | create-partition disk="root_disk" id="root" role="root" { 42 | constraints { 43 | min (GiB)25 44 | max (GiB)120 45 | } 46 | type (GUID)"linux-fs" 47 | filesystem { 48 | type "xfs" 49 | label "ROOT" 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /crates/superblock/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "superblock" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | serde = { workspace = true, features = ["derive"] } 10 | serde_json.workspace = true 11 | snafu.workspace = true 12 | uuid = { workspace = true, features = ["v8"] } 13 | zerocopy = { workspace = true, features = ["derive", "std"] } 14 | 15 | [dev-dependencies] 16 | test-log.workspace = true 17 | zstd.workspace = true 18 | -------------------------------------------------------------------------------- /crates/superblock/src/btrfs.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: Copyright © 2025 Serpent OS Developers 2 | // 3 | // SPDX-License-Identifier: MPL-2.0 4 | 5 | //! BTRFS superblock handling 6 | //! 7 | //! This module provides functionality for reading and parsing BTRFS filesystem superblocks, 8 | //! which contain critical metadata about the filesystem including UUIDs and labels. 9 | 10 | use crate::{Detection, UnicodeError}; 11 | use uuid::Uuid; 12 | use zerocopy::*; 13 | 14 | /// BTRFS superblock definition that matches the on-disk format used by the Linux kernel. 15 | /// 16 | /// The superblock contains critical filesystem metadata including: 17 | /// - Filesystem UUID and label 18 | /// - Size and usage information 19 | /// - Root tree locations 20 | /// - Compatibility flags 21 | #[derive(FromBytes, Debug)] 22 | #[repr(C)] 23 | pub struct Btrfs { 24 | /// Checksum of the superblock data 25 | pub csum: [u8; 32], 26 | /// Filesystem UUID 27 | pub fsid: [u8; 16], 28 | /// Physical byte number where this copy of the superblock is located 29 | pub bytenr: U64, 30 | /// Superblock flags 31 | pub flags: U64, 32 | /// Magic number identifying this as a BTRFS superblock 33 | pub magic: U64, 34 | /// Transaction ID of the filesystem 35 | pub generation: U64, 36 | /// Logical address of the root tree root 37 | pub root: U64, 38 | /// Logical address of the chunk tree root 39 | pub chunk_root: U64, 40 | /// Logical address of the log tree root 41 | pub log_root: U64, 42 | /// Transaction ID of the log tree 43 | pub log_root_transid: U64, 44 | /// Total size of the filesystem in bytes 45 | pub total_bytes: U64, 46 | /// Number of bytes used 47 | pub bytes_used: U64, 48 | /// Object ID of the root directory 49 | pub root_dir_objectid: U64, 50 | /// Number of devices making up the filesystem 51 | pub num_devices: U64, 52 | /// Size of a sector in bytes 53 | pub sectorsize: U32, 54 | /// Size of nodes in the filesystem trees 55 | pub nodesize: U32, 56 | /// Size of leaf nodes in the filesystem trees 57 | pub leafsize: U32, 58 | /// Stripe size for the filesystem 59 | pub stripesize: U32, 60 | /// Size of the system chunk array 61 | pub sys_chunk_array_size: U32, 62 | /// Generation of the chunk tree 63 | pub chunk_root_generation: U64, 64 | /// Compatible feature flags 65 | pub compat_flags: U64, 66 | /// Compatible read-only feature flags 67 | pub compat_ro_flags: U64, 68 | /// Incompatible feature flags 69 | pub incompat_flags: U64, 70 | /// Checksum algorithm type 71 | pub csum_type: U16, 72 | /// Level of the root tree 73 | pub root_level: u8, 74 | /// Level of the chunk tree 75 | pub chunk_root_level: u8, 76 | /// Level of the log tree 77 | pub log_root_level: u8, 78 | /// Device information 79 | pub dev_item: [u8; 98], 80 | /// Volume label 81 | pub label: [u8; 256], 82 | /// Cache generation number 83 | pub cache_generation: U64, 84 | /// UUID tree generation 85 | pub uuid_tree_generation: U64, 86 | /// Metadata UUID for the filesystem 87 | pub metadata_uuid: [u8; 16], 88 | /// Number of global root entries 89 | pub nr_global_roots: U64, 90 | /// Reserved for future use 91 | pub reserved: [u8; 32], 92 | /// System chunk array data 93 | pub sys_chunk_array: [u8; 2048], 94 | /// Backup copy of root tree info 95 | pub root_backup: [u8; 256], 96 | } 97 | 98 | /// Offset where the BTRFS superblock starts (65536 bytes) 99 | pub const START_POSITION: u64 = 0x10000; 100 | 101 | /// Magic number identifying a BTRFS superblock ("_BHRfS_M") 102 | pub const MAGIC: U64 = U64::new(0x4D5F53665248425F); 103 | 104 | impl Detection for Btrfs { 105 | type Magic = U64; 106 | 107 | const OFFSET: u64 = START_POSITION; 108 | 109 | const MAGIC_OFFSET: u64 = START_POSITION + 0x40; 110 | 111 | const SIZE: usize = std::mem::size_of::(); 112 | 113 | fn is_valid_magic(magic: &Self::Magic) -> bool { 114 | *magic == MAGIC 115 | } 116 | } 117 | 118 | impl Btrfs { 119 | /// Return the encoded UUID for this superblock as a string 120 | pub fn uuid(&self) -> Result { 121 | Ok(Uuid::from_bytes(self.fsid).hyphenated().to_string()) 122 | } 123 | 124 | /// Return the volume label as a string 125 | pub fn label(&self) -> Result { 126 | Ok(str::from_utf8(&self.label)?.trim_end_matches('\0').to_owned()) 127 | } 128 | } 129 | -------------------------------------------------------------------------------- /crates/superblock/src/ext4.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: Copyright © 2025 Serpent OS Developers 2 | // 3 | // SPDX-License-Identifier: MPL-2.0 4 | 5 | //! EXT4 superblock handling 6 | //! 7 | //! This module provides functionality for parsing and interacting with EXT4 filesystem superblocks. 8 | //! The superblock contains critical metadata about the filesystem including UUID, volume label, 9 | //! and various configuration parameters. 10 | 11 | use crate::{Detection, UnicodeError}; 12 | use uuid::Uuid; 13 | use zerocopy::*; 14 | 15 | /// EXT4 Superblock definition that mirrors the on-disk format used by the Linux kernel. 16 | /// Contains metadata and configuration for an EXT4 filesystem. 17 | #[derive(Debug, FromBytes)] 18 | #[repr(C)] 19 | pub struct Ext4 { 20 | /// Total count of inodes in filesystem 21 | pub inodes_count: U32, 22 | /// Total count of blocks (lower 32-bits) 23 | pub block_counts_lo: U32, 24 | /// Reserved block count (lower 32-bits) 25 | pub r_blocks_count_lo: U32, 26 | /// Free blocks count (lower 32-bits) 27 | pub free_blocks_count_lo: U32, 28 | /// Free inodes count 29 | pub free_inodes_count: U32, 30 | /// First data block location 31 | pub first_data_block: U32, 32 | /// Block size is 2 ^ (10 + log_block_size) 33 | pub log_block_size: U32, 34 | /// Cluster size is 2 ^ (10 + log_cluster_size) 35 | pub log_cluster_size: U32, 36 | /// Number of blocks per group 37 | pub blocks_per_group: U32, 38 | /// Number of clusters per group 39 | pub clusters_per_group: U32, 40 | /// Number of inodes per group 41 | pub inodes_per_group: U32, 42 | /// Mount time 43 | pub m_time: U32, 44 | /// Write time 45 | pub w_time: U32, 46 | /// Number of mounts since last consistency check 47 | pub mnt_count: U16, 48 | /// Maximum mounts allowed between checks 49 | pub max_mnt_count: U16, 50 | /// Magic signature (0xEF53) 51 | pub magic: U16, 52 | /// Filesystem state flags 53 | pub state: U16, 54 | /// Behavior when detecting errors 55 | pub errors: U16, 56 | /// Minor revision level 57 | pub minor_rev_level: U16, 58 | /// Time of last consistency check 59 | pub lastcheck: U32, 60 | /// Maximum time between checks 61 | pub checkinterval: U32, 62 | /// OS that created the filesystem 63 | pub creator_os: U32, 64 | /// Revision level 65 | pub rev_level: U32, 66 | /// Default uid for reserved blocks 67 | pub def_resuid: U16, 68 | /// Default gid for reserved blocks 69 | pub def_resgid: U16, 70 | /// First non-reserved inode 71 | pub first_ino: U32, 72 | /// Size of inode structure 73 | pub inode_size: U16, 74 | /// Block group number of this superblock 75 | pub block_group_nr: U16, 76 | /// Compatible feature set flags 77 | pub feature_compat: U32, 78 | /// Incompatible feature set flags 79 | pub feature_incompat: U32, 80 | /// Read-only compatible feature set flags 81 | pub feature_ro_compat: U32, 82 | /// 128-bit filesystem identifier 83 | pub uuid: [u8; 16], 84 | /// Volume name 85 | pub volume_name: [u8; 16], 86 | /// Directory where last mounted 87 | pub last_mounted: [u8; 64], 88 | /// For compression 89 | pub algorithm_usage_bitmap: U32, 90 | /// Number of blocks to preallocate 91 | pub prealloc_blocks: u8, 92 | /// Number of blocks to preallocate for directories 93 | pub prealloc_dir_blocks: u8, 94 | /// Reserved GDT blocks for online filesystem growth 95 | pub reserved_gdt_blocks: U16, 96 | /// Journal UUID 97 | pub journal_uuid: [u8; 16], 98 | /// Journal inode 99 | pub journal_inum: U32, 100 | /// Journal device 101 | pub journal_dev: U32, 102 | /// Head of list of inodes to delete 103 | pub last_orphan: U32, 104 | /// HTREE hash seed 105 | pub hash_seed: [U32; 4], 106 | /// Default hash version to use 107 | pub def_hash_version: u8, 108 | /// Journal backup type 109 | pub jnl_backup_type: u8, 110 | /// Group descriptor size 111 | pub desc_size: U16, 112 | /// Default mount options 113 | pub default_mount_opts: U32, 114 | /// First metablock block group 115 | pub first_meta_bg: U32, 116 | /// When the filesystem was created 117 | pub mkfs_time: U32, 118 | /// Journal backup 119 | pub jnl_blocks: [U32; 17], 120 | /// High 32-bits of block count 121 | pub blocks_count_hi: U32, 122 | /// High 32-bits of free block count 123 | pub free_blocks_count_hi: U32, 124 | /// Minimum inode extra size 125 | pub min_extra_isize: U16, 126 | /// Desired inode extra size 127 | pub want_extra_isize: U16, 128 | /// Miscellaneous flags 129 | pub flags: U32, 130 | /// RAID stride 131 | pub raid_stride: U16, 132 | /// MMP update interval 133 | pub mmp_update_interval: U16, 134 | /// Multi-mount protection block 135 | pub mmp_block: U64, 136 | /// RAID stripe width 137 | pub raid_stripe_width: U32, 138 | /// Log groups per flex block 139 | pub log_groups_per_flex: u8, 140 | /// Metadata checksum type 141 | pub checksum_type: u8, 142 | /// Reserved padding 143 | pub reserved_pad: U16, 144 | /// Number of KiB written 145 | pub kbytes_written: U64, 146 | /// Snapshot inode number 147 | pub snapshot_inum: U32, 148 | /// Snapshot ID 149 | pub snapshot_id: U32, 150 | /// Reserved blocks for snapshot 151 | pub snapshot_r_blocks_count: U64, 152 | /// Snapshot list ID 153 | pub snapshot_list: U32, 154 | /// Error count 155 | pub error_count: U32, 156 | /// First error time 157 | pub first_error_time: U32, 158 | /// First error inode 159 | pub first_error_inod: U32, 160 | /// First error block 161 | pub first_error_block: U64, 162 | /// First error function 163 | pub first_error_func: [u8; 32], 164 | /// First error line number 165 | pub first_error_line: U32, 166 | /// Last error time 167 | pub last_error_time: U32, 168 | /// Last error inode 169 | pub last_error_inod: U32, 170 | /// Last error line number 171 | pub last_error_line: U32, 172 | /// Last error block 173 | pub last_error_block: U64, 174 | /// Last error function 175 | pub last_error_func: [u8; 32], 176 | /// Mount options in string form 177 | pub mount_opts: [u8; 64], 178 | /// User quota inode 179 | pub usr_quota_inum: U32, 180 | /// Group quota inode 181 | pub grp_quota_inum: U32, 182 | /// Overhead blocks/clusters 183 | pub overhead_clusters: U32, 184 | /// Reserved for future expansion 185 | pub reserved: [U32; 108], 186 | /// Superblock checksum 187 | pub checksum: U32, 188 | } 189 | 190 | /// Magic number that identifies an EXT4 superblock 191 | pub const MAGIC: U16 = U16::new(0xEF53); 192 | 193 | /// Start position of superblock in filesystem 194 | pub const START_POSITION: u64 = 1024; 195 | 196 | impl Detection for Ext4 { 197 | type Magic = U16; 198 | 199 | const OFFSET: u64 = START_POSITION; 200 | 201 | const MAGIC_OFFSET: u64 = START_POSITION + 0x38; 202 | 203 | const SIZE: usize = std::mem::size_of::(); 204 | 205 | fn is_valid_magic(magic: &Self::Magic) -> bool { 206 | *magic == MAGIC 207 | } 208 | } 209 | 210 | impl Ext4 { 211 | /// Return the encoded UUID for this superblock 212 | pub fn uuid(&self) -> Result { 213 | Ok(Uuid::from_bytes(self.uuid).hyphenated().to_string()) 214 | } 215 | 216 | /// Return the volume label as valid utf8 217 | pub fn label(&self) -> Result { 218 | Ok(str::from_utf8(&self.volume_name)?.into()) 219 | } 220 | } 221 | -------------------------------------------------------------------------------- /crates/superblock/src/f2fs.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: Copyright © 2025 Serpent OS Developers 2 | // 3 | // SPDX-License-Identifier: MPL-2.0 4 | 5 | //! F2FS (Flash-Friendly File System) superblock handling 6 | //! 7 | //! This module implements parsing and access to the F2FS filesystem superblock, 8 | //! which contains critical metadata about the filesystem including: 9 | //! - Version information 10 | //! - Layout parameters (sector size, block size, segment size etc) 11 | //! - Block addresses for key filesystem structures 12 | //! - Volume name and UUID 13 | //! - Encryption settings 14 | //! - Device information 15 | 16 | use crate::{Detection, UnicodeError}; 17 | use uuid::Uuid; 18 | use zerocopy::*; 19 | 20 | /// Maximum length of volume name 21 | pub const MAX_VOLUME_LEN: usize = 512; 22 | /// Maximum number of supported extensions 23 | pub const MAX_EXTENSION: usize = 64; 24 | /// Length of each extension entry 25 | pub const EXTENSION_LEN: usize = 8; 26 | /// Length of version string 27 | pub const VERSION_LEN: usize = 256; 28 | /// Maximum number of devices in array 29 | pub const MAX_DEVICES: usize = 8; 30 | /// Maximum number of quota types 31 | pub const MAX_QUOTAS: usize = 3; 32 | /// Length of stop reason string 33 | pub const MAX_STOP_REASON: usize = 32; 34 | /// Maximum number of recorded errors 35 | pub const MAX_ERRORS: usize = 16; 36 | 37 | /// Represents the F2FS superblock structure that exists on disk 38 | #[derive(Debug, FromBytes, Unaligned)] 39 | #[repr(C, packed)] 40 | pub struct F2FS { 41 | /// Magic number to identify F2FS filesystem 42 | pub magic: U32, 43 | /// Major version of filesystem 44 | pub major_ver: U16, 45 | /// Minor version of filesystem 46 | pub minor_ver: U16, 47 | /// Log2 of sector size in bytes 48 | pub log_sectorsize: U32, 49 | /// Log2 of sectors per block 50 | pub log_sectors_per_block: U32, 51 | /// Log2 of block size in bytes 52 | pub log_blocksize: U32, 53 | /// Log2 of blocks per segment 54 | pub log_blocks_per_seg: U32, 55 | /// Number of segments per section 56 | pub segs_per_sec: U32, 57 | /// Number of sections per zone 58 | pub secs_per_zone: U32, 59 | /// Checksum offset within superblock 60 | pub checksum_offset: U32, 61 | /// Total block count 62 | pub block_count: U64, 63 | /// Total section count 64 | pub section_count: U32, 65 | /// Total segment count 66 | pub segment_count: U32, 67 | /// Number of segments for checkpoint 68 | pub segment_count_ckpt: U32, 69 | /// Number of segments for SIT 70 | pub segment_count_sit: U32, 71 | /// Number of segments for NAT 72 | pub segment_count_nat: U32, 73 | /// Number of segments for SSA 74 | pub segment_count_ssa: U32, 75 | /// Number of segments for main area 76 | pub segment_count_main: U32, 77 | /// First segment block address 78 | pub segment0_blkaddr: U32, 79 | /// Checkpoint block address 80 | pub cp_blkaddr: U32, 81 | /// SIT block address 82 | pub sit_blkaddr: U32, 83 | /// NAT block address 84 | pub nat_blkaddr: U32, 85 | /// SSA block address 86 | pub ssa_blkaddr: U32, 87 | /// Main area block address 88 | pub main_blkaddr: U32, 89 | /// Root inode number 90 | pub root_ino: U32, 91 | /// Node inode number 92 | pub node_ino: U32, 93 | /// Meta inode number 94 | pub meta_ino: U32, 95 | /// Filesystem UUID 96 | pub uuid: [u8; 16], 97 | /// Volume name in UTF-16 98 | pub volume_name: [U16; MAX_VOLUME_LEN], 99 | /// Number of supported extensions 100 | pub extension_count: U32, 101 | /// List of supported extensions 102 | pub extension_list: [[u8; EXTENSION_LEN]; MAX_EXTENSION], 103 | /// Checkpoint payload 104 | pub cp_payload: U32, 105 | /// Filesystem version string 106 | pub version: [u8; VERSION_LEN], 107 | /// Initial filesystem version 108 | pub init_version: [u8; VERSION_LEN], 109 | /// Feature flags 110 | pub feature: U32, 111 | /// Encryption level 112 | pub encryption_level: u8, 113 | /// Encryption password salt 114 | pub encryption_pw_salt: [u8; 16], 115 | /// Array of attached devices 116 | pub devs: [Device; MAX_DEVICES], 117 | /// Quota file inode numbers 118 | pub qf_ino: [U32; MAX_QUOTAS], 119 | /// Number of hot extensions 120 | pub hot_ext_count: u8, 121 | /// Character encoding 122 | pub s_encoding: U16, 123 | /// Encoding flags 124 | pub s_encoding_flags: U16, 125 | /// Filesystem stop reason 126 | pub s_stop_reason: [u8; MAX_STOP_REASON], 127 | /// Recent errors 128 | pub s_errors: [u8; MAX_ERRORS], 129 | /// Reserved space 130 | pub reserved: [u8; 258], 131 | /// Superblock checksum 132 | pub crc: U32, 133 | } 134 | 135 | /// Represents a device entry in the F2FS superblock 136 | #[derive(Debug, Clone, Copy, FromBytes)] 137 | #[repr(C, packed)] 138 | pub struct Device { 139 | /// Device path 140 | pub path: [u8; 64], 141 | /// Total number of segments on device 142 | pub total_segments: U32, 143 | } 144 | 145 | impl Detection for F2FS { 146 | type Magic = U32; 147 | 148 | const OFFSET: u64 = START_POSITION; 149 | 150 | const MAGIC_OFFSET: u64 = START_POSITION; 151 | 152 | const SIZE: usize = std::mem::size_of::(); 153 | 154 | fn is_valid_magic(magic: &Self::Magic) -> bool { 155 | *magic == MAGIC 156 | } 157 | } 158 | 159 | /// F2FS superblock magic number for validation 160 | pub const MAGIC: U32 = U32::new(0xF2F52010); 161 | /// Starting position of superblock in bytes 162 | pub const START_POSITION: u64 = 1024; 163 | 164 | impl F2FS { 165 | /// Returns the filesystem UUID as a hyphenated string 166 | pub fn uuid(&self) -> Result { 167 | Ok(Uuid::from_bytes(self.uuid).hyphenated().to_string()) 168 | } 169 | 170 | /// Returns the volume label as a UTF-16 decoded string 171 | /// 172 | /// Handles null termination and invalid UTF-16 sequences 173 | pub fn label(&self) -> Result { 174 | // Convert the array of U16 to u16 175 | let vol = self.volume_name.map(|x| x.get()); 176 | let prelim_label = String::from_utf16(&vol)?; 177 | // Need valid grapheme step and skip (u16)\0 nul termination in fixed block size 178 | Ok(prelim_label.trim_end_matches('\0').to_owned()) 179 | } 180 | } 181 | -------------------------------------------------------------------------------- /crates/superblock/src/fat.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: Copyright © 2025 Serpent OS Developers 2 | // 3 | // SPDX-License-Identifier: MPL-2.0 4 | 5 | //! Fat32 6 | //! 7 | //! This module implements parsing and access to the FAT32 filesystem boot sector, 8 | //! which contains critical metadata about the filesystem including: 9 | //! - Version information 10 | //! - Volume name and UUID 11 | //! - Encryption settings 12 | 13 | use crate::{Detection, UnicodeError}; 14 | use zerocopy::*; 15 | 16 | /// Starting position of superblock in bytes 17 | pub const START_POSITION: u64 = 0; 18 | 19 | const MAGIC: [u8; 2] = [0x55, 0xAA]; 20 | 21 | #[repr(C, packed)] 22 | #[derive(FromBytes, Unaligned, Debug)] 23 | pub struct Fat { 24 | /// Boot strap short or near jump 25 | pub ignored: [u8; 3], 26 | /// Name - can be used to special case partition manager volumes 27 | pub system_id: [u8; 8], 28 | /// Bytes per logical sector 29 | pub sector_size: U16, 30 | /// Sectors per cluster 31 | pub sec_per_clus: u8, 32 | /// Reserved sectors 33 | pub _reserved: U16, 34 | /// Number of FATs 35 | pub fats: u8, 36 | /// Root directory entries 37 | pub dir_entries: U16, 38 | /// Number of sectors 39 | pub sectors: U16, 40 | /// Media code 41 | pub media: u8, 42 | /// Sectors/FAT 43 | pub fat_length: U16, 44 | /// Sectors per track 45 | pub secs_track: U16, 46 | /// Number of heads 47 | pub heads: U16, 48 | /// Hidden sectors (unused) 49 | pub hidden: U32, 50 | /// Number of sectors (if sectors == 0) 51 | pub total_sect: U32, 52 | 53 | // Shared memory region for FAT16 and FAT32 54 | // Best way is to use a union with zerocopy, however that requires having to use `--cfg zerocopy_derive_union_into_bytes` https://github.com/google/zerocopy/issues/1792 55 | pub shared: [u8; 54], // The size of the union fields in bytes 56 | } 57 | 58 | #[derive(FromBytes, Immutable, Unaligned)] 59 | #[repr(C, packed)] 60 | pub struct Fat16And32Fields { 61 | // Physical drive number 62 | pub drive_number: u8, 63 | // Mount state 64 | pub state: u8, 65 | // Extended boot signature 66 | pub signature: u8, 67 | // Volume ID 68 | pub vol_id: U32, 69 | // Volume label 70 | pub vol_label: [u8; 11], 71 | // File system type 72 | pub fs_type: [u8; 8], 73 | } 74 | 75 | #[derive(FromBytes, Immutable, Unaligned)] 76 | #[repr(C, packed)] 77 | pub struct Fat16Fields { 78 | pub common: Fat16And32Fields, 79 | } 80 | 81 | #[derive(FromBytes, Immutable, Unaligned)] 82 | #[repr(C, packed)] 83 | pub struct Fat32Fields { 84 | // FAT32-specific fields 85 | /// Sectors/FAT 86 | pub fat32_length: U32, 87 | /// FAT mirroring flags 88 | pub fat32_flags: U16, 89 | /// Major, minor filesystem version 90 | pub fat32_version: [u8; 2], 91 | /// First cluster in root directory 92 | pub root_cluster: U32, 93 | /// Filesystem info sector 94 | pub info_sector: U16, 95 | /// Backup boot sector 96 | pub backup_boot: U16, 97 | /// Unused 98 | pub reserved2: [U16; 6], 99 | 100 | pub common: Fat16And32Fields, 101 | } 102 | 103 | impl Detection for Fat { 104 | type Magic = [u8; 2]; 105 | 106 | const OFFSET: u64 = START_POSITION; 107 | 108 | const MAGIC_OFFSET: u64 = 0x1FE; 109 | 110 | const SIZE: usize = std::mem::size_of::(); 111 | 112 | fn is_valid_magic(magic: &Self::Magic) -> bool { 113 | *magic == MAGIC 114 | } 115 | } 116 | 117 | pub enum FatType { 118 | Fat16, 119 | Fat32, 120 | } 121 | 122 | impl Fat { 123 | pub fn fat_type(&self) -> FatType { 124 | // this is how the linux kernel does it in https://github.com/torvalds/linux/blob/master/fs/fat/inode.c 125 | if self.fat_length == 0 && self.fat32().fat32_length != 0 { 126 | FatType::Fat32 127 | } else { 128 | FatType::Fat16 129 | } 130 | } 131 | 132 | /// Returns the filesystem id 133 | pub fn uuid(&self) -> Result { 134 | Ok(match self.fat_type() { 135 | FatType::Fat16 => vol_id(self.fat16().common.vol_id), 136 | FatType::Fat32 => vol_id(self.fat32().common.vol_id), 137 | }) 138 | } 139 | 140 | /// Returns the volume label 141 | pub fn label(&self) -> Result { 142 | match self.fat_type() { 143 | FatType::Fat16 => vol_label(&self.fat16().common.vol_label), 144 | FatType::Fat32 => vol_label(&self.fat32().common.vol_label), 145 | } 146 | } 147 | 148 | fn fat16(&self) -> &Fat16Fields { 149 | let bytes: &[u8; size_of::()] = first_n_bytes(&self.shared); 150 | transmute_ref!(bytes) 151 | } 152 | 153 | fn fat32(&self) -> &Fat32Fields { 154 | transmute_ref!(&self.shared) 155 | } 156 | } 157 | 158 | fn first_n_bytes(arr: &[u8; M]) -> &[u8; N] { 159 | const { 160 | assert!(M >= N, "input array must be at least as large as output array"); 161 | } 162 | 163 | <&[u8; N]>::try_from(&arr[..N]).unwrap() 164 | } 165 | 166 | fn vol_label(vol_label: &[u8; 11]) -> Result { 167 | Ok(String::from_utf8_lossy(vol_label).trim_end_matches(' ').to_string()) 168 | } 169 | 170 | fn vol_id(vol_id: U32) -> String { 171 | format!("{:04X}-{:04X}", vol_id >> 16, vol_id & 0xFFFF) 172 | } 173 | -------------------------------------------------------------------------------- /crates/superblock/src/lib.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: Copyright © 2025 Serpent OS Developers 2 | // 3 | // SPDX-License-Identifier: MPL-2.0 4 | 5 | //! Superblock detection and handling for various filesystems 6 | //! 7 | //! This module provides functionality to detect and read superblocks from different 8 | //! filesystem types including Btrfs, Ext4, F2FS, LUKS2, and XFS. 9 | 10 | use std::io::{self, BufRead, Cursor, Read, Seek}; 11 | 12 | use snafu::{ResultExt, Snafu}; 13 | use zerocopy::FromBytes; 14 | 15 | pub mod btrfs; 16 | pub mod ext4; 17 | pub mod f2fs; 18 | pub mod fat; 19 | pub mod luks2; 20 | pub mod xfs; 21 | 22 | /// Common interface for superblock detection 23 | pub trait Detection: Sized + FromBytes { 24 | /// The magic number type for this superblock 25 | type Magic: FromBytes + PartialEq + Eq; 26 | 27 | /// The offset in bytes where the superblock is located 28 | const OFFSET: u64; 29 | 30 | /// The offset within the superblock where the magic number is located 31 | const MAGIC_OFFSET: u64; 32 | 33 | /// The size in bytes of the superblock 34 | const SIZE: usize; 35 | 36 | /// Check if the magic number is valid for this superblock type 37 | fn is_valid_magic(magic: &Self::Magic) -> bool; 38 | } 39 | 40 | /// Errors that can occur when reading superblocks 41 | #[derive(Debug, Snafu)] 42 | pub enum Error { 43 | /// An I/O error occurred 44 | #[snafu(display("io"))] 45 | Io { source: io::Error }, 46 | 47 | /// No known filesystem superblock was detected 48 | #[snafu(display("unknown superblock"))] 49 | UnknownSuperblock, 50 | } 51 | 52 | /// Errors that can occur when decoding strings from FS metadata 53 | #[derive(Debug, Snafu)] 54 | pub enum UnicodeError { 55 | /// Error decoding UTF-8 string data 56 | #[snafu(display("{source}"), context(false))] 57 | InvalidUtf8 { source: std::str::Utf8Error }, 58 | 59 | /// Error decoding UTF-16 string data 60 | #[snafu(display("{source}"), context(false))] 61 | InvalidUtf16 { source: std::string::FromUtf16Error }, 62 | } 63 | 64 | /// Attempts to detect a superblock of the given type from the reader 65 | pub fn detect_superblock(reader: &mut R) -> io::Result> { 66 | reader.seek(io::SeekFrom::Start(T::MAGIC_OFFSET))?; 67 | let mut magic_buf = vec![0u8; std::mem::size_of::()]; 68 | reader.read_exact(&mut magic_buf)?; 69 | 70 | match T::Magic::read_from_bytes(&magic_buf) { 71 | Ok(magic) if T::is_valid_magic(&magic) => { 72 | reader.seek(io::SeekFrom::Start(T::OFFSET))?; 73 | let mut block_buf = vec![0u8; T::SIZE]; 74 | reader.read_exact(&mut block_buf)?; 75 | if let Ok(block) = FromBytes::read_from_bytes(&block_buf) { 76 | Ok(Some(block)) 77 | } else { 78 | Ok(None) 79 | } 80 | } 81 | _ => Ok(None), 82 | } 83 | } 84 | 85 | /// Supported filesystem types that can be detected and read 86 | #[derive(Clone, Debug, PartialEq, Eq)] 87 | pub enum Kind { 88 | /// Btrfs filesystem 89 | Btrfs, 90 | /// Ext4 filesystem 91 | Ext4, 92 | /// LUKS2 encrypted container 93 | Luks2, 94 | /// F2FS (Flash-Friendly File System) 95 | F2FS, 96 | /// XFS filesystem 97 | Xfs, 98 | /// FAT filesystem 99 | Fat, 100 | } 101 | 102 | impl std::fmt::Display for Kind { 103 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 104 | match &self { 105 | Kind::Btrfs => f.write_str("btrfs"), 106 | Kind::Ext4 => f.write_str("ext4"), 107 | Kind::Luks2 => f.write_str("luks2"), 108 | Kind::F2FS => f.write_str("f2fs"), 109 | Kind::Xfs => f.write_str("xfs"), 110 | Kind::Fat => f.write_str("fat"), 111 | } 112 | } 113 | } 114 | 115 | pub enum Superblock { 116 | Btrfs(Box), 117 | Ext4(Box), 118 | F2FS(Box), 119 | Luks2(Box), 120 | Xfs(Box), 121 | Fat(Box), 122 | } 123 | 124 | impl Superblock { 125 | /// Returns the filesystem type of this superblock 126 | pub fn kind(&self) -> Kind { 127 | match self { 128 | Superblock::Btrfs(_) => Kind::Btrfs, 129 | Superblock::Ext4(_) => Kind::Ext4, 130 | Superblock::F2FS(_) => Kind::F2FS, 131 | Superblock::Luks2(_) => Kind::Luks2, 132 | Superblock::Xfs(_) => Kind::Xfs, 133 | Superblock::Fat(_) => Kind::Fat, 134 | } 135 | } 136 | 137 | /// Returns the filesystem UUID if available 138 | pub fn uuid(&self) -> Result { 139 | match self { 140 | Superblock::Btrfs(block) => block.uuid(), 141 | Superblock::Ext4(block) => block.uuid(), 142 | Superblock::F2FS(block) => block.uuid(), 143 | Superblock::Luks2(block) => block.uuid(), 144 | Superblock::Xfs(block) => block.uuid(), 145 | Superblock::Fat(block) => block.uuid(), 146 | } 147 | } 148 | 149 | /// Returns the volume label if available 150 | pub fn label(&self) -> Result { 151 | match self { 152 | Superblock::Btrfs(block) => block.label(), 153 | Superblock::Ext4(block) => block.label(), 154 | Superblock::F2FS(block) => block.label(), 155 | Superblock::Luks2(block) => block.label(), 156 | Superblock::Xfs(block) => block.label(), 157 | Superblock::Fat(block) => block.label(), 158 | } 159 | } 160 | } 161 | 162 | impl Superblock { 163 | /// Attempt to detect and read a filesystem superblock from raw bytes 164 | /// 165 | /// This is more efficient than using a reader as it avoids multiple seeks 166 | pub fn from_bytes(bytes: &[u8]) -> Result { 167 | let mut cursor = Cursor::new(bytes); 168 | 169 | macro_rules! try_detect { 170 | ($variant:ident, $ty:ty) => { 171 | if let Some(sb) = detect_superblock::<$ty, _>(&mut cursor).context(IoSnafu)? { 172 | return Ok(Self::$variant(Box::new(sb))); 173 | } 174 | }; 175 | } 176 | 177 | // Try each filesystem type in order of likelihood 178 | try_detect!(Ext4, ext4::Ext4); 179 | try_detect!(Btrfs, btrfs::Btrfs); 180 | try_detect!(F2FS, f2fs::F2FS); 181 | try_detect!(Xfs, xfs::Xfs); 182 | try_detect!(Luks2, luks2::Luks2); 183 | try_detect!(Fat, fat::Fat); 184 | 185 | Err(Error::UnknownSuperblock) 186 | } 187 | 188 | /// Attempt to detect and read a filesystem superblock from a reader 189 | /// 190 | /// Note: This will read the minimum necessary bytes to detect the superblock, 191 | /// which is more efficient than reading the entire device. 192 | pub fn from_reader(reader: &mut R) -> Result { 193 | // Preallocate a fixed buffer for the largest superblock we need to read 194 | let mut bytes = vec![0u8; 128 * 1024]; // 128KB covers all superblock offsets 195 | reader.rewind().context(IoSnafu)?; 196 | reader.read_exact(&mut bytes).context(IoSnafu)?; 197 | 198 | Self::from_bytes(&bytes) 199 | } 200 | } 201 | 202 | #[cfg(test)] 203 | mod tests { 204 | use std::{ 205 | fs, 206 | io::{Cursor, Read}, 207 | }; 208 | 209 | use crate::Kind; 210 | 211 | use super::Superblock; 212 | 213 | #[test_log::test] 214 | fn test_determination() { 215 | let tests = vec![ 216 | ( 217 | "btrfs", 218 | Kind::Btrfs, 219 | "blsforme testing", 220 | "829d6a03-96a5-4749-9ea2-dbb6e59368b2", 221 | ), 222 | ( 223 | "ext4", 224 | Kind::Ext4, 225 | "blsforme testing", 226 | "731af94c-9990-4eed-944d-5d230dbe8a0d", 227 | ), 228 | ( 229 | "f2fs", 230 | Kind::F2FS, 231 | "blsforme testing", 232 | "d2c85810-4e75-4274-bc7d-a78267af7443", 233 | ), 234 | ("luks+ext4", Kind::Luks2, "", "be373cae-2bd1-4ad5-953f-3463b2e53e59"), 235 | ("xfs", Kind::Xfs, "BLSFORME", "45e8a3bf-8114-400f-95b0-380d0fb7d42d"), 236 | ("fat16", Kind::Fat, "TESTLABEL", "A1B2-C3D4"), 237 | ("fat32", Kind::Fat, "TESTLABEL", "A1B2-C3D4"), 238 | ]; 239 | 240 | // Pre-allocate a buffer for determination tests 241 | let mut memory: Vec = Vec::with_capacity(512 * 1024); 242 | 243 | for (fsname, kind, label, uuid) in tests.into_iter() { 244 | // Swings and roundabouts: Unpack ztd image in memory to get the Seekable trait we need 245 | // While each Superblock API is non-seekable, we enforce superblock::for_reader to be seekable 246 | // to make sure we pre-read a blob and pass it in for rewind/speed. 247 | memory.clear(); 248 | 249 | let mut fi = fs::File::open(format!("tests/{fsname}.img.zst")).expect("Cannot find test image"); 250 | let mut stream = zstd::stream::Decoder::new(&mut fi).expect("Unable to decode stream"); 251 | stream 252 | .read_to_end(&mut memory) 253 | .expect("Could not unpack filesystem in memory"); 254 | 255 | let mut cursor = Cursor::new(&mut memory); 256 | let block = Superblock::from_reader(&mut cursor).expect("Failed to find right block implementation"); 257 | eprintln!("{fsname}.img.zstd: superblock matched to {}", block.kind()); 258 | assert_eq!(block.kind(), kind); 259 | assert_eq!(block.label().unwrap(), label); 260 | assert_eq!(block.uuid().unwrap(), uuid); 261 | 262 | // Is it possible to get the JSON config out of LUKS2? 263 | if let Superblock::Luks2(block) = block { 264 | let config = block.read_config(&mut cursor).expect("Cannot read LUKS2 config"); 265 | eprintln!("{}", serde_json::to_string_pretty(&config).unwrap()); 266 | assert!(config.config.json_size > 0); 267 | assert!(config.config.keyslots_size > 0); 268 | 269 | let keyslot = config.keyslots.get(&0).unwrap(); 270 | assert_eq!(keyslot.area.encryption, "aes-xts-plain64"); 271 | } 272 | } 273 | } 274 | } 275 | -------------------------------------------------------------------------------- /crates/superblock/src/luks2.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: Copyright © 2025 Serpent OS Developers 2 | // 3 | // SPDX-License-Identifier: MPL-2.0 4 | 5 | //! # LUKS2 superblock support 6 | //! 7 | //! This module provides functionality for reading and parsing LUKS2 (Linux Unified Key Setup 2) 8 | //! superblocks and their associated metadata. 9 | //! 10 | //! LUKS2 is a disk encryption format that uses the dm-crypt subsystem. It stores metadata 11 | //! like encryption parameters, key slots and segment information in JSON format. 12 | //! 13 | 14 | use std::io; 15 | 16 | use snafu::Snafu; 17 | 18 | mod config; 19 | mod superblock; 20 | 21 | pub use config::*; 22 | pub use superblock::*; 23 | 24 | /// Errors that can occur when parsing LUKS config 25 | #[derive(Debug, Snafu)] 26 | pub enum ConfigError { 27 | /// An I/O error occurred 28 | #[snafu(display("io"))] 29 | Io { source: io::Error }, 30 | 31 | /// Invalid JSON 32 | #[snafu(display("invalid json"))] 33 | InvalidJson { source: serde_json::Error }, 34 | 35 | /// Error decoding UTF-8 string data 36 | #[snafu(display("invalid utf8 in decode"))] 37 | InvalidUtf8 { source: std::str::Utf8Error }, 38 | } 39 | -------------------------------------------------------------------------------- /crates/superblock/src/luks2/config.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: Copyright © 2025 Serpent OS Developers 2 | // 3 | // SPDX-License-Identifier: MPL-2.0 4 | 5 | use serde::{Deserialize, Serialize}; 6 | use std::collections::HashMap; 7 | 8 | /// Top-level LUKS2 configuration structure representing a LUKS2 encrypted device. 9 | /// This structure contains all the configuration needed to manage a LUKS2 device, 10 | /// including core configuration, keyslots and segments. 11 | #[derive(Debug, Deserialize, Serialize)] 12 | pub struct Luks2Config { 13 | /// Core configuration data containing metadata and keyslot sizes 14 | pub config: Luks2ConfigData, 15 | /// Map of keyslot IDs to their corresponding keyslot configurations. 16 | /// Each keyslot contains information about key derivation and storage. 17 | pub keyslots: HashMap, 18 | /// Map of segment IDs to their corresponding segment configurations. 19 | /// Segments define the encrypted regions of the device. 20 | pub segments: HashMap, 21 | // pub tokens: HashMap, 22 | // pub digests: HashMap, 23 | } 24 | 25 | /// Core LUKS2 configuration data containing essential metadata about the encrypted device. 26 | #[derive(Debug, Deserialize, Serialize)] 27 | pub struct Luks2ConfigData { 28 | /// Size of the JSON metadata area in bytes. 29 | /// This defines how much space is reserved for the LUKS2 header. 30 | #[serde(with = "display_from_str")] 31 | pub json_size: u64, 32 | 33 | /// Size of the keyslots area in bytes. 34 | /// This defines the total space available for storing encrypted keys. 35 | #[serde(with = "display_from_str")] 36 | pub keyslots_size: u64, 37 | 38 | /// Optional configuration flags that modify device behavior. 39 | /// These flags can affect how the device is activated and used. 40 | #[serde(default)] 41 | pub flags: Vec, 42 | 43 | /// Requirements for device activation. 44 | /// These define what conditions must be met to unlock the device. 45 | #[serde(default)] 46 | pub requirements: Vec, 47 | } 48 | 49 | /// Key derivation function (KDF) configuration used to generate encryption keys from passwords. 50 | #[derive(Debug, Deserialize, Serialize)] 51 | pub struct Luks2Kdf { 52 | /// Type of KDF (e.g. pbkdf2, argon2i, argon2id) 53 | /// Specifies which algorithm is used for key derivation 54 | #[serde(rename = "type")] 55 | pub kdf_type: String, 56 | /// Random salt used in key derivation to prevent rainbow table attacks 57 | pub salt: String, 58 | 59 | /// Hash algorithm used for PBKDF2 60 | /// Only applicable when kdf_type is "pbkdf2" 61 | #[serde(skip_serializing_if = "Option::is_none")] 62 | pub hash: Option, 63 | /// Number of iterations for PBKDF2 64 | /// Only applicable when kdf_type is "pbkdf2" 65 | #[serde(skip_serializing_if = "Option::is_none")] 66 | pub iterations: Option, 67 | 68 | /// Time cost parameter for Argon2 69 | /// Only applicable when kdf_type is "argon2i" or "argon2id" 70 | #[serde(skip_serializing_if = "Option::is_none")] 71 | pub time: Option, 72 | /// Memory usage in bytes for Argon2 73 | /// Only applicable when kdf_type is "argon2i" or "argon2id" 74 | #[serde(skip_serializing_if = "Option::is_none")] 75 | pub memory: Option, 76 | /// Number of parallel threads for Argon2 77 | /// Only applicable when kdf_type is "argon2i" or "argon2id" 78 | #[serde(skip_serializing_if = "Option::is_none")] 79 | pub cpus: Option, 80 | } 81 | 82 | /// Configuration for a single keyslot containing key material and derivation settings. 83 | #[derive(Debug, Deserialize, Serialize)] 84 | pub struct Luks2Keyslot { 85 | /// Type of keyslot, defining how the key material is processed 86 | #[serde(rename = "type")] 87 | pub slot_type: String, 88 | 89 | /// Size of the keyslot key in bytes 90 | pub key_size: u64, 91 | 92 | /// Storage area configuration defining where and how key material is stored 93 | pub area: Luks2KeyslotArea, 94 | /// Key derivation parameters used to process passwords into keys 95 | pub kdf: Luks2Kdf, 96 | } 97 | 98 | /// Configuration for keyslot storage area defining where encrypted keys are stored. 99 | #[derive(Debug, Deserialize, Serialize)] 100 | pub struct Luks2KeyslotArea { 101 | /// Type of storage area, defining how the area is organized 102 | #[serde(rename = "type")] 103 | pub area_type: String, 104 | 105 | /// Offset in bytes where this area begins on the device 106 | #[serde(with = "display_from_str")] 107 | pub offset: u64, 108 | 109 | /// Size of this area in bytes 110 | #[serde(with = "display_from_str")] 111 | pub size: u64, 112 | 113 | /// Encryption algorithm used to protect stored key material 114 | pub encryption: String, 115 | 116 | /// Size of encryption key in bytes used for this area 117 | pub key_size: u64, 118 | } 119 | 120 | /// Configuration for a disk segment defining an encrypted region of the device. 121 | #[derive(Debug, Deserialize, Serialize)] 122 | pub struct Luks2Segment { 123 | /// Type of segment, defining how the region is processed 124 | #[serde(rename = "type")] 125 | pub segment_type: String, 126 | /// Offset where segment begins, as a string representation 127 | pub offset: String, 128 | /// Size of segment, as a string representation 129 | pub size: String, 130 | /// Initialization vector tweak used for encryption 131 | pub iv_tweak: String, 132 | /// Encryption algorithm used for this segment 133 | pub encryption: String, 134 | /// Sector size in bytes - the granularity of encryption 135 | pub sector_size: u64, 136 | } 137 | 138 | mod display_from_str { 139 | use std::{fmt::Display, str::FromStr}; 140 | 141 | use serde::{Deserialize, Deserializer, Serializer}; 142 | 143 | pub(super) fn serialize(value: &T, serializer: S) -> Result 144 | where 145 | T: Display, 146 | S: Serializer, 147 | { 148 | serializer.serialize_str(&value.to_string()) 149 | } 150 | 151 | pub(super) fn deserialize<'de, T, D>(deserializer: D) -> Result 152 | where 153 | T: FromStr, 154 | T::Err: Display, 155 | D: Deserializer<'de>, 156 | { 157 | let s = String::deserialize(deserializer)?; 158 | s.parse().map_err(serde::de::Error::custom) 159 | } 160 | } 161 | -------------------------------------------------------------------------------- /crates/superblock/src/luks2/superblock.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: Copyright © 2025 Serpent OS Developers 2 | // 3 | // SPDX-License-Identifier: MPL-2.0 4 | 5 | //! # LUKS2 superblock support 6 | //! 7 | //! This module provides functionality for reading and parsing LUKS2 (Linux Unified Key Setup 2) 8 | //! superblocks and their associated metadata. 9 | //! 10 | //! LUKS2 is a disk encryption format that uses the dm-crypt subsystem. It stores metadata 11 | //! like encryption parameters, key slots and segment information in JSON format. 12 | //! 13 | //! ## Format Details 14 | //! 15 | //! The LUKS2 header contains: 16 | //! - Magic number to identify LUKS2 format 17 | //! - Version number 18 | //! - Header size and offset 19 | //! - UUID and label for volume identification 20 | //! - Checksum algorithm and salt for validation 21 | //! - JSON metadata area containing encryption parameters 22 | //! 23 | 24 | use std::{ 25 | io::{Read, Seek}, 26 | ops::Sub, 27 | }; 28 | 29 | use snafu::ResultExt; 30 | use zerocopy::*; 31 | 32 | use super::{ConfigError, InvalidJsonSnafu, InvalidUtf8Snafu, IoSnafu, Luks2Config}; 33 | use crate::{Detection, UnicodeError}; 34 | 35 | /// Length of the magic number field in bytes 36 | pub const MAGIC_LEN: usize = 6; 37 | /// Length of the label field in bytes 38 | pub const LABEL_LEN: usize = 48; 39 | /// Length of the checksum algorithm field in bytes 40 | pub const CHECKSUM_ALG_LEN: usize = 32; 41 | /// Length of the salt field in bytes 42 | pub const SALT_LEN: usize = 64; 43 | /// Length of the UUID field in bytes 44 | pub const UUID_LEN: usize = 40; 45 | /// Length of the checksum field in bytes 46 | pub const CHECKSUM_LEN: usize = 64; 47 | 48 | /// LUKS2 on-disk header format 49 | /// 50 | /// Per the `cryptsetup` docs for dm-crypt backed LUKS2, header is at first byte. 51 | /// The header contains metadata about the encrypted volume including magic number, 52 | /// version, checksums and JSON configuration. 53 | #[derive(FromBytes, Unaligned, Debug)] 54 | #[repr(C, packed)] 55 | pub struct Luks2 { 56 | /// Magic number identifying LUKS2 format 57 | pub magic: [u8; MAGIC_LEN], 58 | /// LUKS format version 59 | pub version: U16, 60 | /// Size of the header in bytes 61 | pub hdr_size: U64, 62 | /// Header sequence ID for rewrite protection 63 | pub seqid: U64, 64 | /// Volume label 65 | pub label: [u8; LABEL_LEN], 66 | /// Checksum algorithm identifier 67 | pub checksum_alg: [u8; CHECKSUM_ALG_LEN], 68 | /// Salt used for checksum 69 | pub salt: [u8; SALT_LEN], 70 | /// Volume UUID 71 | pub uuid: [u8; UUID_LEN], 72 | /// Subsystem label 73 | pub subsystem: [u8; LABEL_LEN], 74 | /// Secondary header offset 75 | pub hdr_offset: U64, 76 | /// Padding bytes 77 | pub padding: [u8; 184], 78 | /// Header checksum 79 | pub csum: [u8; CHECKSUM_LEN], 80 | /// Additional padding to 4096 bytes 81 | pub padding4096: [u8; 7 * 512], 82 | } 83 | 84 | /// Magic number constants for LUKS2 format identification 85 | pub struct MagicMatch; 86 | 87 | impl MagicMatch { 88 | /// Standard LUKS2 magic number 89 | pub const LUKS2: [u8; MAGIC_LEN] = [b'L', b'U', b'K', b'S', 0xba, 0xbe]; 90 | /// Alternative LUKS2 magic number (reversed) 91 | pub const SKUL2: [u8; MAGIC_LEN] = [b'S', b'K', b'U', b'L', 0xba, 0xbe]; 92 | } 93 | 94 | impl Detection for Luks2 { 95 | type Magic = [u8; MAGIC_LEN]; 96 | 97 | const OFFSET: u64 = 0; 98 | 99 | const MAGIC_OFFSET: u64 = 0; 100 | 101 | const SIZE: usize = std::mem::size_of::(); 102 | 103 | fn is_valid_magic(magic: &Self::Magic) -> bool { 104 | *magic == MagicMatch::LUKS2 || *magic == MagicMatch::SKUL2 105 | } 106 | } 107 | 108 | impl Luks2 { 109 | /// Get the UUID of the LUKS2 volume 110 | /// 111 | /// Note: LUKS2 stores string UUID rather than 128-bit sequence 112 | pub fn uuid(&self) -> Result { 113 | Ok(str::from_utf8(&self.uuid)?.trim_end_matches('\0').to_owned()) 114 | } 115 | 116 | /// Get the label of the LUKS2 volume 117 | /// 118 | /// Note: Label is often empty, set in config instead 119 | pub fn label(&self) -> Result { 120 | Ok(str::from_utf8(&self.label)?.trim_end_matches('\0').to_owned()) 121 | } 122 | 123 | /// Read and parse the JSON configuration areas from the LUKS2 header 124 | /// 125 | /// # Arguments 126 | /// 127 | /// * `reader` - Any type implementing Read trait to read the JSON data 128 | /// 129 | /// # Returns 130 | /// 131 | /// Returns parsed Luks2Config on success, Error on failure 132 | pub fn read_config(&self, reader: &mut R) -> Result { 133 | let mut json_data = vec![0u8; self.hdr_size.get().sub(4096) as usize]; 134 | // Skip the header and read the JSON data 135 | reader 136 | .seek(std::io::SeekFrom::Start(std::mem::size_of::() as u64)) 137 | .context(IoSnafu)?; 138 | reader.read_exact(&mut json_data).context(IoSnafu)?; 139 | 140 | // clip the json_data at the first nul byte 141 | let raw_input = str::from_utf8(&json_data) 142 | .context(InvalidUtf8Snafu)? 143 | .trim_end_matches('\0'); 144 | let config: Luks2Config = serde_json::from_str(raw_input).context(InvalidJsonSnafu)?; 145 | Ok(config) 146 | } 147 | } 148 | -------------------------------------------------------------------------------- /crates/superblock/src/xfs.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: Copyright © 2025 Serpent OS Developers 2 | // 3 | // SPDX-License-Identifier: MPL-2.0 4 | 5 | //! XFS filesystem superblock parsing and handling 6 | //! 7 | //! This module provides functionality to parse and interact with XFS filesystem superblocks. 8 | //! The XFS superblock contains critical metadata about the filesystem including: 9 | //! - Basic filesystem parameters (block size, inode counts, etc) 10 | //! - UUID and volume label information 11 | //! - Feature flags and compatibility information 12 | //! - Quota tracking data 13 | //! - Log and realtime extent details 14 | 15 | use crate::{Detection, UnicodeError}; 16 | use uuid::Uuid; 17 | use zerocopy::*; 18 | 19 | /// 64-bit block number for regular filesystem blocks 20 | pub type RfsBlock = U64; 21 | /// 64-bit extent length for realtime blocks 22 | pub type RtbXlen = U64; 23 | /// 64-bit filesystem block number 24 | pub type FsBlock = U64; 25 | /// 64-bit inode number 26 | pub type Ino = I64; 27 | /// 32-bit allocation group block number 28 | pub type AgBlock = U32; 29 | /// 32-bit allocation group count 30 | pub type AgCount = U32; 31 | /// 32-bit extent length 32 | pub type ExtLen = U32; 33 | /// 64-bit log sequence number 34 | pub type Lsn = I64; 35 | 36 | /// Maximum length of XFS volume label (12 bytes) 37 | pub const MAX_LABEL_LEN: usize = 12; 38 | 39 | /// XFS superblock structure, containing filesystem metadata and parameters 40 | /// 41 | /// This structure maps directly to the on-disk format of an XFS superblock. 42 | /// All multi-byte integer fields are stored in big-endian byte order. 43 | #[derive(FromBytes, Debug)] 44 | #[repr(C, align(8))] 45 | pub struct Xfs { 46 | /// Magic number, must contain 'XFSB' 47 | pub magicnum: U32, 48 | /// Filesystem block size in bytes 49 | pub blocksize: U32, 50 | /// Number of blocks in data subvolume 51 | pub dblocks: RfsBlock, 52 | /// Number of blocks in realtime subvolume 53 | pub rblocks: RfsBlock, 54 | /// Number of realtime extents 55 | pub rextents: RtbXlen, 56 | /// Filesystem UUID 57 | pub uuid: [u8; 16], 58 | /// Starting block of log if internal log 59 | pub logstart: FsBlock, 60 | /// Root directory inode number 61 | pub rootino: Ino, 62 | /// Realtime bitmap inode 63 | pub rbmino: Ino, 64 | /// Realtime summary inode 65 | pub rsumino: Ino, 66 | /// Realtime extent size in blocks 67 | pub rextsize: AgBlock, 68 | /// Blocks per allocation group 69 | pub agblocks: AgBlock, 70 | /// Number of allocation groups 71 | pub agcount: AgCount, 72 | /// Number of realtime bitmap blocks 73 | pub rbmblocks: ExtLen, 74 | /// Number of log blocks 75 | pub logblocks: ExtLen, 76 | /// Filesystem version number 77 | pub versionnum: U16, 78 | /// Sector size in bytes 79 | pub sectsize: U16, 80 | /// Inode size in bytes 81 | pub inodesize: U16, 82 | /// Inodes per block 83 | pub inopblock: U16, 84 | /// Filesystem volume name/label 85 | pub fname: [u8; MAX_LABEL_LEN], 86 | /// Log2 of blocksize 87 | pub blocklog: u8, 88 | /// Log2 of sector size 89 | pub sectlog: u8, 90 | /// Log2 of inode size 91 | pub inodelog: u8, 92 | /// Log2 of inodes per block 93 | pub inopblog: u8, 94 | /// Log2 of blocks per allocation group 95 | pub agblklog: u8, 96 | /// Log2 of realtime extents 97 | pub rextslog: u8, 98 | /// Filesystem being created flag 99 | pub inprogress: u8, 100 | /// Max % of fs for inodes 101 | pub imax_pct: u8, 102 | 103 | /// Number of inodes allocated 104 | pub icount: U64, 105 | /// Number of free inodes 106 | pub ifree: U64, 107 | /// Number of free data blocks 108 | pub fdblocks: U64, 109 | /// Number of free realtime extents 110 | pub frextents: U64, 111 | 112 | /// User quota inode 113 | pub uquotino: Ino, 114 | /// Group quota inode 115 | pub gquotino: Ino, 116 | /// Quota flags 117 | pub qflags: U16, 118 | /// Flags 119 | pub flags: u8, 120 | /// Shared version number 121 | pub shared_vn: u8, 122 | /// Inode chunk alignment 123 | pub inoalignment: ExtLen, 124 | /// Stripe or RAID unit 125 | pub unit: U32, 126 | /// Stripe or RAID width 127 | pub width: U32, 128 | /// Log2 of dir block size 129 | pub dirblklog: u8, 130 | /// Log2 of log sector size 131 | pub logsectlog: u8, 132 | /// Log sector size 133 | pub logsectsize: U16, 134 | /// Log stripe unit size 135 | pub logsunit: U32, 136 | /// Version 2 features 137 | pub features2: U32, 138 | 139 | /// Bad features mask 140 | pub bad_features: U32, 141 | 142 | /// Compatible feature flags 143 | pub features_compat: U32, 144 | /// Read-only compatible feature flags 145 | pub features_ro_cmopat: U32, 146 | /// Incompatible feature flags 147 | pub features_incompat: U32, 148 | /// Log incompatible feature flags 149 | pub features_log_incompat: U32, 150 | 151 | /// Superblock checksum 152 | pub crc: U32, 153 | /// Sparse inode alignment 154 | pub spino_align: ExtLen, 155 | 156 | /// Project quota inode 157 | pub pquotino: Ino, 158 | /// Last write sequence 159 | pub lsn: Lsn, 160 | /// Metadata UUID 161 | pub meta_uuid: [u8; 16], 162 | } 163 | 164 | /// XFS superblock magic number ('XFSB' in ASCII) 165 | pub const MAGIC: U32 = U32::new(0x58465342); 166 | 167 | impl Xfs { 168 | /// Returns the filesystem UUID as a properly formatted string 169 | pub fn uuid(&self) -> Result { 170 | Ok(Uuid::from_bytes(self.uuid).hyphenated().to_string()) 171 | } 172 | 173 | /// Returns the volume label as a UTF-8 string, trimming any null termination 174 | pub fn label(&self) -> Result { 175 | Ok(str::from_utf8(&self.fname)?.trim_end_matches('\0').to_owned()) 176 | } 177 | } 178 | 179 | impl Detection for Xfs { 180 | type Magic = U32; 181 | 182 | const OFFSET: u64 = 0x0; 183 | 184 | const MAGIC_OFFSET: u64 = 0x0; 185 | 186 | const SIZE: usize = std::mem::size_of::(); 187 | 188 | fn is_valid_magic(magic: &Self::Magic) -> bool { 189 | *magic == MAGIC 190 | } 191 | } 192 | -------------------------------------------------------------------------------- /crates/superblock/tests/README.md: -------------------------------------------------------------------------------- 1 | # Raw filesystem images 2 | 3 | We provide a number of raw filesystem images (without content) to verify 4 | the `superblock` crate, providing CI for filesystems that may change over time. 5 | 6 | Primarily `blsforme` needs to understand the UUID for `/proc/cmdline` generation, 7 | however extraction of volume label is also supported (`blsforme testing` in most 8 | test images) 9 | 10 | ## btrfs.img.zst 11 | 12 | UUID: 829d6a03-96a5-4749-9ea2-dbb6e59368b2 13 | 14 | ## ext4.img.zst 15 | 16 | UUID: 731af94c-9990-4eed-944d-5d230dbe8a0d 17 | 18 | ## f2fs.img.zst 19 | 20 | UUID: d2c85810-4e75-4274-bc7d-a78267af7443 21 | 22 | ## luks+ext4.img.zst 23 | 24 | Password : abc 25 | Version : LUKS2 26 | LUKS UUID: be373cae-2bd1-4ad5-953f-3463b2e53e59 27 | EXT4 UUID: e27c657e-d03c-4f89-b36d-2de6880bc2a1 28 | 29 | ## xfs.img 30 | 31 | Limited to 12-char volume name 32 | 33 | UUID : 45e8a3bf-8114-400f-95b0-380d0fb7d42d 34 | LABEL: BLSFORME 35 | 36 | ## fat16.img.zst 37 | 38 | UUID : A1B2-C3D4 (volume id not a uuid) 39 | LABEL: TESTLABEL 40 | 41 | created with commands : 42 | 43 | dd if=/dev/zero of=fat16.img bs=512 count=32768 44 | mkfs.fat -F 16 -n "TESTLABEL" -i A1B2C3D4 fat16.img 45 | zstd fat16.img 46 | rm fat16.img 47 | 48 | ## fat32.img.zst 49 | 50 | UUID : A1B2-C3D4 (volume id not a uuid) 51 | LABEL: TESTLABEL 52 | 53 | created with commands : 54 | 55 | dd if=/dev/zero of=fat32.img bs=512 count=32768 56 | mkfs.fat -F 32 -n "TESTLABEL" -i A1B2C3D4 fat32.img 57 | zstd fat32.img 58 | rm fat32.img -------------------------------------------------------------------------------- /crates/superblock/tests/btrfs.img.zst: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AerynOS/disks-rs/7536726f0768ab34673e7b0306e528d290892423/crates/superblock/tests/btrfs.img.zst -------------------------------------------------------------------------------- /crates/superblock/tests/ext4.img.zst: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AerynOS/disks-rs/7536726f0768ab34673e7b0306e528d290892423/crates/superblock/tests/ext4.img.zst -------------------------------------------------------------------------------- /crates/superblock/tests/f2fs.img.zst: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AerynOS/disks-rs/7536726f0768ab34673e7b0306e528d290892423/crates/superblock/tests/f2fs.img.zst -------------------------------------------------------------------------------- /crates/superblock/tests/fat16.img: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AerynOS/disks-rs/7536726f0768ab34673e7b0306e528d290892423/crates/superblock/tests/fat16.img -------------------------------------------------------------------------------- /crates/superblock/tests/fat16.img.zst: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AerynOS/disks-rs/7536726f0768ab34673e7b0306e528d290892423/crates/superblock/tests/fat16.img.zst -------------------------------------------------------------------------------- /crates/superblock/tests/fat32.img: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AerynOS/disks-rs/7536726f0768ab34673e7b0306e528d290892423/crates/superblock/tests/fat32.img -------------------------------------------------------------------------------- /crates/superblock/tests/fat32.img.zst: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AerynOS/disks-rs/7536726f0768ab34673e7b0306e528d290892423/crates/superblock/tests/fat32.img.zst -------------------------------------------------------------------------------- /crates/superblock/tests/luks+ext4.img.zst: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AerynOS/disks-rs/7536726f0768ab34673e7b0306e528d290892423/crates/superblock/tests/luks+ext4.img.zst -------------------------------------------------------------------------------- /crates/superblock/tests/xfs.img.zst: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AerynOS/disks-rs/7536726f0768ab34673e7b0306e528d290892423/crates/superblock/tests/xfs.img.zst -------------------------------------------------------------------------------- /crates/types/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "types" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | [dependencies] 7 | kdl = { workspace = true, optional = true } 8 | thiserror.workspace = true 9 | miette = { workspace = true, optional = true } 10 | gpt.workspace = true 11 | uuid.workspace = true 12 | 13 | [features] 14 | kdl = ["dep:kdl", "dep:miette"] 15 | -------------------------------------------------------------------------------- /crates/types/src/constraints.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: Copyright © 2025 AerynOS Developers 2 | // 3 | // SPDX-License-Identifier: MPL-2.0 4 | 5 | #[cfg(feature = "kdl")] 6 | use crate::{get_kdl_entry, kdl_value_to_storage_size}; 7 | 8 | /// Constraints for partition size, 1:1 mapping to SizeRequirements in 9 | /// partitioning strategy internals. 10 | #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] 11 | pub enum Constraints { 12 | /// Exact size in bytes 13 | Exact(u64), 14 | /// Minimum size in bytes, using more if available 15 | AtLeast(u64), 16 | /// Between min and max bytes 17 | Range { min: u64, max: u64 }, 18 | /// Use all remaining space 19 | Remaining, 20 | 21 | /// Default constraints 22 | #[default] 23 | Invalid, 24 | } 25 | 26 | #[cfg(feature = "kdl")] 27 | impl Constraints { 28 | pub fn from_kdl_node(node: &kdl::KdlNode) -> Result { 29 | let range = node 30 | .iter_children() 31 | .find(|n| n.name().value() == "min") 32 | .zip(node.iter_children().find(|n| n.name().value() == "max")); 33 | 34 | if let Some((min, max)) = range { 35 | let min = kdl_value_to_storage_size(get_kdl_entry(min, &0)?)? as u64; 36 | let max = kdl_value_to_storage_size(get_kdl_entry(max, &0)?)? as u64; 37 | 38 | Ok(Self::Range { 39 | min: min as u64, 40 | max: max as u64, 41 | }) 42 | } else if let Some(min) = node.iter_children().find(|n| n.name().value() == "min") { 43 | let min = kdl_value_to_storage_size(get_kdl_entry(min, &0)?)? as u64; 44 | Ok(Self::AtLeast(min as u64)) 45 | } else if let Some(exact) = node.iter_children().find(|n| n.name().value() == "exactly") { 46 | let exact = kdl_value_to_storage_size(get_kdl_entry(exact, &0)?)? as u64; 47 | Ok(Self::Exact(exact as u64)) 48 | } else if node.iter_children().any(|n| n.name().value() == "remaining") { 49 | Ok(Self::Remaining) 50 | } else { 51 | Err(crate::Error::MissingProperty(crate::MissingProperty { 52 | at: node.span(), 53 | id: "min, max, exactly or remaining", 54 | advice: Some("add one of these properties".into()), 55 | })) 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /crates/types/src/errors.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: Copyright © 2025 Serpent OS Developers 2 | // 3 | // SPDX-License-Identifier: MPL-2.0 4 | 5 | use std::io; 6 | 7 | #[cfg(feature = "kdl")] 8 | use miette::{Diagnostic, NamedSource, SourceSpan}; 9 | #[cfg(feature = "kdl")] 10 | use std::sync::Arc; 11 | use thiserror::Error; 12 | 13 | #[cfg(feature = "kdl")] 14 | use crate::KdlType; 15 | 16 | /// Error type for the provisioning crate 17 | #[cfg_attr(feature = "kdl", derive(Diagnostic))] 18 | #[derive(Debug, Error)] 19 | pub enum Error { 20 | #[error(transparent)] 21 | IO(#[from] io::Error), 22 | 23 | #[cfg(feature = "kdl")] 24 | #[diagnostic(transparent)] 25 | #[error(transparent)] 26 | Kdl(#[from] kdl::KdlError), 27 | 28 | #[cfg(feature = "kdl")] 29 | #[error("unknown type")] 30 | UnknownType, 31 | 32 | #[error("unknown variant")] 33 | UnknownVariant, 34 | 35 | #[cfg(feature = "kdl")] 36 | #[diagnostic(transparent)] 37 | #[error(transparent)] 38 | InvalidArguments(#[from] InvalidArguments), 39 | 40 | #[cfg(feature = "kdl")] 41 | #[diagnostic(transparent)] 42 | #[error(transparent)] 43 | InvalidType(#[from] InvalidType), 44 | 45 | #[cfg(feature = "kdl")] 46 | #[diagnostic(transparent)] 47 | #[error(transparent)] 48 | UnsupportedNode(#[from] UnsupportedNode), 49 | 50 | #[cfg(feature = "kdl")] 51 | #[diagnostic(transparent)] 52 | #[error(transparent)] 53 | MissingEntry(#[from] MissingEntry), 54 | 55 | #[cfg(feature = "kdl")] 56 | #[error("missing node: {0}")] 57 | MissingNode(&'static str), 58 | 59 | #[cfg(feature = "kdl")] 60 | #[diagnostic(transparent)] 61 | #[error(transparent)] 62 | MissingProperty(#[from] MissingProperty), 63 | 64 | #[cfg(feature = "kdl")] 65 | #[diagnostic(transparent)] 66 | #[error(transparent)] 67 | UnsupportedValue(#[from] UnsupportedValue), 68 | } 69 | 70 | #[cfg(feature = "kdl")] 71 | /// Merged error for parsing failures 72 | /// Returns a list of diagnostics for the user 73 | #[derive(Debug, Diagnostic, Error)] 74 | #[error("failed to parse KDL")] 75 | #[diagnostic(severity(error))] 76 | pub struct ParseError { 77 | #[source_code] 78 | pub src: NamedSource>, 79 | #[related] 80 | pub diagnostics: Vec, 81 | } 82 | 83 | #[cfg(feature = "kdl")] 84 | /// Error for invalid types 85 | #[derive(Debug, Diagnostic, Error)] 86 | #[error("invalid type, expected {expected_type}")] 87 | #[diagnostic(severity(error))] 88 | pub struct InvalidType { 89 | #[label] 90 | pub at: SourceSpan, 91 | 92 | /// The expected type 93 | pub expected_type: KdlType, 94 | } 95 | 96 | #[cfg(feature = "kdl")] 97 | /// Error for missing mandatory properties 98 | #[derive(Debug, Diagnostic, Error)] 99 | #[error("missing property: {id}")] 100 | #[diagnostic(severity(error))] 101 | pub struct MissingProperty { 102 | #[label] 103 | pub at: SourceSpan, 104 | 105 | pub id: &'static str, 106 | 107 | #[help] 108 | pub advice: Option, 109 | } 110 | 111 | #[cfg(feature = "kdl")] 112 | /// Error for missing mandatory properties 113 | #[derive(Debug, Diagnostic, Error)] 114 | #[error("missing entry: {id}")] 115 | #[diagnostic(severity(error))] 116 | pub struct MissingEntry { 117 | #[label] 118 | pub at: SourceSpan, 119 | 120 | pub id: String, 121 | 122 | #[help] 123 | pub advice: Option, 124 | } 125 | 126 | #[cfg(feature = "kdl")] 127 | /// Error for unsupported node types 128 | #[derive(Debug, Diagnostic, Error)] 129 | #[error("unsupported node: {name}")] 130 | #[diagnostic(severity(error))] 131 | pub struct UnsupportedNode { 132 | #[label] 133 | pub at: SourceSpan, 134 | 135 | pub name: String, 136 | } 137 | 138 | #[cfg(feature = "kdl")] 139 | /// Error for unsupported values 140 | #[derive(Debug, Diagnostic, Error)] 141 | #[error("unsupported value")] 142 | #[diagnostic(severity(error))] 143 | pub struct UnsupportedValue { 144 | #[label] 145 | pub at: SourceSpan, 146 | 147 | #[help] 148 | pub advice: Option, 149 | } 150 | 151 | #[cfg(feature = "kdl")] 152 | /// Error for invalid arguments 153 | #[derive(Debug, Diagnostic, Error)] 154 | #[error("invalid arguments")] 155 | #[diagnostic(severity(error))] 156 | pub struct InvalidArguments { 157 | #[label] 158 | pub at: SourceSpan, 159 | 160 | #[help] 161 | pub advice: Option, 162 | } 163 | 164 | #[cfg(feature = "kdl")] 165 | /// Error for missing types 166 | #[derive(Debug, Diagnostic, Error)] 167 | #[error("missing type")] 168 | #[diagnostic(severity(error))] 169 | pub struct MissingType { 170 | #[label] 171 | pub at: SourceSpan, 172 | 173 | #[help] 174 | pub advice: Option, 175 | } 176 | -------------------------------------------------------------------------------- /crates/types/src/filesystem.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: Copyright © 2025 Serpent OS Developers 2 | // SPDX-FileCopyrightText: Copyright © 2025 AerynOS Developers 3 | // 4 | // SPDX-License-Identifier: MPL-2.0 5 | 6 | use std::{fmt, str::FromStr}; 7 | 8 | #[cfg(feature = "kdl")] 9 | use crate::{get_kdl_entry, kdl_value_to_integer, kdl_value_to_string}; 10 | 11 | #[cfg(feature = "kdl")] 12 | use super::FromKdlProperty; 13 | 14 | /// The filesystem information for a partition 15 | /// This is used to format the partition with a filesystem 16 | #[derive(Debug, Clone, PartialEq)] 17 | pub enum Filesystem { 18 | Fat32 { 19 | label: Option, 20 | volume_id: Option, 21 | }, 22 | Standard { 23 | filesystem_type: StandardFilesystemType, 24 | label: Option, 25 | uuid: Option, 26 | }, 27 | } 28 | 29 | #[derive(Debug, Clone, PartialEq)] 30 | pub enum StandardFilesystemType { 31 | F2fs, 32 | Ext4, 33 | Xfs, 34 | Swap, 35 | } 36 | 37 | impl fmt::Display for StandardFilesystemType { 38 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 39 | match self { 40 | Self::Ext4 => f.write_str("ext4"), 41 | Self::F2fs => f.write_str("f2fs"), 42 | Self::Xfs => f.write_str("xfs"), 43 | Self::Swap => f.write_str("swap"), 44 | } 45 | } 46 | } 47 | 48 | impl FromStr for StandardFilesystemType { 49 | type Err = crate::Error; 50 | 51 | fn from_str(value: &str) -> Result { 52 | match value { 53 | "ext4" => Ok(Self::Ext4), 54 | "f2fs" => Ok(Self::F2fs), 55 | "xfs" => Ok(Self::Xfs), 56 | "swap" => Ok(Self::Swap), 57 | _ => Err(crate::Error::UnknownVariant), 58 | } 59 | } 60 | } 61 | 62 | #[cfg(feature = "kdl")] 63 | impl FromKdlProperty<'_> for StandardFilesystemType { 64 | fn from_kdl_property(entry: &kdl::KdlEntry) -> Result { 65 | let value = kdl_value_to_string(entry)?; 66 | let v = value.parse().map_err(|_| crate::UnsupportedValue { 67 | at: entry.span(), 68 | advice: Some("'fat32', 'ext4', 'f2fs', 'xfs' 'swap' are supported".into()), 69 | })?; 70 | Ok(v) 71 | } 72 | } 73 | 74 | #[cfg(feature = "kdl")] 75 | impl Filesystem { 76 | pub fn from_kdl_node(node: &kdl::KdlNode) -> Result { 77 | let mut fs_type = None; 78 | let mut label = None; 79 | let mut uuid = None; 80 | let mut volume_id = None; 81 | 82 | for entry in node.iter_children() { 83 | match entry.name().value() { 84 | "type" => fs_type = Some(kdl_value_to_string(get_kdl_entry(entry, &0)?)?), 85 | "label" => label = Some(kdl_value_to_string(get_kdl_entry(entry, &0)?)?), 86 | "uuid" => uuid = Some(kdl_value_to_string(get_kdl_entry(entry, &0)?)?), 87 | "volume_id" => volume_id = Some(kdl_value_to_integer(get_kdl_entry(entry, &0)?)? as u32), 88 | _ => { 89 | return Err(crate::UnsupportedNode { 90 | at: entry.span(), 91 | name: entry.name().value().into(), 92 | } 93 | .into()) 94 | } 95 | } 96 | } 97 | 98 | let fs_type = fs_type.ok_or(crate::UnsupportedNode { 99 | at: node.span(), 100 | name: "type".into(), 101 | })?; 102 | 103 | match fs_type.as_str() { 104 | "fat32" => { 105 | if uuid.is_some() { 106 | return Err(crate::InvalidArguments { 107 | at: node.span(), 108 | advice: Some("FAT32 does not support UUID".into()), 109 | } 110 | .into()); 111 | } 112 | Ok(Filesystem::Fat32 { label, volume_id }) 113 | } 114 | fs_type => { 115 | if volume_id.is_some() { 116 | return Err(crate::InvalidArguments { 117 | at: node.span(), 118 | advice: Some(format!("volume_id is only supported for FAT32, not {fs_type}")), 119 | } 120 | .into()); 121 | } 122 | Ok(Filesystem::Standard { 123 | filesystem_type: fs_type.parse()?, 124 | label, 125 | uuid, 126 | }) 127 | } 128 | } 129 | } 130 | } 131 | -------------------------------------------------------------------------------- /crates/types/src/kdl_helpers.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: Copyright © 2025 Serpent OS Developers 2 | // 3 | // SPDX-License-Identifier: MPL-2.0 4 | 5 | use std::fmt; 6 | 7 | use crate::{Error, InvalidType, MissingEntry, MissingProperty, StorageUnit}; 8 | use kdl::{KdlEntry, KdlNode, KdlValue, NodeKey}; 9 | 10 | /// The type of a KDL value 11 | #[derive(Debug)] 12 | pub enum KdlType { 13 | /// A boolean value 14 | Boolean, 15 | /// A string value 16 | String, 17 | /// A null value 18 | Null, 19 | /// An integer value 20 | Integer, 21 | } 22 | 23 | impl KdlType { 24 | // Determine the kdl value type 25 | pub fn for_value(value: &KdlValue) -> Result { 26 | if value.is_bool() { 27 | Ok(Self::Boolean) 28 | } else if value.is_string() { 29 | Ok(Self::String) 30 | } else if value.is_null() { 31 | Ok(Self::Null) 32 | } else if value.is_integer() { 33 | Ok(Self::Integer) 34 | } else { 35 | Err(Error::UnknownType) 36 | } 37 | } 38 | } 39 | 40 | impl fmt::Display for KdlType { 41 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 42 | match self { 43 | KdlType::Boolean => f.write_str("boolean"), 44 | KdlType::String => f.write_str("string"), 45 | KdlType::Null => f.write_str("null"), 46 | KdlType::Integer => f.write_str("int"), 47 | } 48 | } 49 | } 50 | 51 | pub trait FromKdlProperty<'a>: Sized { 52 | fn from_kdl_property(entry: &'a KdlEntry) -> Result; 53 | } 54 | 55 | pub trait FromKdlType<'a>: Sized { 56 | fn from_kdl_type(id: &'a KdlEntry) -> Result; 57 | } 58 | 59 | // Get a property from a node 60 | pub fn get_kdl_property<'a>(node: &'a KdlNode, name: &'static str) -> Result<&'a KdlEntry, Error> { 61 | let entry = node.entry(name).ok_or_else(|| MissingProperty { 62 | at: node.span(), 63 | id: name, 64 | advice: Some(format!("add `{name}=...` to bind the property")), 65 | })?; 66 | 67 | Ok(entry) 68 | } 69 | 70 | pub fn get_kdl_entry<'a, T>(node: &'a KdlNode, id: &'a T) -> Result<&'a KdlEntry, Error> 71 | where 72 | T: Into + ToString + Clone, 73 | { 74 | let entry = node.entry(id.clone()).ok_or_else(|| MissingEntry { 75 | at: node.span(), 76 | id: id.to_string(), 77 | advice: None, 78 | })?; 79 | 80 | Ok(entry) 81 | } 82 | 83 | // Get a string property from a value 84 | pub fn kdl_value_to_string(entry: &kdl::KdlEntry) -> Result { 85 | let value = entry.value().as_string().ok_or(InvalidType { 86 | at: entry.span(), 87 | expected_type: KdlType::String, 88 | })?; 89 | 90 | Ok(value.to_owned()) 91 | } 92 | 93 | // Get an integer property from a value 94 | pub fn kdl_value_to_integer(entry: &kdl::KdlEntry) -> Result { 95 | let value = entry.value().as_integer().ok_or(InvalidType { 96 | at: entry.span(), 97 | expected_type: KdlType::Integer, 98 | })?; 99 | 100 | Ok(value) 101 | } 102 | 103 | // Convert a KDL value to a storage size 104 | pub fn kdl_value_to_storage_size(entry: &kdl::KdlEntry) -> Result { 105 | let value = kdl_value_to_integer(entry)?; 106 | let units = StorageUnit::from_kdl_type(entry)?; 107 | Ok(value as u64 * units as u64) 108 | } 109 | 110 | // Get a string property from a node 111 | pub fn get_property_str(node: &KdlNode, name: &'static str) -> Result { 112 | let value = get_kdl_property(node, name).and_then(kdl_value_to_string)?; 113 | Ok(value.to_owned()) 114 | } 115 | -------------------------------------------------------------------------------- /crates/types/src/lib.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: Copyright © 2025 Serpent OS Developers 2 | // SPDX-FileCopyrightText: Copyright © 2025 AerynOS Developers 3 | // 4 | // SPDX-License-Identifier: MPL-2.0 5 | 6 | #[cfg(feature = "kdl")] 7 | mod kdl_helpers; 8 | #[cfg(feature = "kdl")] 9 | pub use kdl_helpers::*; 10 | mod errors; 11 | pub use errors::*; 12 | 13 | pub use gpt; 14 | 15 | mod partition_table; 16 | pub use partition_table::*; 17 | mod partition_role; 18 | pub use partition_role::*; 19 | 20 | mod units; 21 | pub use units::*; 22 | pub mod constraints; 23 | pub use constraints::*; 24 | pub mod filesystem; 25 | pub use filesystem::*; 26 | mod partition_type; 27 | pub use partition_type::*; 28 | -------------------------------------------------------------------------------- /crates/types/src/partition_role.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: Copyright © 2025 Serpent OS Developers 2 | // SPDX-FileCopyrightText: Copyright © 2025 AerynOS Developers 3 | // 4 | // SPDX-License-Identifier: MPL-2.0 5 | 6 | use std::{fmt, str::FromStr}; 7 | 8 | #[cfg(feature = "kdl")] 9 | use crate::kdl_value_to_string; 10 | 11 | #[cfg(feature = "kdl")] 12 | use super::FromKdlProperty; 13 | 14 | /// The role assigned to a partition 15 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] 16 | pub enum PartitionRole { 17 | /// Boot partition (usually ESP) 18 | Boot, 19 | 20 | /// Extended boot partition (e.g. XBOOTLDR) 21 | ExtendedBoot, 22 | 23 | /// Root filesystem 24 | Root, 25 | 26 | /// Home directory mount 27 | Home, 28 | 29 | /// Swap partition 30 | Swap, 31 | } 32 | 33 | impl PartitionRole { 34 | pub fn as_path(&self) -> &'static str { 35 | match self { 36 | Self::Boot => "/efi", 37 | Self::ExtendedBoot => "/boot", 38 | Self::Root => "/", 39 | Self::Home => "/home", 40 | Self::Swap => "swap", 41 | } 42 | } 43 | } 44 | 45 | impl fmt::Display for PartitionRole { 46 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 47 | match self { 48 | Self::Boot => f.write_str("boot"), 49 | Self::ExtendedBoot => f.write_str("extended-boot"), 50 | Self::Root => f.write_str("root"), 51 | Self::Home => f.write_str("home"), 52 | Self::Swap => f.write_str("swap"), 53 | } 54 | } 55 | } 56 | 57 | impl FromStr for PartitionRole { 58 | type Err = crate::Error; 59 | 60 | /// Attempt to convert a string to a partition role 61 | fn from_str(value: &str) -> Result { 62 | match value { 63 | "boot" => Ok(Self::Boot), 64 | "extended-boot" => Ok(Self::ExtendedBoot), 65 | "root" => Ok(Self::Root), 66 | "home" => Ok(Self::Home), 67 | "swap" => Ok(Self::Swap), 68 | _ => Err(crate::Error::UnknownVariant), 69 | } 70 | } 71 | } 72 | 73 | #[cfg(feature = "kdl")] 74 | impl FromKdlProperty<'_> for PartitionRole { 75 | fn from_kdl_property(entry: &kdl::KdlEntry) -> Result { 76 | let value = kdl_value_to_string(entry)?; 77 | let v = value.parse().map_err(|_| crate::UnsupportedValue { 78 | at: entry.span(), 79 | advice: Some("'boot', 'extended-boot', 'root', 'home' and 'swap' are supported".into()), 80 | })?; 81 | Ok(v) 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /crates/types/src/partition_table.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: Copyright © 2025 Serpent OS Developers 2 | // SPDX-FileCopyrightText: Copyright © 2025 AerynOS Developers 3 | // 4 | // SPDX-License-Identifier: MPL-2.0 5 | 6 | use std::{fmt, str::FromStr}; 7 | 8 | #[cfg(feature = "kdl")] 9 | use super::FromKdlProperty; 10 | #[cfg(feature = "kdl")] 11 | use crate::kdl_value_to_string; 12 | 13 | /// The type of partition table to create 14 | #[derive(Debug, PartialEq)] 15 | pub enum PartitionTableType { 16 | /// GUID Partition Table 17 | Gpt, 18 | 19 | /// Master Boot Record 20 | Msdos, 21 | } 22 | 23 | impl fmt::Display for PartitionTableType { 24 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 25 | match self { 26 | Self::Gpt => f.write_str("gpt"), 27 | Self::Msdos => f.write_str("msdos"), 28 | } 29 | } 30 | } 31 | 32 | impl FromStr for PartitionTableType { 33 | type Err = crate::Error; 34 | 35 | /// Attempt to convert a string to a partition table type 36 | fn from_str(value: &str) -> Result { 37 | match value { 38 | "gpt" => Ok(Self::Gpt), 39 | "msdos" => Ok(Self::Msdos), 40 | _ => Err(crate::Error::UnknownVariant), 41 | } 42 | } 43 | } 44 | 45 | #[cfg(feature = "kdl")] 46 | impl FromKdlProperty<'_> for PartitionTableType { 47 | fn from_kdl_property(entry: &kdl::KdlEntry) -> Result { 48 | let value = kdl_value_to_string(entry)?; 49 | let v = value.parse().map_err(|_| crate::UnsupportedValue { 50 | at: entry.span(), 51 | advice: Some("'gpt' and 'msdos' are supported".into()), 52 | })?; 53 | Ok(v) 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /crates/types/src/partition_type.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: Copyright © 2025 Serpent OS Developers 2 | // SPDX-FileCopyrightText: Copyright © 2025 AerynOS Developers 3 | // 4 | // SPDX-License-Identifier: MPL-2.0 5 | 6 | use std::{fmt, str::FromStr}; 7 | 8 | pub use gpt::partition_types::Type as GptPartitionType; 9 | pub use uuid::Uuid; 10 | 11 | #[cfg(feature = "kdl")] 12 | use crate::{get_kdl_entry, kdl_value_to_string, UnsupportedValue}; 13 | 14 | #[cfg(feature = "kdl")] 15 | use super::FromKdlType; 16 | 17 | #[cfg(feature = "kdl")] 18 | pub enum PartitionTypeKDL { 19 | GUID, 20 | } 21 | 22 | #[cfg(feature = "kdl")] 23 | impl FromStr for PartitionTypeKDL { 24 | type Err = crate::Error; 25 | 26 | fn from_str(value: &str) -> Result { 27 | match value { 28 | "guid" => Ok(Self::GUID), 29 | _ => Err(crate::Error::UnknownVariant), 30 | } 31 | } 32 | } 33 | 34 | #[cfg(feature = "kdl")] 35 | impl fmt::Display for PartitionTypeKDL { 36 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 37 | match self { 38 | Self::GUID => f.write_str("guid"), 39 | } 40 | } 41 | } 42 | 43 | #[cfg(feature = "kdl")] 44 | impl<'a> FromKdlType<'a> for PartitionTypeKDL { 45 | fn from_kdl_type(id: &'a kdl::KdlEntry) -> Result { 46 | let ty_id = if let Some(ty) = id.ty() { 47 | ty.value().to_lowercase() 48 | } else { 49 | "".into() 50 | }; 51 | 52 | let v = ty_id.parse().map_err(|_| UnsupportedValue { 53 | at: id.span(), 54 | advice: Some("only '(GUID)' type is supported".into()), 55 | })?; 56 | Ok(v) 57 | } 58 | } 59 | 60 | /// Represents GPT partition type GUIDs 61 | #[derive(Debug, PartialEq)] 62 | pub enum PartitionTypeGuid { 63 | EfiSystemPartition, 64 | ExtendedBootLoader, 65 | LinuxSwap, 66 | LinuxFilesystem, 67 | } 68 | 69 | impl fmt::Display for PartitionTypeGuid { 70 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 71 | match self { 72 | Self::EfiSystemPartition => f.write_str("EFI System Partition"), 73 | Self::ExtendedBootLoader => f.write_str("Linux Extended Boot"), 74 | Self::LinuxFilesystem => f.write_str("Linux Filesystem"), 75 | Self::LinuxSwap => f.write_str("Linux Swap"), 76 | } 77 | } 78 | } 79 | 80 | impl FromStr for PartitionTypeGuid { 81 | type Err = crate::Error; 82 | 83 | fn from_str(value: &str) -> Result { 84 | match value { 85 | "efi-system-partition" => Ok(Self::EfiSystemPartition), 86 | "linux-extended-boot" => Ok(Self::ExtendedBootLoader), 87 | "linux-swap" => Ok(Self::LinuxSwap), 88 | "linux-fs" => Ok(Self::LinuxFilesystem), 89 | _ => Err(crate::Error::UnknownVariant), 90 | } 91 | } 92 | } 93 | 94 | impl PartitionTypeGuid { 95 | /// Returns the GUID value for this partition type 96 | pub fn as_guid(&self) -> GptPartitionType { 97 | match self { 98 | Self::EfiSystemPartition => gpt::partition_types::EFI, 99 | Self::ExtendedBootLoader => gpt::partition_types::FREEDESK_BOOT, 100 | Self::LinuxSwap => gpt::partition_types::LINUX_SWAP, 101 | Self::LinuxFilesystem => gpt::partition_types::LINUX_FS, 102 | } 103 | } 104 | 105 | #[cfg(feature = "kdl")] 106 | pub fn from_kdl_node(node: &kdl::KdlNode) -> Result { 107 | let value = kdl_value_to_string(get_kdl_entry(node, &0)?)?; 108 | let v = value.parse().map_err(|_| crate::UnsupportedValue { 109 | at: node.span(), 110 | advice: Some( 111 | "'efi-system-partition', 'linux-swap' 'linux-extended-boot' and 'linux-fs' are supported".into(), 112 | ), 113 | })?; 114 | Ok(v) 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /crates/types/src/units.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: Copyright © 2025 Serpent OS Developers 2 | // 3 | // SPDX-License-Identifier: MPL-2.0 4 | 5 | use std::{fmt, str::FromStr}; 6 | 7 | #[cfg(feature = "kdl")] 8 | use crate::UnsupportedValue; 9 | 10 | #[cfg(feature = "kdl")] 11 | use super::FromKdlType; 12 | 13 | /// Storage unit 14 | #[derive(Default, Debug, Clone, Copy, PartialEq, Eq)] 15 | #[repr(u64)] 16 | pub enum StorageUnit { 17 | /// Bytes 18 | #[default] 19 | Bytes = 1, 20 | 21 | // as 1000s, 22 | /// Kilobytes 23 | Kilobytes = 1000, 24 | /// Megabytes 25 | Megabytes = 1_000_000, 26 | /// Gigabytes 27 | Gigabytes = 1_000_000_000, 28 | /// Terabytes 29 | Terabytes = 1_000_000_000_000, 30 | 31 | // as 1024s, 32 | /// Kibibytes 33 | Kibibytes = 1024, 34 | /// Mebibytes 35 | Mebibytes = 1024 * 1024, 36 | /// Gibibytes 37 | Gibibytes = 1024 * 1024 * 1024, 38 | /// Tebibytes 39 | Tebibytes = 1024 * 1024 * 1024 * 1024, 40 | } 41 | 42 | impl fmt::Display for StorageUnit { 43 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 44 | match self { 45 | StorageUnit::Bytes => f.write_str("bytes"), 46 | StorageUnit::Kilobytes => f.write_str("kilobytes"), 47 | StorageUnit::Megabytes => f.write_str("megabytes"), 48 | StorageUnit::Gigabytes => f.write_str("gigabytes"), 49 | StorageUnit::Terabytes => f.write_str("terabytes"), 50 | StorageUnit::Kibibytes => f.write_str("kibibytes"), 51 | StorageUnit::Mebibytes => f.write_str("mebibytes"), 52 | StorageUnit::Gibibytes => f.write_str("gibibytes"), 53 | StorageUnit::Tebibytes => f.write_str("tebibytes"), 54 | } 55 | } 56 | } 57 | 58 | impl FromStr for StorageUnit { 59 | type Err = crate::Error; 60 | 61 | /// Attempt to convert a string to a storage unit 62 | fn from_str(value: &str) -> Result { 63 | match value { 64 | "b" => Ok(Self::Bytes), 65 | "kb" => Ok(Self::Kilobytes), 66 | "mb" => Ok(Self::Megabytes), 67 | "gb" => Ok(Self::Gigabytes), 68 | "tb" => Ok(Self::Terabytes), 69 | "kib" => Ok(Self::Kibibytes), 70 | "mib" => Ok(Self::Mebibytes), 71 | "gib" => Ok(Self::Gibibytes), 72 | "tib" => Ok(Self::Tebibytes), 73 | _ => Err(crate::Error::UnknownVariant), 74 | } 75 | } 76 | } 77 | 78 | #[cfg(feature = "kdl")] 79 | impl FromKdlType<'_> for StorageUnit { 80 | fn from_kdl_type(id: &kdl::KdlEntry) -> Result { 81 | let ty_id = if let Some(ty) = id.ty() { 82 | ty.value().to_lowercase() 83 | } else { 84 | "b".into() 85 | }; 86 | 87 | let v = ty_id.parse().map_err(|_| UnsupportedValue { 88 | at: id.span(), 89 | advice: Some("'b', 'kb', 'mb', 'gb', 'tb', 'kib', 'mib', 'gib', 'tib' are supported".into()), 90 | })?; 91 | Ok(v) 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- 1 | edition = "2021" 2 | max_width = 120 3 | --------------------------------------------------------------------------------