├── .github └── workflows │ └── test.yml ├── .gitignore ├── Cargo.lock ├── Cargo.toml ├── LICENSE.Apache-2.0.txt ├── LICENSE.MIT.txt ├── README.md ├── fuzz.py ├── src ├── iter_blocks.rs └── main.rs └── test.py /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Test 2 | 3 | on: 4 | - push 5 | - pull_request 6 | 7 | jobs: 8 | build: 9 | strategy: 10 | matrix: 11 | rust-version: [1.60.0, stable, nightly] 12 | fail-fast: false 13 | runs-on: ubuntu-latest 14 | steps: 15 | - uses: actions/checkout@v2 16 | - name: Set up Rust ${{ matrix.rust-version }} 17 | uses: actions-rs/toolchain@v1 18 | id: rustup 19 | with: 20 | toolchain: ${{ matrix.rust-version }} 21 | override: true 22 | - uses: actions/setup-python@v2 23 | with: 24 | python-version: "3.10" 25 | - name: Install fuse 26 | run: sudo apt-get install libfuse3-dev 27 | - name: Build 28 | run: | 29 | LOCK_SHA256=$(shasum -a 256 Cargo.lock) 30 | cargo build --verbose 31 | if [ $LOCK_SHA256 != $(shasum -a 256 Cargo.lock)]; then exit 1; fi 32 | - name: Run unit tests 33 | run: cargo test --verbose 34 | - name: Run integration test 35 | run: python3 test.py 36 | - name: Run fuzz test 37 | run: python3 fuzz.py 38 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | .project 3 | .idea 4 | .*.swp 5 | \#*# 6 | .DS_Store 7 | desktop.ini 8 | *.tar 9 | *.tar.gz 10 | *.tar.bz2 11 | *.zip 12 | -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 3 4 | 5 | [[package]] 6 | name = "atty" 7 | version = "0.2.14" 8 | source = "registry+https://github.com/rust-lang/crates.io-index" 9 | checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" 10 | dependencies = [ 11 | "hermit-abi", 12 | "libc", 13 | "winapi", 14 | ] 15 | 16 | [[package]] 17 | name = "autocfg" 18 | version = "1.1.0" 19 | source = "registry+https://github.com/rust-lang/crates.io-index" 20 | checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" 21 | 22 | [[package]] 23 | name = "bitflags" 24 | version = "1.3.2" 25 | source = "registry+https://github.com/rust-lang/crates.io-index" 26 | checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" 27 | 28 | [[package]] 29 | name = "byteorder" 30 | version = "1.4.3" 31 | source = "registry+https://github.com/rust-lang/crates.io-index" 32 | checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610" 33 | 34 | [[package]] 35 | name = "cfg-if" 36 | version = "1.0.0" 37 | source = "registry+https://github.com/rust-lang/crates.io-index" 38 | checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" 39 | 40 | [[package]] 41 | name = "clap" 42 | version = "3.2.21" 43 | source = "registry+https://github.com/rust-lang/crates.io-index" 44 | checksum = "1ed5341b2301a26ab80be5cbdced622e80ed808483c52e45e3310a877d3b37d7" 45 | dependencies = [ 46 | "atty", 47 | "bitflags", 48 | "clap_lex", 49 | "indexmap", 50 | "strsim", 51 | "termcolor", 52 | "textwrap", 53 | ] 54 | 55 | [[package]] 56 | name = "clap_lex" 57 | version = "0.2.4" 58 | source = "registry+https://github.com/rust-lang/crates.io-index" 59 | checksum = "2850f2f5a82cbf437dd5af4d49848fbdfc27c157c3d010345776f952765261c5" 60 | dependencies = [ 61 | "os_str_bytes", 62 | ] 63 | 64 | [[package]] 65 | name = "cowblock" 66 | version = "2.0.0" 67 | dependencies = [ 68 | "clap", 69 | "fuser", 70 | "libc", 71 | "tempfile", 72 | ] 73 | 74 | [[package]] 75 | name = "fastrand" 76 | version = "1.8.0" 77 | source = "registry+https://github.com/rust-lang/crates.io-index" 78 | checksum = "a7a407cfaa3385c4ae6b23e84623d48c2798d06e3e6a1878f7f59f17b3f86499" 79 | dependencies = [ 80 | "instant", 81 | ] 82 | 83 | [[package]] 84 | name = "fuser" 85 | version = "0.11.1" 86 | source = "registry+https://github.com/rust-lang/crates.io-index" 87 | checksum = "104ed58f182bc2975062cd3fab229e82b5762de420e26cf5645f661402694599" 88 | dependencies = [ 89 | "libc", 90 | "log", 91 | "memchr", 92 | "page_size", 93 | "pkg-config", 94 | "smallvec", 95 | "users", 96 | "zerocopy", 97 | ] 98 | 99 | [[package]] 100 | name = "hashbrown" 101 | version = "0.12.3" 102 | source = "registry+https://github.com/rust-lang/crates.io-index" 103 | checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" 104 | 105 | [[package]] 106 | name = "hermit-abi" 107 | version = "0.1.19" 108 | source = "registry+https://github.com/rust-lang/crates.io-index" 109 | checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33" 110 | dependencies = [ 111 | "libc", 112 | ] 113 | 114 | [[package]] 115 | name = "indexmap" 116 | version = "1.9.1" 117 | source = "registry+https://github.com/rust-lang/crates.io-index" 118 | checksum = "10a35a97730320ffe8e2d410b5d3b69279b98d2c14bdb8b70ea89ecf7888d41e" 119 | dependencies = [ 120 | "autocfg", 121 | "hashbrown", 122 | ] 123 | 124 | [[package]] 125 | name = "instant" 126 | version = "0.1.12" 127 | source = "registry+https://github.com/rust-lang/crates.io-index" 128 | checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c" 129 | dependencies = [ 130 | "cfg-if", 131 | ] 132 | 133 | [[package]] 134 | name = "libc" 135 | version = "0.2.132" 136 | source = "registry+https://github.com/rust-lang/crates.io-index" 137 | checksum = "8371e4e5341c3a96db127eb2465ac681ced4c433e01dd0e938adbef26ba93ba5" 138 | 139 | [[package]] 140 | name = "log" 141 | version = "0.4.17" 142 | source = "registry+https://github.com/rust-lang/crates.io-index" 143 | checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e" 144 | dependencies = [ 145 | "cfg-if", 146 | ] 147 | 148 | [[package]] 149 | name = "memchr" 150 | version = "2.5.0" 151 | source = "registry+https://github.com/rust-lang/crates.io-index" 152 | checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" 153 | 154 | [[package]] 155 | name = "os_str_bytes" 156 | version = "6.3.0" 157 | source = "registry+https://github.com/rust-lang/crates.io-index" 158 | checksum = "9ff7415e9ae3fff1225851df9e0d9e4e5479f947619774677a63572e55e80eff" 159 | 160 | [[package]] 161 | name = "page_size" 162 | version = "0.4.2" 163 | source = "registry+https://github.com/rust-lang/crates.io-index" 164 | checksum = "eebde548fbbf1ea81a99b128872779c437752fb99f217c45245e1a61dcd9edcd" 165 | dependencies = [ 166 | "libc", 167 | "winapi", 168 | ] 169 | 170 | [[package]] 171 | name = "pkg-config" 172 | version = "0.3.25" 173 | source = "registry+https://github.com/rust-lang/crates.io-index" 174 | checksum = "1df8c4ec4b0627e53bdf214615ad287367e482558cf84b109250b37464dc03ae" 175 | 176 | [[package]] 177 | name = "proc-macro2" 178 | version = "1.0.43" 179 | source = "registry+https://github.com/rust-lang/crates.io-index" 180 | checksum = "0a2ca2c61bc9f3d74d2886294ab7b9853abd9c1ad903a3ac7815c58989bb7bab" 181 | dependencies = [ 182 | "unicode-ident", 183 | ] 184 | 185 | [[package]] 186 | name = "quote" 187 | version = "1.0.21" 188 | source = "registry+https://github.com/rust-lang/crates.io-index" 189 | checksum = "bbe448f377a7d6961e30f5955f9b8d106c3f5e449d493ee1b125c1d43c2b5179" 190 | dependencies = [ 191 | "proc-macro2", 192 | ] 193 | 194 | [[package]] 195 | name = "redox_syscall" 196 | version = "0.2.16" 197 | source = "registry+https://github.com/rust-lang/crates.io-index" 198 | checksum = "fb5a58c1855b4b6819d59012155603f0b22ad30cad752600aadfcb695265519a" 199 | dependencies = [ 200 | "bitflags", 201 | ] 202 | 203 | [[package]] 204 | name = "remove_dir_all" 205 | version = "0.5.3" 206 | source = "registry+https://github.com/rust-lang/crates.io-index" 207 | checksum = "3acd125665422973a33ac9d3dd2df85edad0f4ae9b00dafb1a05e43a9f5ef8e7" 208 | dependencies = [ 209 | "winapi", 210 | ] 211 | 212 | [[package]] 213 | name = "smallvec" 214 | version = "1.9.0" 215 | source = "registry+https://github.com/rust-lang/crates.io-index" 216 | checksum = "2fd0db749597d91ff862fd1d55ea87f7855a744a8425a64695b6fca237d1dad1" 217 | 218 | [[package]] 219 | name = "strsim" 220 | version = "0.10.0" 221 | source = "registry+https://github.com/rust-lang/crates.io-index" 222 | checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" 223 | 224 | [[package]] 225 | name = "syn" 226 | version = "1.0.99" 227 | source = "registry+https://github.com/rust-lang/crates.io-index" 228 | checksum = "58dbef6ec655055e20b86b15a8cc6d439cca19b667537ac6a1369572d151ab13" 229 | dependencies = [ 230 | "proc-macro2", 231 | "quote", 232 | "unicode-ident", 233 | ] 234 | 235 | [[package]] 236 | name = "synstructure" 237 | version = "0.12.6" 238 | source = "registry+https://github.com/rust-lang/crates.io-index" 239 | checksum = "f36bdaa60a83aca3921b5259d5400cbf5e90fc51931376a9bd4a0eb79aa7210f" 240 | dependencies = [ 241 | "proc-macro2", 242 | "quote", 243 | "syn", 244 | "unicode-xid", 245 | ] 246 | 247 | [[package]] 248 | name = "tempfile" 249 | version = "3.3.0" 250 | source = "registry+https://github.com/rust-lang/crates.io-index" 251 | checksum = "5cdb1ef4eaeeaddc8fbd371e5017057064af0911902ef36b39801f67cc6d79e4" 252 | dependencies = [ 253 | "cfg-if", 254 | "fastrand", 255 | "libc", 256 | "redox_syscall", 257 | "remove_dir_all", 258 | "winapi", 259 | ] 260 | 261 | [[package]] 262 | name = "termcolor" 263 | version = "1.1.3" 264 | source = "registry+https://github.com/rust-lang/crates.io-index" 265 | checksum = "bab24d30b911b2376f3a13cc2cd443142f0c81dda04c118693e35b3835757755" 266 | dependencies = [ 267 | "winapi-util", 268 | ] 269 | 270 | [[package]] 271 | name = "textwrap" 272 | version = "0.15.0" 273 | source = "registry+https://github.com/rust-lang/crates.io-index" 274 | checksum = "b1141d4d61095b28419e22cb0bbf02755f5e54e0526f97f1e3d1d160e60885fb" 275 | 276 | [[package]] 277 | name = "unicode-ident" 278 | version = "1.0.3" 279 | source = "registry+https://github.com/rust-lang/crates.io-index" 280 | checksum = "c4f5b37a154999a8f3f98cc23a628d850e154479cd94decf3414696e12e31aaf" 281 | 282 | [[package]] 283 | name = "unicode-xid" 284 | version = "0.2.3" 285 | source = "registry+https://github.com/rust-lang/crates.io-index" 286 | checksum = "957e51f3646910546462e67d5f7599b9e4fb8acdd304b087a6494730f9eebf04" 287 | 288 | [[package]] 289 | name = "users" 290 | version = "0.11.0" 291 | source = "registry+https://github.com/rust-lang/crates.io-index" 292 | checksum = "24cc0f6d6f267b73e5a2cadf007ba8f9bc39c6a6f9666f8cf25ea809a153b032" 293 | dependencies = [ 294 | "libc", 295 | "log", 296 | ] 297 | 298 | [[package]] 299 | name = "winapi" 300 | version = "0.3.9" 301 | source = "registry+https://github.com/rust-lang/crates.io-index" 302 | checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" 303 | dependencies = [ 304 | "winapi-i686-pc-windows-gnu", 305 | "winapi-x86_64-pc-windows-gnu", 306 | ] 307 | 308 | [[package]] 309 | name = "winapi-i686-pc-windows-gnu" 310 | version = "0.4.0" 311 | source = "registry+https://github.com/rust-lang/crates.io-index" 312 | checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" 313 | 314 | [[package]] 315 | name = "winapi-util" 316 | version = "0.1.5" 317 | source = "registry+https://github.com/rust-lang/crates.io-index" 318 | checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178" 319 | dependencies = [ 320 | "winapi", 321 | ] 322 | 323 | [[package]] 324 | name = "winapi-x86_64-pc-windows-gnu" 325 | version = "0.4.0" 326 | source = "registry+https://github.com/rust-lang/crates.io-index" 327 | checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" 328 | 329 | [[package]] 330 | name = "zerocopy" 331 | version = "0.6.1" 332 | source = "registry+https://github.com/rust-lang/crates.io-index" 333 | checksum = "332f188cc1bcf1fe1064b8c58d150f497e697f49774aa846f2dc949d9a25f236" 334 | dependencies = [ 335 | "byteorder", 336 | "zerocopy-derive", 337 | ] 338 | 339 | [[package]] 340 | name = "zerocopy-derive" 341 | version = "0.3.1" 342 | source = "registry+https://github.com/rust-lang/crates.io-index" 343 | checksum = "a0fbc82b82efe24da867ee52e015e58178684bd9dd64c34e66bdf21da2582a9f" 344 | dependencies = [ 345 | "proc-macro2", 346 | "syn", 347 | "synstructure", 348 | ] 349 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "cowblock" 3 | version = "2.0.0" 4 | edition = "2018" 5 | rust-version = "1.60" 6 | description = "Block-level copy-on-write tool" 7 | repository = "https://github.com/remram44/cowblock" 8 | readme = "README.md" 9 | license = "MIT OR Apache-2.0" 10 | 11 | [dependencies] 12 | clap = "3.1" 13 | fuser = "0.11" 14 | libc = "0.2" 15 | 16 | [dev-dependencies] 17 | tempfile = "3.3" 18 | -------------------------------------------------------------------------------- /LICENSE.Apache-2.0.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE.MIT.txt: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Remi Rampin 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Block-Level Copy-on-Write 2 | ========================= 3 | 4 | What is this? 5 | ------------- 6 | 7 | This is a little tool allowing you to make changes to a big file without affecting the original, and without making an entire copy either. 8 | 9 | It is implemented as a filesystem in userspace that keeps track of changes to the blocks of a file. 10 | 11 | For example, if you have a big database or virtual hard drive and you want to make changes but keep the original; you can use this tool to create a copy of the file: 12 | 13 | ``` 14 | $ touch virtual_copy.db 15 | $ cowblock original.db virtual_copy.db & 16 | $ sqlite3 virtual_copy.db 17 | # Make changes here 18 | # The changes are visible in virtual_copy.db, 19 | # but no change is made to original.db 20 | # The changed blocks are stored in virtual_copy.db-diff and virtual_copy.db-extra, 21 | # which are much smaller files 22 | $ fusermount -u virtual_copy.db 23 | ``` 24 | 25 | Why? 26 | ---- 27 | 28 | There are options for copy-on-write filesystems, however they are quite limited: 29 | 30 | * Tools like unionfs-fuse, aufs, and overlayfs do copy-on-write for filesystems, but copy whole files when you need to write to them. There is no way to copy part of a big file without makine a copy of it. 31 | * Filesystems like btrfs or zfs offer copy-on-write (with `cp --reflink`), but you need to be using that filesystem to benefit from it. 32 | * You can abuse devicemapper to do this but it is pretty difficult (and you'll get devices rather than regular files) 33 | 34 | How? 35 | ---- 36 | 37 | The diff file contains an index at the start, indicating where the blocks of the file can be found in the diff. Blocks that haven't been overwritten yet are 0, while other numbers are the index of the block in the diff file. 38 | 39 | The index is checked before every block read to determine whether we should read from the original or the diff. 40 | -------------------------------------------------------------------------------- /fuzz.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import os 4 | import random 5 | import struct 6 | import subprocess 7 | import time 8 | 9 | 10 | # Make test data 11 | def make_data(size, seed): 12 | rand = random.Random(seed) 13 | return bytes(rand.randint(0, 255) for _ in range(size)) 14 | 15 | 16 | def hexstring(data): 17 | lines = [] 18 | for i in range(0, len(data), 16): 19 | s = data[i:i + 16] 20 | lines.append(' '.join('%02X' % b for b in s)) 21 | return '\n'.join(lines) 22 | 23 | 24 | def do_test(seed): 25 | print("\ndo_test(seed=%d)" % seed, flush=True) 26 | 27 | # Make data array 28 | rand = random.Random(seed) 29 | init_data_size = rand.randint(30, 600) 30 | data = make_data( 31 | init_data_size, 32 | rand.randint(0, (1 << 32) - 1), 33 | ) 34 | 35 | print('> make_data(%d)' % len(data), flush=True) 36 | 37 | # Make test input file 38 | with open('input.bin', 'wb') as fp: 39 | fp.write(data) 40 | assert os.path.getsize('input.bin') == len(data) 41 | 42 | # Remove diff and extra files 43 | try: 44 | os.remove('cow-diff') 45 | except FileNotFoundError: 46 | pass 47 | try: 48 | os.remove('cow-extra') 49 | except FileNotFoundError: 50 | pass 51 | 52 | try: 53 | # Mount 54 | with open('cow', 'wb'): 55 | pass 56 | mount_proc = subprocess.Popen(['target/debug/cowblock', 'input.bin', 'cow', '--block-size', '64']) 57 | time.sleep(2) 58 | assert mount_proc.returncode is None 59 | 60 | for _ in range(100): 61 | if os.path.getsize('cow') != len(data): 62 | raise AssertionError("Invalid file size: %d != %d" % (os.path.getsize('cow'), len(data))) 63 | 64 | # Do random write 65 | with open('cow', 'r+b') as fp: 66 | # Only 10% chance to write over the end of the file 67 | in_bounds = rand.random() > 0.10 68 | if in_bounds: 69 | pos = rand.randint(0, len(data)) 70 | else: 71 | pos = rand.randint(0, len(data) + 200) 72 | 73 | # Random buffer 74 | buf = make_data( 75 | rand.randint(0, 300), 76 | rand.randint(0, (1 << 32) - 1), 77 | ) 78 | 79 | print('> write(%d, %d)' % (pos, len(buf)), flush=True) 80 | if pos + len(buf) > len(data): 81 | print('(new size %d)' % (pos + len(buf)), flush=True) 82 | 83 | # Do the write 84 | if pos > len(data): 85 | data = data + bytes([0] * (pos - len(data))) 86 | data = data[:pos] + buf + data[pos + len(buf):] 87 | fp.seek(pos, 0) 88 | res = fp.write(buf) 89 | 90 | if res != len(buf): 91 | raise AssertionError("Partial write: %d != %d" % (res, len(buf))) 92 | 93 | # Check extra file 94 | with open('cow-extra', 'rb') as fp: 95 | extra = fp.read() 96 | if extra != data[init_data_size - (init_data_size % 64):]: 97 | raise AssertionError("Invalid extra file content:\n%s\n !=\n%s" % (hexstring(extra), hexstring(data[init_data_size - (init_data_size % 100):]))) 98 | del extra 99 | 100 | # Check diff file 101 | with open('cow-diff', 'rb') as fp: 102 | diff = fp.read() 103 | for block in range(init_data_size // 64): 104 | num, = struct.unpack('>L', diff[block * 4:block * 4 + 4]) 105 | if num != 0: 106 | pos = (num - 1) * 64 107 | pos += (init_data_size // 64) * 4 108 | block_data = diff[pos:pos + 64] 109 | if block_data != data[block * 64:block * 64 + 64]: 110 | raise AssertionError("Invalid diff block %d:\n%s\n !=\n%s" % (block, hexstring(block_data), hexstring(data[block * 64:block * 64 + 64]))) 111 | del diff 112 | 113 | # Do random read 114 | with open('cow', 'rb') as fp: 115 | pos = max(0, pos - rand.randint(0, 300)) 116 | # Only 10% chance to request more than the total length of the file 117 | in_bounds = rand.random() > 0.10 118 | if in_bounds: 119 | size = rand.randint(pos, len(data) - 1) - pos 120 | else: 121 | size = rand.randint(pos, len(data) + 200) - pos 122 | 123 | print('> read(%d, %d)' % (pos, size), flush=True) 124 | 125 | # Do the read 126 | fp.seek(pos, 0) 127 | buf = fp.read(size) 128 | 129 | if len(buf) != size: 130 | print('(read %d)' % len(buf), flush=True) 131 | 132 | # Check it 133 | if buf != data[pos:pos + size]: 134 | raise AssertionError("Invalid read:\n%s\n !=\n%s" % (hexstring(buf), hexstring(data[pos:pos + size]))) 135 | finally: 136 | mount_proc.terminate() 137 | mount_proc.wait() 138 | subprocess.call(['fusermount', '-u', 'cow']) 139 | 140 | for filename in ('input.bin', 'cow-diff', 'cow-extra'): 141 | try: 142 | os.remove(filename) 143 | except FileNotFoundError: 144 | pass 145 | 146 | for i in range(20): 147 | do_test(i) 148 | -------------------------------------------------------------------------------- /src/iter_blocks.rs: -------------------------------------------------------------------------------- 1 | pub fn iter_blocks(block_size: u64, start: u64, size: u64) -> IterBlocks { 2 | IterBlocks { 3 | block_size, 4 | start, 5 | end: start + size, 6 | offset: 0, 7 | } 8 | } 9 | 10 | pub struct IterBlocks { 11 | block_size: u64, 12 | start: u64, 13 | end: u64, 14 | offset: u64, 15 | } 16 | 17 | impl IterBlocks { 18 | pub fn next(&mut self) -> Option { 19 | if self.start >= self.end { 20 | return None; 21 | } 22 | 23 | let block_num = self.start / self.block_size; 24 | let end = self.end.min((block_num + 1) * self.block_size); 25 | let block = Block { 26 | start: self.start, 27 | end, 28 | offset: self.offset, 29 | block_size: self.block_size, 30 | }; 31 | self.offset += end - self.start; 32 | self.start = end; 33 | Some(block) 34 | } 35 | } 36 | 37 | #[derive(Debug, PartialEq, Eq, Clone, Copy)] 38 | pub struct Block { 39 | pub start: u64, 40 | pub end: u64, 41 | pub offset: u64, 42 | pub block_size: u64, 43 | } 44 | 45 | impl Block { 46 | pub fn size(&self) -> u64 { 47 | self.end - self.start 48 | } 49 | 50 | pub fn num(&self) -> u64 { 51 | self.start / self.block_size 52 | } 53 | } 54 | 55 | #[test] 56 | fn test_blocks() { 57 | fn collect(mut iterator: IterBlocks) -> Vec { 58 | let mut result = Vec::new(); 59 | while let Some(block) = iterator.next() { 60 | result.push(block); 61 | } 62 | assert!(iterator.next().is_none()); 63 | result 64 | } 65 | 66 | assert_eq!( 67 | collect(iter_blocks(10, 4, 4)), 68 | vec![ 69 | Block { start: 4, end: 8, offset: 0, block_size: 10 }, 70 | ], 71 | ); 72 | assert_eq!( 73 | collect(iter_blocks(10, 24, 26)), 74 | vec![ 75 | Block { start: 24, end: 30, offset: 0, block_size: 10 }, 76 | Block { start: 30, end: 40, offset: 6, block_size: 10 }, 77 | Block { start: 40, end: 50, offset: 16, block_size: 10 }, 78 | ], 79 | ); 80 | assert_eq!( 81 | collect(iter_blocks(10, 20, 26)), 82 | vec![ 83 | Block { start: 20, end: 30, offset: 0, block_size: 10 }, 84 | Block { start: 30, end: 40, offset: 10, block_size: 10 }, 85 | Block { start: 40, end: 46, offset: 20, block_size: 10 }, 86 | ], 87 | ); 88 | } 89 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | mod iter_blocks; 2 | 3 | use clap::{Arg, Command}; 4 | use fuser::{FileAttr, Filesystem, FileType, MountOption, Request, ReplyAttr, ReplyData, ReplyDirectory, ReplyEmpty, ReplyEntry, ReplyOpen, ReplyWrite}; 5 | use libc::{EINVAL, EIO, ENOENT}; 6 | use std::borrow::Cow; 7 | use std::env::args_os; 8 | use std::error::Error; 9 | use std::io::{Error as IoError, ErrorKind as IoErrorKind, Read, Seek, SeekFrom, Write}; 10 | use std::ffi::OsStr; 11 | use std::fs::{File, OpenOptions}; 12 | use std::path::{Path, PathBuf}; 13 | use std::time::UNIX_EPOCH; 14 | 15 | use iter_blocks::iter_blocks; 16 | 17 | fn main() { 18 | match main_r() { 19 | Ok(()) => {} 20 | Err(e) => { 21 | eprintln!("{}", e); 22 | std::process::exit(1); 23 | } 24 | } 25 | } 26 | 27 | fn path_with_suffix(path: &Path, suffix: &str) -> Result { 28 | let path = path.canonicalize()?; 29 | let mut filename = path.file_name().unwrap_or(OsStr::new("")).to_owned(); 30 | filename.push(suffix); 31 | Ok(path.with_file_name(filename)) 32 | } 33 | 34 | fn main_r() -> Result<(), Box> { 35 | // Read command line 36 | let mut cli = Command::new("cowblock") 37 | .bin_name("cowblock") 38 | .version(env!("CARGO_PKG_VERSION")) 39 | .author(env!("CARGO_PKG_AUTHORS")) 40 | .about(env!("CARGO_PKG_DESCRIPTION")) 41 | .arg( 42 | Arg::new("input") 43 | .help("Input file name") 44 | .required(true) 45 | .takes_value(true) 46 | .allow_invalid_utf8(true) 47 | ) 48 | .arg( 49 | Arg::new("mount") 50 | .help("Mount point (file)") 51 | .required(true) 52 | .takes_value(true) 53 | .allow_invalid_utf8(true) 54 | ) 55 | .arg( 56 | Arg::new("diff") 57 | .long("diff") 58 | .help("Diff file, storing the overwritten blocks") 59 | .takes_value(true) 60 | .allow_invalid_utf8(true) 61 | ) 62 | .arg( 63 | Arg::new("extra") 64 | .long("extra") 65 | .help("Extra file, storing the appended blocks") 66 | .takes_value(true) 67 | .allow_invalid_utf8(true) 68 | ) 69 | .arg( 70 | Arg::new("block-size") 71 | .long("block-size") 72 | .help("Size of the blocks of the diff file") 73 | .takes_value(true) 74 | .default_value("4096") 75 | ); 76 | let matches = cli.try_get_matches_from_mut(args_os())?; 77 | let input_path = Path::new(matches.value_of_os("input").unwrap()); 78 | let mount_path = Path::new(matches.value_of_os("mount").unwrap()); 79 | let diff_path = match matches.value_of_os("diff") { 80 | Some(name) => Cow::Borrowed(Path::new(name)), 81 | None => Cow::Owned(path_with_suffix(mount_path, "-diff")?), 82 | }; 83 | let extra_path = match matches.value_of_os("extra") { 84 | Some(name) => Cow::Borrowed(Path::new(name)), 85 | None => Cow::Owned(path_with_suffix(mount_path, "-extra")?), 86 | }; 87 | let block_size: u64 = matches.value_of("block-size").unwrap().parse()?; 88 | 89 | if block_size < 4 { 90 | return Err(IoError::new(IoErrorKind::InvalidInput, "Invalid block size").into()); 91 | } 92 | 93 | let options = vec![ 94 | MountOption::RW, 95 | MountOption::FSName("fuse-cow-block".to_owned()), 96 | MountOption::DefaultPermissions, 97 | ]; 98 | let filesystem = CowBlockFs::new(block_size, input_path, &diff_path, &extra_path)?; 99 | fuser::mount2(filesystem, mount_path, &options) 100 | .map_err(|e| Box::new(e) as Box) 101 | } 102 | 103 | fn getuid() -> u32 { 104 | unsafe { 105 | libc::getuid() 106 | } 107 | } 108 | 109 | fn getgid() -> u32 { 110 | unsafe { 111 | libc::getgid() 112 | } 113 | } 114 | 115 | struct CowBlockFs { 116 | block_size: u64, 117 | input: File, 118 | diff: File, 119 | extra: File, 120 | file_size: u64, 121 | nblocks: u64, 122 | nbytes: u64, 123 | } 124 | 125 | impl CowBlockFs { 126 | fn new(block_size: u64, input_path: &Path, diff_path: &Path, extra_path: &Path) -> Result { 127 | let mut input = OpenOptions::new().read(true).open(input_path)?; 128 | let input_file_size = input.seek(SeekFrom::End(0))?; 129 | let mut diff = OpenOptions::new().read(true).write(true).create(true).open(diff_path)?; 130 | let mut extra = OpenOptions::new().read(true).write(true).create(true).open(extra_path)?; 131 | 132 | // Measure the header, which is the index of the blocks 133 | let nblocks = input_file_size / block_size; 134 | println!( 135 | "Input file is {} bytes, that's {} full blocks of {} bytes", 136 | input_file_size, 137 | nblocks, 138 | block_size, 139 | ); 140 | let nbytes = if nblocks < 1 << 32 { 141 | 4 142 | } else { 143 | 8 144 | }; 145 | println!( 146 | "Using {}-byte offsets in header, total header size {} bytes", 147 | nbytes, 148 | nblocks * nbytes, 149 | ); 150 | 151 | if nblocks != 0 { 152 | let current_diff_len = diff.seek(SeekFrom::End(0))?; 153 | if current_diff_len == 0 { 154 | // Allocate space for the index 155 | diff.seek(SeekFrom::Start(nblocks * nbytes - 1))?; 156 | diff.write_all(b"\0")?; 157 | } else if current_diff_len < nblocks * nbytes { 158 | return Err(IoError::new(IoErrorKind::InvalidData, "Diff file exists but is too small")); 159 | } 160 | } 161 | 162 | let mut extra_file_size = extra.seek(SeekFrom::End(0))?; 163 | 164 | // If the input file contains a partial last block 165 | // (ie the size is not a multiple of the block size) 166 | if input_file_size % block_size != 0 && extra_file_size == 0 { 167 | // Copy last block to extra file 168 | let mut buf = vec![0u8; (input_file_size % block_size) as usize]; 169 | input.seek(SeekFrom::Start((input_file_size / block_size) * block_size))?; 170 | input.read_exact(&mut buf)?; 171 | extra.write_all(&buf)?; 172 | extra_file_size += buf.len() as u64; 173 | } 174 | let file_size = nblocks * block_size + extra_file_size; 175 | 176 | Ok(CowBlockFs { 177 | block_size, 178 | input, 179 | diff, 180 | extra, 181 | file_size, 182 | nblocks, 183 | nbytes, 184 | }) 185 | } 186 | 187 | fn file_attr(&self) -> FileAttr { 188 | FileAttr { 189 | ino: 1, 190 | size: self.file_size, 191 | blocks: (self.file_size - 1) / 512 + 1, 192 | atime: UNIX_EPOCH, 193 | mtime: UNIX_EPOCH, 194 | ctime: UNIX_EPOCH, 195 | crtime: UNIX_EPOCH, 196 | kind: FileType::RegularFile, 197 | perm: 0o755, 198 | nlink: 2, 199 | uid: getuid(), 200 | gid: getgid(), 201 | rdev: 0, 202 | flags: 0, 203 | blksize: 512, 204 | } 205 | } 206 | 207 | fn read_index(&mut self, block_num: u64) -> Result, IoError> { 208 | let diff_block_num = if self.nbytes == 4 { 209 | self.diff.seek(SeekFrom::Start(block_num * 4))?; 210 | let mut data = [0u8; 4]; 211 | self.diff.read_exact(&mut data)?; 212 | let data = 213 | (data[0] as u64) << 24 214 | | (data[1] as u64) << 16 215 | | (data[2] as u64) << 8 216 | | data[3] as u64; 217 | if data == 0 { 218 | return Ok(None); 219 | } else { 220 | data - 1 221 | } 222 | } else { 223 | self.diff.seek(SeekFrom::Start(block_num * 8))?; 224 | let mut data = [0u8; 8]; 225 | self.diff.read_exact(&mut data)?; 226 | let data = 227 | (data[0] as u64) << 56 228 | | (data[1] as u64) << 48 229 | | (data[2] as u64) << 40 230 | | (data[3] as u64) << 32 231 | | (data[4] as u64) << 24 232 | | (data[5] as u64) << 16 233 | | (data[6] as u64) << 8 234 | | data[7] as u64; 235 | if data == 0 { 236 | return Ok(None); 237 | } else { 238 | data - 1 239 | } 240 | }; 241 | let position = self.nbytes * self.nblocks + diff_block_num * self.block_size; 242 | Ok(Some(position)) 243 | } 244 | 245 | fn write_index(&mut self, block_num: u64, position: u64) -> Result<(), IoError> { 246 | if position < self.nbytes * self.nblocks 247 | || (position - self.nbytes * self.nblocks) % self.block_size != 0 248 | { 249 | return Err(IoError::new(IoErrorKind::InvalidData, "Diff block has invalid location")); 250 | } 251 | let diff_block_num = (position - self.nbytes * self.nblocks) / self.block_size; 252 | if self.nbytes == 4 { 253 | self.diff.seek(SeekFrom::Start(block_num * 4))?; 254 | let data = diff_block_num + 1; 255 | let data = [ 256 | (data >> 24) as u8, 257 | (data >> 16) as u8, 258 | (data >> 8) as u8, 259 | data as u8, 260 | ]; 261 | self.diff.write_all(&data) 262 | } else { 263 | self.diff.seek(SeekFrom::Start(block_num * 8))?; 264 | let data = diff_block_num + 1; 265 | let data = [ 266 | (data >> 56) as u8, 267 | (data >> 48) as u8, 268 | (data >> 40) as u8, 269 | (data >> 32) as u8, 270 | (data >> 24) as u8, 271 | (data >> 16) as u8, 272 | (data >> 8) as u8, 273 | data as u8, 274 | ]; 275 | self.diff.write_all(&data) 276 | } 277 | } 278 | 279 | fn do_read(&mut self, start: u64, size: u64) -> Result, IoError> { 280 | // Clamp read to file size 281 | let size = self.file_size.min(start + size) - start; 282 | 283 | let mut result = vec![0u8; size as usize]; 284 | let mut blocks = iter_blocks(self.block_size, start, size); 285 | while let Some(block) = blocks.next() { 286 | let result_slice = &mut result[ 287 | block.offset as usize 288 | .. 289 | (block.offset + block.size()) as usize 290 | ]; 291 | 292 | // Is this over the input file's length? 293 | if block.num() >= self.nblocks { 294 | // Read from extra file 295 | self.extra.seek(SeekFrom::Start(block.start - self.nblocks * self.block_size))?; 296 | self.extra.read_exact(result_slice)?; 297 | } else { 298 | // Has this block been overwritten? 299 | match self.read_index(block.num())? { 300 | None => { 301 | // No, read from input file 302 | self.input.seek(SeekFrom::Start(block.start))?; 303 | self.input.read_exact(result_slice)?; 304 | } 305 | Some(position) => { 306 | // Yes, read from diff file 307 | self.diff.seek(SeekFrom::Start(position))?; 308 | self.diff.read_exact(result_slice)?; 309 | } 310 | } 311 | } 312 | } 313 | 314 | Ok(result) 315 | } 316 | 317 | fn do_write(&mut self, start: u64, data: &[u8]) -> Result { 318 | let mut blocks = iter_blocks(self.block_size, start, data.len() as u64); 319 | while let Some(block) = blocks.next() { 320 | // Is this over the input file's length? 321 | if block.num() >= self.nblocks { 322 | // Write to extra file 323 | if block.start > self.file_size { 324 | self.extra.seek(SeekFrom::End(0))?; 325 | self.extra.write_all(&vec![0u8; (block.start - self.file_size) as usize])?; 326 | self.file_size = block.start; 327 | } else { 328 | self.extra.seek(SeekFrom::Start(block.start - self.nblocks * self.block_size))?; 329 | } 330 | // As an optimization, write all the remaining blocks and stop, 331 | // rather than continuing to write the blocks one-by-one 332 | self.extra.write_all(&data[block.offset as usize..])?; 333 | self.file_size = self.file_size.max(block.start + data.len() as u64 - block.offset); 334 | break; 335 | } else { 336 | // Has this block been overwritten? 337 | match self.read_index(block.num())? { 338 | Some(position) => { 339 | // Yes, just write to diff file 340 | self.diff.seek(SeekFrom::Start(position + block.start % self.block_size))?; 341 | self.diff.write_all(&data[block.offset as usize..block.offset as usize + block.size() as usize])?; 342 | } 343 | None => { 344 | // No 345 | // Allocate a block in diff file 346 | let position = self.diff.seek(SeekFrom::End(0))?; 347 | self.write_index(block.num(), position)?; 348 | 349 | // Are we writing a whole block? 350 | if block.size() == self.block_size { 351 | // Yes, just do it 352 | self.diff.seek(SeekFrom::Start(position))?; 353 | self.diff.write(&data[block.offset as usize..block.offset as usize + block.size() as usize])?; 354 | } else { 355 | // No, read the rest of the block from input file 356 | let mut buf = vec![0u8; self.block_size as usize]; 357 | self.input.seek(SeekFrom::Start(block.num() * self.block_size))?; 358 | self.input.read_exact(&mut buf)?; 359 | 360 | // Put the new data in it 361 | buf[(block.start - block.num() * self.block_size) as usize..(block.end - block.num() * self.block_size) as usize].clone_from_slice(&data[block.offset as usize..(block.offset + block.size()) as usize]); 362 | 363 | // Write it to diff file 364 | self.diff.seek(SeekFrom::Start(position))?; 365 | self.diff.write_all(&buf)?; 366 | } 367 | } 368 | } 369 | } 370 | } 371 | 372 | Ok(data.len() as u32) 373 | } 374 | } 375 | 376 | const ZERO: std::time::Duration = std::time::Duration::ZERO; 377 | 378 | impl Filesystem for CowBlockFs { 379 | fn lookup(&mut self, _req: &Request, _parent: u64, _name: &OsStr, reply: ReplyEntry) { 380 | reply.error(ENOENT); 381 | } 382 | 383 | fn readlink(&mut self, _req: &Request, ino: u64, reply: ReplyData) { 384 | match ino { 385 | 1 => reply.error(EINVAL), 386 | _ => reply.error(ENOENT), 387 | } 388 | } 389 | 390 | fn getattr(&mut self, _req: &Request, ino: u64, reply: ReplyAttr) { 391 | match ino { 392 | 1 => reply.attr(&ZERO, &self.file_attr()), 393 | _ => reply.error(ENOENT), 394 | } 395 | } 396 | 397 | fn open(&mut self, _req: &Request, _ino: u64, _flags: i32, reply: ReplyOpen) { 398 | reply.opened(0, 0); 399 | } 400 | 401 | fn opendir(&mut self, _req: &Request<'_>, _ino: u64, _flags: i32, reply: ReplyOpen) { 402 | reply.opened(0, 0); 403 | } 404 | 405 | fn readdir( 406 | &mut self, 407 | _req: &Request<'_>, 408 | _ino: u64, 409 | _fh: u64, 410 | _offset: i64, 411 | reply: ReplyDirectory, 412 | ) { 413 | reply.error(ENOENT); 414 | } 415 | 416 | fn read(&mut self, _req: &Request, ino: u64, _fh: u64, offset: i64, size: u32, _flags: i32, _lock_owner: Option, reply: ReplyData) { 417 | if ino != 1 { 418 | reply.error(ENOENT); 419 | return; 420 | } 421 | 422 | let offset = offset as u64; 423 | let size = size as u64; 424 | match self.do_read(offset as u64, size as u64) { 425 | Ok(result) => reply.data(&result), 426 | Err(e) => { 427 | eprintln!("Read error: {}", e); 428 | reply.error(EIO); 429 | } 430 | } 431 | } 432 | 433 | fn write(&mut self, _req: &Request, ino: u64, _fh: u64, offset: i64, data: &[u8], _write_flags: u32, _flags: i32, _lock_owner: Option, reply: ReplyWrite) { 434 | if ino != 1 { 435 | reply.error(ENOENT); 436 | return; 437 | } 438 | 439 | match self.do_write(offset as u64, data) { 440 | Ok(bytes) => reply.written(bytes), 441 | Err(e) => { 442 | eprintln!("Write error: {}", e); 443 | reply.error(EIO); 444 | } 445 | } 446 | } 447 | 448 | fn flush(&mut self, _req: &Request, ino: u64, _fh: u64, _lock_owner: u64, reply: ReplyEmpty) { 449 | if ino != 1 { 450 | reply.error(ENOENT); 451 | return; 452 | } 453 | if let Err(e) = self.diff.sync_all() { 454 | eprintln!("Flush error: {}", e); 455 | reply.error(e.raw_os_error().unwrap_or(EIO)); 456 | } else { 457 | reply.ok(); 458 | } 459 | } 460 | 461 | fn fsync(&mut self, _req: &Request, ino: u64, _fh: u64, datasync: bool, reply: ReplyEmpty) { 462 | if ino != 1 { 463 | reply.error(ENOENT); 464 | return; 465 | } 466 | let res = if datasync { 467 | self.diff.sync_data() 468 | } else { 469 | self.diff.sync_all() 470 | }; 471 | if let Err(e) = res { 472 | eprintln!("Fsync error: {}", e); 473 | reply.error(e.raw_os_error().unwrap_or(EIO)); 474 | } else { 475 | reply.ok(); 476 | } 477 | } 478 | } 479 | -------------------------------------------------------------------------------- /test.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import os 4 | import subprocess 5 | import time 6 | 7 | 8 | # Make test input file 9 | with open('input.bin', 'wb') as fp: 10 | for i in range(0, 4096 * 12, 256): 11 | fp.write(bytes(range(256))) 12 | fp.write(bytes(range(128))) 13 | assert os.path.getsize('input.bin') == 4096 * 12 + 128 14 | 15 | 16 | # Remove diff and extra files 17 | try: 18 | os.remove('cow-diff') 19 | except FileNotFoundError: 20 | pass 21 | try: 22 | os.remove('cow-extra') 23 | except FileNotFoundError: 24 | pass 25 | 26 | 27 | try: 28 | # Mount 29 | with open('cow', 'w'): 30 | pass 31 | mount_proc = subprocess.Popen(['target/debug/cowblock', 'input.bin', 'cow']) 32 | time.sleep(2) 33 | assert mount_proc.returncode is None 34 | 35 | assert os.path.getsize('cow') == 4096 * 12 + 128, os.path.getsize('cow') 36 | 37 | # Do some reads 38 | with open('cow', 'rb') as fp: 39 | print('> read(4084, 24)', flush=True) 40 | fp.seek(4096 - 12, 0) 41 | data = fp.read(24) 42 | assert data == bytes(range(244, 256)) + bytes(range(0, 12)), data 43 | 44 | print('> read(4091, 4106)', flush=True) 45 | fp.seek(4096 - 5, 0) 46 | data = fp.read(4096 + 10) 47 | assert data[0:10] == b'\xFB\xFC\xFD\xFE\xFF\x00\x01\x02\x03\x04' 48 | assert data == bytes(range(251, 256)) + bytes(range(256)) * 16 + bytes(range(0, 5)) 49 | 50 | # Do some writes 51 | with open('cow', 'r+b') as fp: 52 | print('> write(3000, 3)', flush=True) 53 | fp.seek(3000, 0) 54 | fp.write(b'aaa') 55 | fp.flush() 56 | 57 | print('> write(4092, 4)', flush=True) 58 | fp.seek(4096 - 4) 59 | fp.write(b'cccccccc') 60 | fp.flush() 61 | 62 | print('> write(49150, 4)', flush=True) 63 | fp.seek(4096 * 12 - 2) 64 | fp.write(b'dddd') 65 | fp.flush() 66 | assert os.path.getsize('cow') == 4096 * 12 + 128 67 | 68 | print('> write(49276, 8)', flush=True) 69 | fp.seek(4096 * 12 + 128 - 4) 70 | fp.write(b'eeeeeeee') 71 | fp.flush() 72 | assert os.path.getsize('cow') == 4096 * 12 + 128 + 4 73 | 74 | # Read again 75 | with open('cow', 'rb') as fp: 76 | print('> read(2999, 5)', flush=True) 77 | fp.seek(2999, 0) 78 | data = fp.read(5) 79 | assert data == b'\xB7aaa\xBB', data 80 | 81 | print('> read(4091, 10)', flush=True) 82 | fp.seek(4096 - 5, 0) 83 | data = fp.read(10) 84 | assert data == b'\xFBcccccccc\x04', data 85 | 86 | print('> read(49149, 6)', flush=True) 87 | fp.seek(4096 * 12 - 3) 88 | data = fp.read(6) 89 | assert data == b'\xFDdddd\x02', data 90 | 91 | print('> read(49274, 10)', flush=True) 92 | fp.seek(4096 * 12 + 128 - 6) 93 | data = fp.read(12) 94 | assert data == b'\x7A\x7Beeeeeeee', data 95 | finally: 96 | mount_proc.terminate() 97 | mount_proc.wait() 98 | subprocess.call(['fusermount', '-u', 'cow']) 99 | --------------------------------------------------------------------------------