├── .gitignore ├── Cargo.lock ├── Cargo.toml ├── LICENSE.txt ├── README.md ├── init.sql ├── misc ├── implement.md └── plan.md ├── src ├── db_module.rs ├── db_module │ └── sqlite.rs ├── filesystem.rs ├── lib.rs ├── main.rs └── sqerror.rs └── tests ├── filesystem.rs ├── helpers └── mod.rs └── sqlite.rs /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | 4 | *.sqlite 5 | *.sqlite3 6 | *.db 7 | .idea/ 8 | -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 4 4 | 5 | [[package]] 6 | name = "addr2line" 7 | version = "0.24.2" 8 | source = "registry+https://github.com/rust-lang/crates.io-index" 9 | checksum = "dfbe277e56a376000877090da837660b4427aad530e3028d44e0bffe4f89a1c1" 10 | dependencies = [ 11 | "gimli", 12 | ] 13 | 14 | [[package]] 15 | name = "adler2" 16 | version = "2.0.0" 17 | source = "registry+https://github.com/rust-lang/crates.io-index" 18 | checksum = "512761e0bb2578dd7380c6baaa0f4ce03e84f95e960231d1dec8bf4d7d6e2627" 19 | 20 | [[package]] 21 | name = "aho-corasick" 22 | version = "1.1.3" 23 | source = "registry+https://github.com/rust-lang/crates.io-index" 24 | checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916" 25 | dependencies = [ 26 | "memchr", 27 | ] 28 | 29 | [[package]] 30 | name = "android-tzdata" 31 | version = "0.1.1" 32 | source = "registry+https://github.com/rust-lang/crates.io-index" 33 | checksum = "e999941b234f3131b00bc13c22d06e8c5ff726d1b6318ac7eb276997bbb4fef0" 34 | 35 | [[package]] 36 | name = "android_system_properties" 37 | version = "0.1.5" 38 | source = "registry+https://github.com/rust-lang/crates.io-index" 39 | checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" 40 | dependencies = [ 41 | "libc", 42 | ] 43 | 44 | [[package]] 45 | name = "anstream" 46 | version = "0.6.18" 47 | source = "registry+https://github.com/rust-lang/crates.io-index" 48 | checksum = "8acc5369981196006228e28809f761875c0327210a891e941f4c683b3a99529b" 49 | dependencies = [ 50 | "anstyle", 51 | "anstyle-parse", 52 | "anstyle-query", 53 | "anstyle-wincon", 54 | "colorchoice", 55 | "is_terminal_polyfill", 56 | "utf8parse", 57 | ] 58 | 59 | [[package]] 60 | name = "anstyle" 61 | version = "1.0.10" 62 | source = "registry+https://github.com/rust-lang/crates.io-index" 63 | checksum = "55cc3b69f167a1ef2e161439aa98aed94e6028e5f9a59be9a6ffb47aef1651f9" 64 | 65 | [[package]] 66 | name = "anstyle-parse" 67 | version = "0.2.6" 68 | source = "registry+https://github.com/rust-lang/crates.io-index" 69 | checksum = "3b2d16507662817a6a20a9ea92df6652ee4f94f914589377d69f3b21bc5798a9" 70 | dependencies = [ 71 | "utf8parse", 72 | ] 73 | 74 | [[package]] 75 | name = "anstyle-query" 76 | version = "1.1.2" 77 | source = "registry+https://github.com/rust-lang/crates.io-index" 78 | checksum = "79947af37f4177cfead1110013d678905c37501914fba0efea834c3fe9a8d60c" 79 | dependencies = [ 80 | "windows-sys", 81 | ] 82 | 83 | [[package]] 84 | name = "anstyle-wincon" 85 | version = "3.0.6" 86 | source = "registry+https://github.com/rust-lang/crates.io-index" 87 | checksum = "2109dbce0e72be3ec00bed26e6a7479ca384ad226efdd66db8fa2e3a38c83125" 88 | dependencies = [ 89 | "anstyle", 90 | "windows-sys", 91 | ] 92 | 93 | [[package]] 94 | name = "atty" 95 | version = "0.2.14" 96 | source = "registry+https://github.com/rust-lang/crates.io-index" 97 | checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" 98 | dependencies = [ 99 | "hermit-abi", 100 | "libc", 101 | "winapi", 102 | ] 103 | 104 | [[package]] 105 | name = "autocfg" 106 | version = "1.4.0" 107 | source = "registry+https://github.com/rust-lang/crates.io-index" 108 | checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26" 109 | 110 | [[package]] 111 | name = "backtrace" 112 | version = "0.3.74" 113 | source = "registry+https://github.com/rust-lang/crates.io-index" 114 | checksum = "8d82cb332cdfaed17ae235a638438ac4d4839913cc2af585c3c6746e8f8bee1a" 115 | dependencies = [ 116 | "addr2line", 117 | "cfg-if", 118 | "libc", 119 | "miniz_oxide", 120 | "object", 121 | "rustc-demangle", 122 | "windows-targets", 123 | ] 124 | 125 | [[package]] 126 | name = "bitflags" 127 | version = "1.3.2" 128 | source = "registry+https://github.com/rust-lang/crates.io-index" 129 | checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" 130 | 131 | [[package]] 132 | name = "bitflags" 133 | version = "2.7.0" 134 | source = "registry+https://github.com/rust-lang/crates.io-index" 135 | checksum = "1be3f42a67d6d345ecd59f675f3f012d6974981560836e938c22b424b85ce1be" 136 | 137 | [[package]] 138 | name = "bumpalo" 139 | version = "3.16.0" 140 | source = "registry+https://github.com/rust-lang/crates.io-index" 141 | checksum = "79296716171880943b8470b5f8d03aa55eb2e645a4874bdbb28adb49162e012c" 142 | 143 | [[package]] 144 | name = "cc" 145 | version = "1.2.8" 146 | source = "registry+https://github.com/rust-lang/crates.io-index" 147 | checksum = "ad0cf6e91fde44c773c6ee7ec6bba798504641a8bc2eb7e37a04ffbf4dfaa55a" 148 | dependencies = [ 149 | "shlex", 150 | ] 151 | 152 | [[package]] 153 | name = "cfg-if" 154 | version = "1.0.0" 155 | source = "registry+https://github.com/rust-lang/crates.io-index" 156 | checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" 157 | 158 | [[package]] 159 | name = "cfg_aliases" 160 | version = "0.2.1" 161 | source = "registry+https://github.com/rust-lang/crates.io-index" 162 | checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" 163 | 164 | [[package]] 165 | name = "chrono" 166 | version = "0.4.39" 167 | source = "registry+https://github.com/rust-lang/crates.io-index" 168 | checksum = "7e36cc9d416881d2e24f9a963be5fb1cd90966419ac844274161d10488b3e825" 169 | dependencies = [ 170 | "android-tzdata", 171 | "iana-time-zone", 172 | "js-sys", 173 | "num-traits", 174 | "wasm-bindgen", 175 | "windows-targets", 176 | ] 177 | 178 | [[package]] 179 | name = "clap" 180 | version = "4.5.26" 181 | source = "registry+https://github.com/rust-lang/crates.io-index" 182 | checksum = "a8eb5e908ef3a6efbe1ed62520fb7287959888c88485abe072543190ecc66783" 183 | dependencies = [ 184 | "clap_builder", 185 | ] 186 | 187 | [[package]] 188 | name = "clap_builder" 189 | version = "4.5.26" 190 | source = "registry+https://github.com/rust-lang/crates.io-index" 191 | checksum = "96b01801b5fc6a0a232407abc821660c9c6d25a1cafc0d4f85f29fb8d9afc121" 192 | dependencies = [ 193 | "anstream", 194 | "anstyle", 195 | "clap_lex", 196 | "strsim", 197 | ] 198 | 199 | [[package]] 200 | name = "clap_lex" 201 | version = "0.7.4" 202 | source = "registry+https://github.com/rust-lang/crates.io-index" 203 | checksum = "f46ad14479a25103f283c0f10005961cf086d8dc42205bb44c46ac563475dca6" 204 | 205 | [[package]] 206 | name = "colorchoice" 207 | version = "1.0.3" 208 | source = "registry+https://github.com/rust-lang/crates.io-index" 209 | checksum = "5b63caa9aa9397e2d9480a9b13673856c78d8ac123288526c37d7839f2a86990" 210 | 211 | [[package]] 212 | name = "core-foundation-sys" 213 | version = "0.8.7" 214 | source = "registry+https://github.com/rust-lang/crates.io-index" 215 | checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" 216 | 217 | [[package]] 218 | name = "env_logger" 219 | version = "0.7.1" 220 | source = "registry+https://github.com/rust-lang/crates.io-index" 221 | checksum = "44533bbbb3bb3c1fa17d9f2e4e38bbbaf8396ba82193c4cb1b6445d711445d36" 222 | dependencies = [ 223 | "atty", 224 | "humantime", 225 | "log 0.4.24", 226 | "regex", 227 | "termcolor", 228 | ] 229 | 230 | [[package]] 231 | name = "erased-serde" 232 | version = "0.4.5" 233 | source = "registry+https://github.com/rust-lang/crates.io-index" 234 | checksum = "24e2389d65ab4fab27dc2a5de7b191e1f6617d1f1c8855c0dc569c94a4cbb18d" 235 | dependencies = [ 236 | "serde", 237 | "typeid", 238 | ] 239 | 240 | [[package]] 241 | name = "errno" 242 | version = "0.3.10" 243 | source = "registry+https://github.com/rust-lang/crates.io-index" 244 | checksum = "33d852cb9b869c2a9b3df2f71a3074817f01e1844f839a144f5fcef059a4eb5d" 245 | dependencies = [ 246 | "libc", 247 | "windows-sys", 248 | ] 249 | 250 | [[package]] 251 | name = "failure" 252 | version = "0.1.8" 253 | source = "registry+https://github.com/rust-lang/crates.io-index" 254 | checksum = "d32e9bd16cc02eae7db7ef620b392808b89f6a5e16bb3497d159c6b92a0f4f86" 255 | dependencies = [ 256 | "backtrace", 257 | "failure_derive", 258 | ] 259 | 260 | [[package]] 261 | name = "failure_derive" 262 | version = "0.1.8" 263 | source = "registry+https://github.com/rust-lang/crates.io-index" 264 | checksum = "aa4da3c766cd7a0db8242e326e9e4e081edd567072893ed320008189715366a4" 265 | dependencies = [ 266 | "proc-macro2", 267 | "quote", 268 | "syn 1.0.109", 269 | "synstructure", 270 | ] 271 | 272 | [[package]] 273 | name = "fallible-iterator" 274 | version = "0.2.0" 275 | source = "registry+https://github.com/rust-lang/crates.io-index" 276 | checksum = "4443176a9f2c162692bd3d352d745ef9413eec5782a80d8fd6f8a1ac692a07f7" 277 | 278 | [[package]] 279 | name = "fallible-streaming-iterator" 280 | version = "0.1.9" 281 | source = "registry+https://github.com/rust-lang/crates.io-index" 282 | checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" 283 | 284 | [[package]] 285 | name = "fastrand" 286 | version = "2.3.0" 287 | source = "registry+https://github.com/rust-lang/crates.io-index" 288 | checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" 289 | 290 | [[package]] 291 | name = "fuse" 292 | version = "0.3.1" 293 | source = "registry+https://github.com/rust-lang/crates.io-index" 294 | checksum = "80e57070510966bfef93662a81cb8aa2b1c7db0964354fa9921434f04b9e8660" 295 | dependencies = [ 296 | "libc", 297 | "log 0.3.9", 298 | "pkg-config", 299 | "thread-scoped", 300 | "time", 301 | ] 302 | 303 | [[package]] 304 | name = "getrandom" 305 | version = "0.2.15" 306 | source = "registry+https://github.com/rust-lang/crates.io-index" 307 | checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7" 308 | dependencies = [ 309 | "cfg-if", 310 | "libc", 311 | "wasi 0.11.0+wasi-snapshot-preview1", 312 | ] 313 | 314 | [[package]] 315 | name = "gimli" 316 | version = "0.31.1" 317 | source = "registry+https://github.com/rust-lang/crates.io-index" 318 | checksum = "07e28edb80900c19c28f1072f2e8aeca7fa06b23cd4169cefe1af5aa3260783f" 319 | 320 | [[package]] 321 | name = "hermit-abi" 322 | version = "0.1.19" 323 | source = "registry+https://github.com/rust-lang/crates.io-index" 324 | checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33" 325 | dependencies = [ 326 | "libc", 327 | ] 328 | 329 | [[package]] 330 | name = "humantime" 331 | version = "1.3.0" 332 | source = "registry+https://github.com/rust-lang/crates.io-index" 333 | checksum = "df004cfca50ef23c36850aaaa59ad52cc70d0e90243c3c7737a4dd32dc7a3c4f" 334 | dependencies = [ 335 | "quick-error", 336 | ] 337 | 338 | [[package]] 339 | name = "iana-time-zone" 340 | version = "0.1.61" 341 | source = "registry+https://github.com/rust-lang/crates.io-index" 342 | checksum = "235e081f3925a06703c2d0117ea8b91f042756fd6e7a6e5d901e8ca1a996b220" 343 | dependencies = [ 344 | "android_system_properties", 345 | "core-foundation-sys", 346 | "iana-time-zone-haiku", 347 | "js-sys", 348 | "wasm-bindgen", 349 | "windows-core", 350 | ] 351 | 352 | [[package]] 353 | name = "iana-time-zone-haiku" 354 | version = "0.1.2" 355 | source = "registry+https://github.com/rust-lang/crates.io-index" 356 | checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" 357 | dependencies = [ 358 | "cc", 359 | ] 360 | 361 | [[package]] 362 | name = "is_terminal_polyfill" 363 | version = "1.70.1" 364 | source = "registry+https://github.com/rust-lang/crates.io-index" 365 | checksum = "7943c866cc5cd64cbc25b2e01621d07fa8eb2a1a23160ee81ce38704e97b8ecf" 366 | 367 | [[package]] 368 | name = "itoa" 369 | version = "1.0.14" 370 | source = "registry+https://github.com/rust-lang/crates.io-index" 371 | checksum = "d75a2a4b1b190afb6f5425f10f6a8f959d2ea0b9c2b1d79553551850539e4674" 372 | 373 | [[package]] 374 | name = "js-sys" 375 | version = "0.3.76" 376 | source = "registry+https://github.com/rust-lang/crates.io-index" 377 | checksum = "6717b6b5b077764fb5966237269cb3c64edddde4b14ce42647430a78ced9e7b7" 378 | dependencies = [ 379 | "once_cell", 380 | "wasm-bindgen", 381 | ] 382 | 383 | [[package]] 384 | name = "libc" 385 | version = "0.2.169" 386 | source = "registry+https://github.com/rust-lang/crates.io-index" 387 | checksum = "b5aba8db14291edd000dfcc4d620c7ebfb122c613afb886ca8803fa4e128a20a" 388 | 389 | [[package]] 390 | name = "libsqlite3-sys" 391 | version = "0.16.0" 392 | source = "registry+https://github.com/rust-lang/crates.io-index" 393 | checksum = "5e5b95e89c330291768dc840238db7f9e204fd208511ab6319b56193a7f2ae25" 394 | dependencies = [ 395 | "cc", 396 | "pkg-config", 397 | "vcpkg", 398 | ] 399 | 400 | [[package]] 401 | name = "linked-hash-map" 402 | version = "0.5.6" 403 | source = "registry+https://github.com/rust-lang/crates.io-index" 404 | checksum = "0717cef1bc8b636c6e1c1bbdefc09e6322da8a9321966e8928ef80d20f7f770f" 405 | 406 | [[package]] 407 | name = "linux-raw-sys" 408 | version = "0.4.15" 409 | source = "registry+https://github.com/rust-lang/crates.io-index" 410 | checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" 411 | 412 | [[package]] 413 | name = "log" 414 | version = "0.3.9" 415 | source = "registry+https://github.com/rust-lang/crates.io-index" 416 | checksum = "e19e8d5c34a3e0e2223db8e060f9e8264aeeb5c5fc64a4ee9965c062211c024b" 417 | dependencies = [ 418 | "log 0.4.24", 419 | ] 420 | 421 | [[package]] 422 | name = "log" 423 | version = "0.4.24" 424 | source = "registry+https://github.com/rust-lang/crates.io-index" 425 | checksum = "3d6ea2a48c204030ee31a7d7fc72c93294c92fe87ecb1789881c9543516e1a0d" 426 | dependencies = [ 427 | "value-bag", 428 | ] 429 | 430 | [[package]] 431 | name = "lru-cache" 432 | version = "0.1.2" 433 | source = "registry+https://github.com/rust-lang/crates.io-index" 434 | checksum = "31e24f1ad8321ca0e8a1e0ac13f23cb668e6f5466c2c57319f6a5cf1cc8e3b1c" 435 | dependencies = [ 436 | "linked-hash-map", 437 | ] 438 | 439 | [[package]] 440 | name = "memchr" 441 | version = "2.7.4" 442 | source = "registry+https://github.com/rust-lang/crates.io-index" 443 | checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" 444 | 445 | [[package]] 446 | name = "miniz_oxide" 447 | version = "0.8.2" 448 | source = "registry+https://github.com/rust-lang/crates.io-index" 449 | checksum = "4ffbe83022cedc1d264172192511ae958937694cd57ce297164951b8b3568394" 450 | dependencies = [ 451 | "adler2", 452 | ] 453 | 454 | [[package]] 455 | name = "nix" 456 | version = "0.29.0" 457 | source = "registry+https://github.com/rust-lang/crates.io-index" 458 | checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46" 459 | dependencies = [ 460 | "bitflags 2.7.0", 461 | "cfg-if", 462 | "cfg_aliases", 463 | "libc", 464 | ] 465 | 466 | [[package]] 467 | name = "num-traits" 468 | version = "0.2.19" 469 | source = "registry+https://github.com/rust-lang/crates.io-index" 470 | checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" 471 | dependencies = [ 472 | "autocfg", 473 | ] 474 | 475 | [[package]] 476 | name = "object" 477 | version = "0.36.7" 478 | source = "registry+https://github.com/rust-lang/crates.io-index" 479 | checksum = "62948e14d923ea95ea2c7c86c71013138b66525b86bdc08d2dcc262bdb497b87" 480 | dependencies = [ 481 | "memchr", 482 | ] 483 | 484 | [[package]] 485 | name = "once_cell" 486 | version = "1.20.2" 487 | source = "registry+https://github.com/rust-lang/crates.io-index" 488 | checksum = "1261fe7e33c73b354eab43b1273a57c8f967d0391e80353e51f764ac02cf6775" 489 | 490 | [[package]] 491 | name = "pkg-config" 492 | version = "0.3.31" 493 | source = "registry+https://github.com/rust-lang/crates.io-index" 494 | checksum = "953ec861398dccce10c670dfeaf3ec4911ca479e9c02154b3a215178c5f566f2" 495 | 496 | [[package]] 497 | name = "proc-macro2" 498 | version = "1.0.93" 499 | source = "registry+https://github.com/rust-lang/crates.io-index" 500 | checksum = "60946a68e5f9d28b0dc1c21bb8a97ee7d018a8b322fa57838ba31cc878e22d99" 501 | dependencies = [ 502 | "unicode-ident", 503 | ] 504 | 505 | [[package]] 506 | name = "quick-error" 507 | version = "1.2.3" 508 | source = "registry+https://github.com/rust-lang/crates.io-index" 509 | checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" 510 | 511 | [[package]] 512 | name = "quote" 513 | version = "1.0.38" 514 | source = "registry+https://github.com/rust-lang/crates.io-index" 515 | checksum = "0e4dccaaaf89514f546c693ddc140f729f958c247918a13380cccc6078391acc" 516 | dependencies = [ 517 | "proc-macro2", 518 | ] 519 | 520 | [[package]] 521 | name = "regex" 522 | version = "1.11.1" 523 | source = "registry+https://github.com/rust-lang/crates.io-index" 524 | checksum = "b544ef1b4eac5dc2db33ea63606ae9ffcfac26c1416a2806ae0bf5f56b201191" 525 | dependencies = [ 526 | "aho-corasick", 527 | "memchr", 528 | "regex-automata", 529 | "regex-syntax", 530 | ] 531 | 532 | [[package]] 533 | name = "regex-automata" 534 | version = "0.4.9" 535 | source = "registry+https://github.com/rust-lang/crates.io-index" 536 | checksum = "809e8dc61f6de73b46c85f4c96486310fe304c434cfa43669d7b40f711150908" 537 | dependencies = [ 538 | "aho-corasick", 539 | "memchr", 540 | "regex-syntax", 541 | ] 542 | 543 | [[package]] 544 | name = "regex-syntax" 545 | version = "0.8.5" 546 | source = "registry+https://github.com/rust-lang/crates.io-index" 547 | checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c" 548 | 549 | [[package]] 550 | name = "rusqlite" 551 | version = "0.20.0" 552 | source = "registry+https://github.com/rust-lang/crates.io-index" 553 | checksum = "2a194373ef527035645a1bc21b10dc2125f73497e6e155771233eb187aedd051" 554 | dependencies = [ 555 | "bitflags 1.3.2", 556 | "fallible-iterator", 557 | "fallible-streaming-iterator", 558 | "libsqlite3-sys", 559 | "lru-cache", 560 | "memchr", 561 | "time", 562 | ] 563 | 564 | [[package]] 565 | name = "rustc-demangle" 566 | version = "0.1.24" 567 | source = "registry+https://github.com/rust-lang/crates.io-index" 568 | checksum = "719b953e2095829ee67db738b3bfa9fa368c94900df327b3f07fe6e794d2fe1f" 569 | 570 | [[package]] 571 | name = "rustix" 572 | version = "0.38.43" 573 | source = "registry+https://github.com/rust-lang/crates.io-index" 574 | checksum = "a78891ee6bf2340288408954ac787aa063d8e8817e9f53abb37c695c6d834ef6" 575 | dependencies = [ 576 | "bitflags 2.7.0", 577 | "errno", 578 | "libc", 579 | "linux-raw-sys", 580 | "windows-sys", 581 | ] 582 | 583 | [[package]] 584 | name = "ryu" 585 | version = "1.0.18" 586 | source = "registry+https://github.com/rust-lang/crates.io-index" 587 | checksum = "f3cb5ba0dc43242ce17de99c180e96db90b235b8a9fdc9543c96d2209116bd9f" 588 | 589 | [[package]] 590 | name = "serde" 591 | version = "1.0.217" 592 | source = "registry+https://github.com/rust-lang/crates.io-index" 593 | checksum = "02fc4265df13d6fa1d00ecff087228cc0a2b5f3c0e87e258d8b94a156e984c70" 594 | dependencies = [ 595 | "serde_derive", 596 | ] 597 | 598 | [[package]] 599 | name = "serde_derive" 600 | version = "1.0.217" 601 | source = "registry+https://github.com/rust-lang/crates.io-index" 602 | checksum = "5a9bf7cf98d04a2b28aead066b7496853d4779c9cc183c440dbac457641e19a0" 603 | dependencies = [ 604 | "proc-macro2", 605 | "quote", 606 | "syn 2.0.96", 607 | ] 608 | 609 | [[package]] 610 | name = "serde_fmt" 611 | version = "1.0.3" 612 | source = "registry+https://github.com/rust-lang/crates.io-index" 613 | checksum = "e1d4ddca14104cd60529e8c7f7ba71a2c8acd8f7f5cfcdc2faf97eeb7c3010a4" 614 | dependencies = [ 615 | "serde", 616 | ] 617 | 618 | [[package]] 619 | name = "shlex" 620 | version = "1.3.0" 621 | source = "registry+https://github.com/rust-lang/crates.io-index" 622 | checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" 623 | 624 | [[package]] 625 | name = "sqlite-fs" 626 | version = "0.1.0" 627 | dependencies = [ 628 | "chrono", 629 | "clap", 630 | "env_logger", 631 | "failure", 632 | "fuse", 633 | "libc", 634 | "log 0.4.24", 635 | "nix", 636 | "rusqlite", 637 | "tempfile", 638 | "time", 639 | ] 640 | 641 | [[package]] 642 | name = "strsim" 643 | version = "0.11.1" 644 | source = "registry+https://github.com/rust-lang/crates.io-index" 645 | checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" 646 | 647 | [[package]] 648 | name = "sval" 649 | version = "2.13.2" 650 | source = "registry+https://github.com/rust-lang/crates.io-index" 651 | checksum = "f6dc0f9830c49db20e73273ffae9b5240f63c42e515af1da1fceefb69fceafd8" 652 | 653 | [[package]] 654 | name = "sval_buffer" 655 | version = "2.13.2" 656 | source = "registry+https://github.com/rust-lang/crates.io-index" 657 | checksum = "429922f7ad43c0ef8fd7309e14d750e38899e32eb7e8da656ea169dd28ee212f" 658 | dependencies = [ 659 | "sval", 660 | "sval_ref", 661 | ] 662 | 663 | [[package]] 664 | name = "sval_dynamic" 665 | version = "2.13.2" 666 | source = "registry+https://github.com/rust-lang/crates.io-index" 667 | checksum = "68f16ff5d839396c11a30019b659b0976348f3803db0626f736764c473b50ff4" 668 | dependencies = [ 669 | "sval", 670 | ] 671 | 672 | [[package]] 673 | name = "sval_fmt" 674 | version = "2.13.2" 675 | source = "registry+https://github.com/rust-lang/crates.io-index" 676 | checksum = "c01c27a80b6151b0557f9ccbe89c11db571dc5f68113690c1e028d7e974bae94" 677 | dependencies = [ 678 | "itoa", 679 | "ryu", 680 | "sval", 681 | ] 682 | 683 | [[package]] 684 | name = "sval_json" 685 | version = "2.13.2" 686 | source = "registry+https://github.com/rust-lang/crates.io-index" 687 | checksum = "0deef63c70da622b2a8069d8600cf4b05396459e665862e7bdb290fd6cf3f155" 688 | dependencies = [ 689 | "itoa", 690 | "ryu", 691 | "sval", 692 | ] 693 | 694 | [[package]] 695 | name = "sval_nested" 696 | version = "2.13.2" 697 | source = "registry+https://github.com/rust-lang/crates.io-index" 698 | checksum = "a39ce5976ae1feb814c35d290cf7cf8cd4f045782fe1548d6bc32e21f6156e9f" 699 | dependencies = [ 700 | "sval", 701 | "sval_buffer", 702 | "sval_ref", 703 | ] 704 | 705 | [[package]] 706 | name = "sval_ref" 707 | version = "2.13.2" 708 | source = "registry+https://github.com/rust-lang/crates.io-index" 709 | checksum = "bb7c6ee3751795a728bc9316a092023529ffea1783499afbc5c66f5fabebb1fa" 710 | dependencies = [ 711 | "sval", 712 | ] 713 | 714 | [[package]] 715 | name = "sval_serde" 716 | version = "2.13.2" 717 | source = "registry+https://github.com/rust-lang/crates.io-index" 718 | checksum = "2a5572d0321b68109a343634e3a5d576bf131b82180c6c442dee06349dfc652a" 719 | dependencies = [ 720 | "serde", 721 | "sval", 722 | "sval_nested", 723 | ] 724 | 725 | [[package]] 726 | name = "syn" 727 | version = "1.0.109" 728 | source = "registry+https://github.com/rust-lang/crates.io-index" 729 | checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" 730 | dependencies = [ 731 | "proc-macro2", 732 | "quote", 733 | "unicode-ident", 734 | ] 735 | 736 | [[package]] 737 | name = "syn" 738 | version = "2.0.96" 739 | source = "registry+https://github.com/rust-lang/crates.io-index" 740 | checksum = "d5d0adab1ae378d7f53bdebc67a39f1f151407ef230f0ce2883572f5d8985c80" 741 | dependencies = [ 742 | "proc-macro2", 743 | "quote", 744 | "unicode-ident", 745 | ] 746 | 747 | [[package]] 748 | name = "synstructure" 749 | version = "0.12.6" 750 | source = "registry+https://github.com/rust-lang/crates.io-index" 751 | checksum = "f36bdaa60a83aca3921b5259d5400cbf5e90fc51931376a9bd4a0eb79aa7210f" 752 | dependencies = [ 753 | "proc-macro2", 754 | "quote", 755 | "syn 1.0.109", 756 | "unicode-xid", 757 | ] 758 | 759 | [[package]] 760 | name = "tempfile" 761 | version = "3.15.0" 762 | source = "registry+https://github.com/rust-lang/crates.io-index" 763 | checksum = "9a8a559c81686f576e8cd0290cd2a24a2a9ad80c98b3478856500fcbd7acd704" 764 | dependencies = [ 765 | "cfg-if", 766 | "fastrand", 767 | "getrandom", 768 | "once_cell", 769 | "rustix", 770 | "windows-sys", 771 | ] 772 | 773 | [[package]] 774 | name = "termcolor" 775 | version = "1.4.1" 776 | source = "registry+https://github.com/rust-lang/crates.io-index" 777 | checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" 778 | dependencies = [ 779 | "winapi-util", 780 | ] 781 | 782 | [[package]] 783 | name = "thread-scoped" 784 | version = "1.0.2" 785 | source = "registry+https://github.com/rust-lang/crates.io-index" 786 | checksum = "bcbb6aa301e5d3b0b5ef639c9a9c7e2f1c944f177b460c04dc24c69b1fa2bd99" 787 | 788 | [[package]] 789 | name = "time" 790 | version = "0.1.45" 791 | source = "registry+https://github.com/rust-lang/crates.io-index" 792 | checksum = "1b797afad3f312d1c66a56d11d0316f916356d11bd158fbc6ca6389ff6bf805a" 793 | dependencies = [ 794 | "libc", 795 | "wasi 0.10.0+wasi-snapshot-preview1", 796 | "winapi", 797 | ] 798 | 799 | [[package]] 800 | name = "typeid" 801 | version = "1.0.2" 802 | source = "registry+https://github.com/rust-lang/crates.io-index" 803 | checksum = "0e13db2e0ccd5e14a544e8a246ba2312cd25223f616442d7f2cb0e3db614236e" 804 | 805 | [[package]] 806 | name = "unicode-ident" 807 | version = "1.0.14" 808 | source = "registry+https://github.com/rust-lang/crates.io-index" 809 | checksum = "adb9e6ca4f869e1180728b7950e35922a7fc6397f7b641499e8f3ef06e50dc83" 810 | 811 | [[package]] 812 | name = "unicode-xid" 813 | version = "0.2.6" 814 | source = "registry+https://github.com/rust-lang/crates.io-index" 815 | checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" 816 | 817 | [[package]] 818 | name = "utf8parse" 819 | version = "0.2.2" 820 | source = "registry+https://github.com/rust-lang/crates.io-index" 821 | checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" 822 | 823 | [[package]] 824 | name = "value-bag" 825 | version = "1.10.0" 826 | source = "registry+https://github.com/rust-lang/crates.io-index" 827 | checksum = "3ef4c4aa54d5d05a279399bfa921ec387b7aba77caf7a682ae8d86785b8fdad2" 828 | dependencies = [ 829 | "value-bag-serde1", 830 | "value-bag-sval2", 831 | ] 832 | 833 | [[package]] 834 | name = "value-bag-serde1" 835 | version = "1.10.0" 836 | source = "registry+https://github.com/rust-lang/crates.io-index" 837 | checksum = "4bb773bd36fd59c7ca6e336c94454d9c66386416734817927ac93d81cb3c5b0b" 838 | dependencies = [ 839 | "erased-serde", 840 | "serde", 841 | "serde_fmt", 842 | ] 843 | 844 | [[package]] 845 | name = "value-bag-sval2" 846 | version = "1.10.0" 847 | source = "registry+https://github.com/rust-lang/crates.io-index" 848 | checksum = "53a916a702cac43a88694c97657d449775667bcd14b70419441d05b7fea4a83a" 849 | dependencies = [ 850 | "sval", 851 | "sval_buffer", 852 | "sval_dynamic", 853 | "sval_fmt", 854 | "sval_json", 855 | "sval_ref", 856 | "sval_serde", 857 | ] 858 | 859 | [[package]] 860 | name = "vcpkg" 861 | version = "0.2.15" 862 | source = "registry+https://github.com/rust-lang/crates.io-index" 863 | checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" 864 | 865 | [[package]] 866 | name = "wasi" 867 | version = "0.10.0+wasi-snapshot-preview1" 868 | source = "registry+https://github.com/rust-lang/crates.io-index" 869 | checksum = "1a143597ca7c7793eff794def352d41792a93c481eb1042423ff7ff72ba2c31f" 870 | 871 | [[package]] 872 | name = "wasi" 873 | version = "0.11.0+wasi-snapshot-preview1" 874 | source = "registry+https://github.com/rust-lang/crates.io-index" 875 | checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" 876 | 877 | [[package]] 878 | name = "wasm-bindgen" 879 | version = "0.2.99" 880 | source = "registry+https://github.com/rust-lang/crates.io-index" 881 | checksum = "a474f6281d1d70c17ae7aa6a613c87fce69a127e2624002df63dcb39d6cf6396" 882 | dependencies = [ 883 | "cfg-if", 884 | "once_cell", 885 | "wasm-bindgen-macro", 886 | ] 887 | 888 | [[package]] 889 | name = "wasm-bindgen-backend" 890 | version = "0.2.99" 891 | source = "registry+https://github.com/rust-lang/crates.io-index" 892 | checksum = "5f89bb38646b4f81674e8f5c3fb81b562be1fd936d84320f3264486418519c79" 893 | dependencies = [ 894 | "bumpalo", 895 | "log 0.4.24", 896 | "proc-macro2", 897 | "quote", 898 | "syn 2.0.96", 899 | "wasm-bindgen-shared", 900 | ] 901 | 902 | [[package]] 903 | name = "wasm-bindgen-macro" 904 | version = "0.2.99" 905 | source = "registry+https://github.com/rust-lang/crates.io-index" 906 | checksum = "2cc6181fd9a7492eef6fef1f33961e3695e4579b9872a6f7c83aee556666d4fe" 907 | dependencies = [ 908 | "quote", 909 | "wasm-bindgen-macro-support", 910 | ] 911 | 912 | [[package]] 913 | name = "wasm-bindgen-macro-support" 914 | version = "0.2.99" 915 | source = "registry+https://github.com/rust-lang/crates.io-index" 916 | checksum = "30d7a95b763d3c45903ed6c81f156801839e5ee968bb07e534c44df0fcd330c2" 917 | dependencies = [ 918 | "proc-macro2", 919 | "quote", 920 | "syn 2.0.96", 921 | "wasm-bindgen-backend", 922 | "wasm-bindgen-shared", 923 | ] 924 | 925 | [[package]] 926 | name = "wasm-bindgen-shared" 927 | version = "0.2.99" 928 | source = "registry+https://github.com/rust-lang/crates.io-index" 929 | checksum = "943aab3fdaaa029a6e0271b35ea10b72b943135afe9bffca82384098ad0e06a6" 930 | 931 | [[package]] 932 | name = "winapi" 933 | version = "0.3.9" 934 | source = "registry+https://github.com/rust-lang/crates.io-index" 935 | checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" 936 | dependencies = [ 937 | "winapi-i686-pc-windows-gnu", 938 | "winapi-x86_64-pc-windows-gnu", 939 | ] 940 | 941 | [[package]] 942 | name = "winapi-i686-pc-windows-gnu" 943 | version = "0.4.0" 944 | source = "registry+https://github.com/rust-lang/crates.io-index" 945 | checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" 946 | 947 | [[package]] 948 | name = "winapi-util" 949 | version = "0.1.9" 950 | source = "registry+https://github.com/rust-lang/crates.io-index" 951 | checksum = "cf221c93e13a30d793f7645a0e7762c55d169dbb0a49671918a2319d289b10bb" 952 | dependencies = [ 953 | "windows-sys", 954 | ] 955 | 956 | [[package]] 957 | name = "winapi-x86_64-pc-windows-gnu" 958 | version = "0.4.0" 959 | source = "registry+https://github.com/rust-lang/crates.io-index" 960 | checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" 961 | 962 | [[package]] 963 | name = "windows-core" 964 | version = "0.52.0" 965 | source = "registry+https://github.com/rust-lang/crates.io-index" 966 | checksum = "33ab640c8d7e35bf8ba19b884ba838ceb4fba93a4e8c65a9059d08afcfc683d9" 967 | dependencies = [ 968 | "windows-targets", 969 | ] 970 | 971 | [[package]] 972 | name = "windows-sys" 973 | version = "0.59.0" 974 | source = "registry+https://github.com/rust-lang/crates.io-index" 975 | checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" 976 | dependencies = [ 977 | "windows-targets", 978 | ] 979 | 980 | [[package]] 981 | name = "windows-targets" 982 | version = "0.52.6" 983 | source = "registry+https://github.com/rust-lang/crates.io-index" 984 | checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" 985 | dependencies = [ 986 | "windows_aarch64_gnullvm", 987 | "windows_aarch64_msvc", 988 | "windows_i686_gnu", 989 | "windows_i686_gnullvm", 990 | "windows_i686_msvc", 991 | "windows_x86_64_gnu", 992 | "windows_x86_64_gnullvm", 993 | "windows_x86_64_msvc", 994 | ] 995 | 996 | [[package]] 997 | name = "windows_aarch64_gnullvm" 998 | version = "0.52.6" 999 | source = "registry+https://github.com/rust-lang/crates.io-index" 1000 | checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" 1001 | 1002 | [[package]] 1003 | name = "windows_aarch64_msvc" 1004 | version = "0.52.6" 1005 | source = "registry+https://github.com/rust-lang/crates.io-index" 1006 | checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" 1007 | 1008 | [[package]] 1009 | name = "windows_i686_gnu" 1010 | version = "0.52.6" 1011 | source = "registry+https://github.com/rust-lang/crates.io-index" 1012 | checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" 1013 | 1014 | [[package]] 1015 | name = "windows_i686_gnullvm" 1016 | version = "0.52.6" 1017 | source = "registry+https://github.com/rust-lang/crates.io-index" 1018 | checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" 1019 | 1020 | [[package]] 1021 | name = "windows_i686_msvc" 1022 | version = "0.52.6" 1023 | source = "registry+https://github.com/rust-lang/crates.io-index" 1024 | checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" 1025 | 1026 | [[package]] 1027 | name = "windows_x86_64_gnu" 1028 | version = "0.52.6" 1029 | source = "registry+https://github.com/rust-lang/crates.io-index" 1030 | checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" 1031 | 1032 | [[package]] 1033 | name = "windows_x86_64_gnullvm" 1034 | version = "0.52.6" 1035 | source = "registry+https://github.com/rust-lang/crates.io-index" 1036 | checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" 1037 | 1038 | [[package]] 1039 | name = "windows_x86_64_msvc" 1040 | version = "0.52.6" 1041 | source = "registry+https://github.com/rust-lang/crates.io-index" 1042 | checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" 1043 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "sqlite-fs" 3 | version = "0.1.0" 4 | authors = ["Matsumura "] 5 | edition = "2021" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | fuse = "0.3" 11 | chrono = "0.4" 12 | libc = "0.2" 13 | failure = "0.1" 14 | log = "0.4" 15 | env_logger = "0.7" 16 | time = "0.1" 17 | 18 | [dependencies.clap] 19 | version = "4.5.26" 20 | features = ["cargo","color"] 21 | 22 | [dependencies.rusqlite] 23 | version = "0.20.0" 24 | features = ["bundled", "blob"] 25 | 26 | [dependencies.nix] 27 | version = "0.29" 28 | features = ["fs"] 29 | 30 | [dev-dependencies] 31 | tempfile = "3" 32 | 33 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | The MIT License 2 | 3 | Copyright (c) 2020 Naruaki Matsumura 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 13 | all 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 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # sqlite-fs 2 | 3 | ## About 4 | 5 | sqlite-fs allows Linux and MacOS to mount a sqlite database file as a normal filesystem. 6 | 7 | ## Requirements 8 | 9 | - Latest Rust Programming Language (≥ 1.38) 10 | - libfuse(Linux) or osxfuse(MacOS) is required by [fuse-rs](https://github.com/zargony/fuse-rs) 11 | 12 | ## Usage 13 | ### Mount a filesystem 14 | 15 | ``` 16 | $ sqlite-fs [] 17 | ``` 18 | 19 | If a database file doesn't exist, sqlite-fs create db file and tables. 20 | 21 | If a database file name isn't specified, sqlite-fs use in-memory-db instead of a file. 22 | All data will be deleted when the filesystem is closed. 23 | 24 | ### Unmount a filesystem 25 | 26 | - Linux 27 | 28 | ``` 29 | $ fusermount -u 30 | ``` 31 | 32 | - Mac 33 | 34 | ``` 35 | $ umount 36 | ``` 37 | 38 | ## example 39 | ``` 40 | $ sqlite-fs ~/mount ~/filesystem.sqlite & 41 | $ echo "Hello world\!" > ~/mount/hello.txt 42 | $ cat ~/mount/hello.txt 43 | Hello world! 44 | ``` 45 | 46 | ## functions 47 | 48 | - [x] Create/Read/Delete directories 49 | - [x] Create/Read/Write/Delete files 50 | - [x] Change attributions 51 | - [x] Copy/Move files 52 | - [x] Create Hard Link and Symbolic Link 53 | - [x] Read/Write extended attributes 54 | - [] File lock operations 55 | - [] Strict error handling 56 | 57 | -------------------------------------------------------------------------------- /init.sql: -------------------------------------------------------------------------------- 1 | PRAGMA foreign_keys=ON; 2 | BEGIN TRANSACTION; 3 | CREATE TABLE metadata( 4 | id integer primary key, 5 | size int default 0 not null, 6 | atime text, 7 | atime_nsec int, 8 | mtime text, 9 | mtime_nsec int, 10 | ctime text, 11 | ctime_nsec int, 12 | crtime text, 13 | crtime_nsec int, 14 | kind int, 15 | mode int, 16 | nlink int default 0 not null, 17 | uid int default 0, 18 | gid int default 0, 19 | rdev int default 0, 20 | flags int default 0 21 | ); 22 | INSERT INTO metadata VALUES(1,0,'1970-01-01 00:00:00',0,'1970-01-01 00:00:00',0,'1970-01-01 00:00:00',0,'1970-01-01 00:00:00',0,16384,16832,1,0,0,0,0); 23 | CREATE TABLE data( 24 | file_id int, 25 | block_num int, 26 | data blob, 27 | foreign key (file_id) references metadata(id) on delete cascade, 28 | primary key (file_id, block_num) 29 | ); 30 | CREATE TABLE dentry( 31 | parent_id int, 32 | child_id int, 33 | file_type int, 34 | name text, 35 | foreign key (parent_id) references metadata(id) on delete cascade, 36 | foreign key (child_id) references metadata(id) on delete cascade, 37 | primary key (parent_id, name) 38 | ); 39 | INSERT INTO dentry VALUES(1,1,16384,'.'); 40 | INSERT INTO dentry VALUES(1,1,16384,'..'); 41 | CREATE TABLE xattr( 42 | file_id int, 43 | name text, 44 | value blob, 45 | foreign key (file_id) references metadata(id) on delete cascade, 46 | primary key (file_id, name) 47 | ); 48 | COMMIT; 49 | 50 | -------------------------------------------------------------------------------- /misc/implement.md: -------------------------------------------------------------------------------- 1 | # 概要 2 | 3 | ## 3行で 4 | この記事は、RustによるFUSEインターフェースの実装である `fuse-rs` を用いてFUSEを使ったファイルシステムの実装に挑戦し、 5 | 得られた知見などを記録したものです。 6 | 複数回に分けて、徐々に関数を実装していきます。今回は、あらかじめ用意されたファイルをreadできるようになる所までいきます。 7 | 作成したファイルシステムは [こちら](https://github.com/narumatt/sqlitefs) 8 | に置いてあります。 9 | 10 | ## 概要 11 | 12 | Filesystem in Userspace(FUSE) はLinuxのユーザ空間でファイルシステムを実現する仕組みです。 13 | 14 | 一般的にファイルシステムを作るというと、カーネルモジュールを作成しなければならないのでいろいろと苦労が多いですが、FUSEを使えば比較的楽に実装できます。 15 | また、HDDなどの実デバイスに直接読み書きするだけでなく、ネットワークストレージを利用した仮想的なファイルシステムを作るのにも都合がよいです。 16 | 17 | そんな訳で、FUSEを使ったSSH as a filesystem や AWS S3 as a filesystemといった 18 | 「読み書きできる何かをファイルシステムとしてマウント出来るようにするソフトウェア」があれこれと存在します。 19 | 上記のようなソフトウェアの代表例である `sshfs` や `s3fs` は使った事のある人もいるのではないでしょうか。 20 | 21 | 元々はLinuxの一部でしたが、MacOSやFreeBSDでも使用できます。最近ではWindowsのWSL2でも使えるようになるようです。WSLの導入の手間が要るとはいえ、WindowsでもFUSEが使えるのは嬉しいですね。 22 | ちなみにWindowsには、Fuseに似た仮想ファイルシステムである [Dokan](https://github.com/dokan-dev/dokany) もあります。 23 | 24 | ただし、カーネルモジュールを作るより楽とはいえ、FUSEを使ったソフトウェアを作成するのは大変です。 25 | ある程度ファイルシステムの知識は必要ですし、何か調べようとしてもドキュメントが少なく、 26 | チュートリアルを見てもほどほどの所で終わってしまい、「あとはサンプルとsshfsの実装などを見てくれ!」とコードの海に投げ出されます。 27 | 28 | そこで、各所の情報をまとめつつ、自分で0からファイルシステムを実装して気をつける点などを見つけていきます。 29 | 30 | ## 参考資料 31 | [Rust FUSE](https://github.com/zargony/fuse-rs) : Rust版Fuseインターフェースのプロジェクト 32 | [libfuse](https://github.com/libfuse/libfuse) : C版のFuseインターフェースライブラリ 33 | [osxfuse](https://github.com/osxfuse/fuse) : MacOS向けのFuseモジュール 34 | [FUSEプロトコルの説明](https://john-millikin.com/the-fuse-protocol) : カーネルモジュール <-> Fuseライブラリ間のプロトコル 35 | [VFSの説明](https://ja.osdn.net/projects/linuxjf/wiki/vfs.txt) 36 | [fuse_lowlevel.h(libfuseのヘッダ)](https://github.com/libfuse/libfuse/blob/master/include/fuse_lowlevel.h): lowlevel関数の説明 37 | [fuse_common.h(libfuseのヘッダ)](https://github.com/libfuse/libfuse/blob/master/include/fuse_common.h) 38 | [Linuxプログラミングインターフェース(書籍)](https://www.oreilly.co.jp/books/9784873115856/) : システムコールがどう動くべきかは大体ここを見て判断する 39 | [libfuseのメーリングリストのアーカイブ](https://sourceforge.net/p/fuse/mailman/fuse-devel/) : fuseの使い方についてはここが一番参考になる 40 | [gcsf](https://github.com/harababurel/gcsf) : fuse-rsを使ったファイルシステムの例 41 | 42 | ## 実験環境 43 | プログラムは全て次の環境で実験しています。 44 | 45 | - Linux: 5.3.11 46 | - ディストリビューション: Fedora 31 47 | - Rust: 1.39.0 48 | - fuse-rs: 0.3.1 49 | 50 | ## FUSEの仕組み(概要) 51 | 52 | FUSE本体はLinuxカーネルに付属するカーネルモジュールで、大抵のディストリビューションではデフォルトで有効になっています。 53 | 54 | FUSEを使ったファイルシステムがマウントされたディレクトリ内に対してシステムコールが呼ばれると、以下のように情報がやりとりされます。 55 | 56 | ``` 57 | システムコール <-> VFS <-> FUSE <-(FUSE ABI)-> FUSEインターフェース <-(FUSE API)-> 自作のファイルシステム <-> デバイスやネットワーク上のストレージ 58 | ``` 59 | 60 | [Wikipediaの図](https://ja.wikipedia.org/wiki/Filesystem_in_Userspace) を見ると分かりやすいです。 61 | 本来であればVFSの先に各ファイルシステムのカーネルモジュールがあるのですが、FUSEは受け取った情報をユーザ空間に横流ししてくれます。 62 | 63 | ## FUSEインターフェース 64 | 65 | FUSEはデバイス `/dev/fuse` を持ち、ここを通じてユーザ空間とやりとりを行います。 66 | 前項の `FUSE <-> FUSEインターフェース` の部分です。 67 | 68 | 規定のプロトコル(FUSE ABI)を用いて `/dev/fuse` に対してデータを渡したり受け取ったりするのがFUSEインターフェースです。 69 | 有名なライブラリとして、C/C++用の [libfuse](https://github.com/libfuse/libfuse) があります。 70 | このlibfuseが大変強力なので、大抵の言語でのFUSEインターフェースはlibfuseのラッパーになっています。 71 | 72 | libfuseを使うと、 `open`, `read`, `write` 等の関数を決められた仕様通りに作成して登録するだけで、ファイルシステムとして動作するようになっています。 73 | 例えば、 `read(2)` のシステムコールが呼ばれると、最終的に自作のファイルシステムの `read` 関数が呼ばれます。 74 | 75 | ```c 76 | // read関数を、常にランダムな内容を返すようにした例 77 | int my_read(const char *path, char *buf, size_t size, off_t offset, struct fuse_file_info *fi) { 78 | ssize_t res; 79 | res = getrandom(buf, size, 0); 80 | return (int)res; 81 | } 82 | ``` 83 | 84 | 登録すべき関数は、 `fuse.h` 内で定義されている通常のものと、 `fuse_lowlevel.h` 内で定義されている低級なものがあります。 85 | ファイルシステムを作成する場合、どちらの関数群を実装するか選択する必要があります。 86 | `fuse.h` の方はおおよそシステムコールと1:1で対応しています。 `lowlevel` の方は `FUSE ABI` と1:1になるように作られています。 87 | 88 | ## fuse-rs 89 | Rustには(ほぼ)独自のFUSEインターフェースの実装 [Rust FUSE(fuse-rs)](https://github.com/zargony/fuse-rs) があります。ありがたいですね。 90 | プロトコルが同じなので、インターフェースの関数(FUSE API)はlibfuseのlowlevel関数と大変似ています。 91 | そのため、何か困った時にはlibfuseの情報が流用できたりします。 92 | 93 | 現時点(2019/10) の最新版は0.3.1で、2年ぐらい更新されていませんが、次バージョン(0.4.0)が開発中です。 94 | 0.3.1と0.4.0では仕様が大きく異なるので注意してください。 95 | また、0.3.1では対応するプロトコルのバージョンが7.8で、最新のものと比較していくつかの機能がありません。 96 | 97 | libfuseはマルチスレッドで動作し、並列I/Oに対応していますが、fuse-rsはシングルスレッドのようです。 98 | 99 | 使用するためには、 `Cargo.toml` に以下のように記述します。 100 | 101 | ```toml 102 | [dependencies] 103 | fuse = "0.3.1" 104 | ``` 105 | 106 | # データの保存先 107 | 今回自分でファイルシステムを実装していく上で、HDDの代わりになるデータの保存先としてsqliteを使用します。 108 | ライブラリは [rusqlite](https://github.com/jgallagher/rusqlite) を使用します。 109 | FUSEの実装方法について調べるのがメインなので、こちらについてはざっくりとしか説明しませんが、ご容赦ください。 110 | 111 | sqliteは可変長のバイナリデータを持てるので、そこにデータを書き込みます。 112 | トランザクションがあるので、ある程度アトミックな操作ができます。 113 | DBなので、メタデータの読み書きも割と簡単にできるでしょう。 114 | 115 | fuse-rsが扱う整数の大半は `u64` ですが、sqliteはunsignedの64bit intに対応していないので、厳密にやろうとするといろいろと面倒になります。 116 | とりあえず全部 `u32` にキャストする事にしますが、気になる場合は `i64` にキャストして、大小比較を行うユーザ定義関数をsqlite上に作成したり、 117 | `u32` 2個に分割したりしてください。 118 | 119 | DBの構造についてざっくりと説明していきます。 120 | 121 | ## データベース構造 122 | テーブルはメタデータテーブル(MDT)とディレクトリエントリテーブル(DET)とブロックデータテーブル(BDT)の3つに分けます。 123 | 今後拡張ファイル属性が必要になってきた場合、拡張属性データテーブル(XATTRT)を追加します。 124 | 125 | 以下では各テーブルについて説明していきます。 126 | 127 | ### メタデータ用テーブル(MDT) 128 | ファイルのinode番号をキーとして検索するとメタデータが返ってくるような、メタデータ用のテーブルを作ります。 129 | メタデータは一般的なファイルシステムのメタデータと同じような形式です。 130 | fuse-rsが関数の引数で渡してきたり、戻り値として要求したりするメタデータ構造体は以下のように定義されています。 131 | 132 | ```rust 133 | // fuse::FileAttr 134 | pub struct FileAttr { 135 | /// inode番号 136 | pub ino: u64, 137 | /// ファイルサイズ(バイト単位) 138 | pub size: u64, 139 | /// ブロックサイズ *Sparse File に対応する場合、実際に使用しているブロック数を返す 140 | pub blocks: u64, 141 | /// Time of last access. *read(2)実行時に更新される 142 | pub atime: Timespec, 143 | /// Time of last modification. *write(2)またはtruncate(2)実行時に更新される 144 | pub mtime: Timespec, 145 | /// Time of last change. *メタデータ変更時に更新される。 write(2)またはtruncate(2)でファイル内容が変わるときも更新される 146 | pub ctime: Timespec, 147 | /// Time of creation (macOS only) 148 | pub crtime: Timespec, 149 | /// ファイル種別 (directory, file, pipe, etc) 150 | pub kind: FileType, 151 | /// パーミッション 152 | pub perm: u16, 153 | /// ハードリンクされている数 154 | pub nlink: u32, 155 | /// User id 156 | pub uid: u32, 157 | /// Group id 158 | pub gid: u32, 159 | /// Rdev *デバイスファイルの場合、デバイスのメジャー番号とマイナー番号が入る 160 | pub rdev: u32, 161 | /// Flags (macOS only, see chflags(2)) *非表示などmac特有の属性が入ります。 162 | pub flags: u32, 163 | } 164 | ``` 165 | 166 | これに合わせて、以下のようなテーブルを作ります。 167 | 168 | |列名 | 型 | 概要| 169 | |---|---|---| 170 | |id|integer primary|ファイルのinode番号 (pkey)| 171 | |size|int|ファイルサイズ| 172 | |atime|text|アクセス時刻| 173 | |atime_nsec|int|アクセス時刻(小数点以下)| 174 | |mtime|text|修正時刻| 175 | |mtime_nsec|int|修正時刻(小数点以下)| 176 | |ctime|text|ステータス変更時刻| 177 | |ctime_nsec|int|ステータス変更時刻(小数点以下)| 178 | |crtime|text|作成時刻(mac用)| 179 | |crtime_nsec|int|作成時刻(小数点以下)| 180 | |kind|int|ファイル種別| 181 | |mode|int|パーミッション(ファイル種別含む)| 182 | |nlink|int|ハードリンク数| 183 | |uid|int|uid| 184 | |gid|int|gid| 185 | |rdev|int|デバイスタイプ| 186 | |flags|int|フラグ(mac用)| 187 | 188 | idをinteger primary keyにします。これがinode番号になります。 189 | 190 | kindはファイル種別です。 191 | 通常ファイル・キャラクターデバイス・ブロックデバイス・FIFO・ソケット・ディレクトリ・シンボリックリンク の7種類があります。 192 | FUSEでは `stat(2)` と同様に、 `mode` にファイル種別のビットも含まれているので、 193 | ビット操作する必要があります。 194 | cのlibfuseでは `libc::S_IFMT` (該当ビットのマスク) `libc::S_IFREG` (通常ファイルを示すビット) 等を用いて 195 | `if((mode & S_IFMT) == S_IFREG)` のようにして判別する事ができます。 196 | fuse-rsの場合はメタデータを返す時はenumで定義されたファイル種別を使い、ビット操作はライブラリ側で処理してくれるので、 197 | 実際のビットがどうなっているかを気にするケースはあまりありませんが、 198 | `mknod` の引数で `mode` が生の値で渡ってくるので、 `mknod` を実装する場合は気をつける必要があります。 199 | 200 | ### ファイルデータ用テーブル(BDT) 201 | ファイルのinode番号とファイル内のブロック番号を指定するとデータが返ってくるような、ブロックデータテーブルを作成します。 202 | ブロックデータテーブル(BDT)のblobにデータを格納します。 203 | BDTはファイルのinode番号, 何番目のブロックか、の列を持ちます。具体的には以下のようになります。 204 | 205 | |列名 | 型 | 概要| 206 | |---|---|---| 207 | |file_id|int|ファイルのinode番号 (pkey)(foreign key)| 208 | |block_num|int|データのブロック番号(1始まり)(pkey)| 209 | |data|blob|データ(4kByte単位とする)| 210 | 211 | 外部キー `foreign key (file_id) references metadata(id) on delete cascade` 212 | を指定する事で、ファイルのメタデータが消えたらデータも削除されるようにします。 213 | 214 | 「あるファイルのあるブロック」は一意なので、主キーとして `(file_id, block_num)` を指定します。 215 | 216 | ### ディレクトリ構造用テーブル(DET) 217 | ディレクトリ構造を表現する方法は、以下の2つの候補があります。 218 | 219 | 1. オブジェクトストレージのように、各ファイルがフルパスを記憶していて、文字列操作で各ディレクトリの情報を得る方法 220 | 1. 一般的なファイルシステムのように、ディレクトリエントリを作る方法 221 | 222 | 今回はfuse-rsの関数とも相性のいい後者のディレクトリエントリ方式で行います。 223 | ディレクトリのinode番号を指定すると、ディレクトリ内の全てのエントリ(ファイル名、ファイルタイプ、inode番号のセット)を返すようなテーブルを作成します。 224 | 225 | 必要なのは以下のデータです。 226 | 227 | |列名 | 型 | 概要| 228 | |---|---|---| 229 | |parent_id|int|親ディレクトリのinode番号 (pkey)(foreign key)| 230 | |child_id|int|子ファイル/子ディレクトリのinode番号 (foreign key)| 231 | |file_type|int|子のファイルタイプ| 232 | |name|text|子のファイル/ディレクトリ名 (pkey)| 233 | 234 | あらゆるディレクトリは `.` (自分自身)と `..` (親ディレクトリ)のエントリを持ちます。 235 | ルートの `..` は自分自身を指すようにします。 236 | `.` と `..` は返さなくともよい事になっていますが、その場合は呼び出し側のプログラムの責任で処理する事になります。 237 | 238 | ### ルートディレクトリ 239 | 初期データとして、ルートディレクトリの情報を入れます。FUSEでは、ルートディレクトリのinode番号は1です。 240 | ルートディレクトリは必ず存在する必要があります。 241 | 242 | # Hello! 243 | ## 概要 244 | 第一段階として、fuse-rsに付属する、サンプルプログラムの `HelloFS` と同じ機能を実装します。 245 | `HelloFS` は以下の機能があります。 246 | 247 | 1. ファイルシステムはリードオンリー 248 | 1. ルート直下に `hello.txt` というファイルがあり、 `"Hello World!\n"` という文字列が書き込まれている 249 | 250 | `fuse::Filesystem` トレイトの関数を実装していきます。 251 | `HelloFS` の機能を実現するのに必要なのは以下の4つの関数です。 252 | 253 | ```rust 254 | use fuse::{ 255 | Filesystem, 256 | ReplyEntry, 257 | ReplyAttr, 258 | ReplyData, 259 | ReplyDirectory, 260 | Request 261 | }; 262 | impl Filesystem for SqliteFs { 263 | fn lookup(&mut self, _req: &Request, parent: u64, name: &OsStr, reply: ReplyEntry){ 264 | ... 265 | } 266 | fn getattr(&mut self, _req: &Request, ino: u64, reply: ReplyAttr) { 267 | ... 268 | } 269 | fn read(&mut self, _req: &Request, ino: u64, _fh: u64, offset: i64, _size: u32, reply: ReplyData) { 270 | ... 271 | } 272 | fn readdir(&mut self, _req: &Request, ino: u64, _fh: u64, offset: i64, mut reply: ReplyDirectory) { 273 | ... 274 | } 275 | } 276 | ``` 277 | 278 | ファイルやディレクトリをopen/closeする関数を実装せずにread関数やreaddir関数を実装していますが、 279 | `libfuse` や `fuse-rs` は全ての関数にデフォルトの実装があり、 280 | 今回のようにreadonlyで状態を持たないファイルシステムの場合、自分で実装しなくても動作します。 281 | これらの関数については今後実装する必要が出てきた時に説明します。 282 | 283 | 284 | ## DB関数 285 | データベースを読み書きする関数です。 286 | 今回作成した関数は以下になります。 287 | 288 | ```rust 289 | pub trait DbModule { 290 | /// ファイルのメタデータを取得する。見つからない場合は0を返す 291 | fn get_inode(&self, inode: u32) -> Result; 292 | 293 | /// ディレクトリのinode番号を指定して、ディレクトが持つディレクトリエントリを全て取得する 294 | fn get_dentry(&self, inode: u32) -> Result, Error>; 295 | 296 | /// 親ディレクトリのinode番号と名前から、ファイルやサブディレクトリのinode番号とメタデータを得る 297 | /// inodeが存在しない場合、inode番号が0の空のinodeを返す 298 | fn lookup(&self, parent: u32, name: &str) -> Result; 299 | 300 | /// inode番号とブロック数を指定して、1ブロック分のデータを読み込む 301 | /// ブロックデータが存在しない場合は、0(NULL)で埋められたブロックを返す 302 | fn get_data(&self, inode: u32, block: u32, length: u32) -> Result, Error>; 303 | 304 | /// DBのブロックサイズとして使っている値を得る 305 | fn get_db_block_size(&self) -> u32; 306 | } 307 | 308 | // メタデータ構造体 309 | pub struct DBFileAttr { 310 | pub ino: u32, 311 | pub size: u32, 312 | pub blocks: u32, 313 | pub atime: SystemTime, 314 | pub mtime: SystemTime, 315 | pub ctime: SystemTime, 316 | pub crtime: SystemTime, 317 | pub kind: FileType, 318 | pub perm: u16, 319 | pub nlink: u32, 320 | pub uid: u32, 321 | pub gid: u32, 322 | pub rdev: u32, 323 | pub flags: u32, 324 | } 325 | 326 | // ディレクトリエントリ構造体 327 | pub struct DEntry { 328 | pub parent_ino: u32, 329 | pub child_ino: u32, 330 | pub filename: String, 331 | pub file_type: FileType, 332 | } 333 | ``` 334 | 335 | ## fuseの関数全般の話 336 | ### fuseの関数 337 | ファイルシステムなので、関数は基本的に受け身です。システムコールに応じて呼び出されます。 338 | fuse-rsでは、 `Filesystem` トレイトが定義されているので、必要な関数を適宜実装していきます。 339 | 340 | ### 引数 341 | どの関数にも `Request` 型の引数 `req` が存在します。 342 | `req.uid()` で実行プロセスのuidが、 `req.gid()` でgidが、 `req.pid()` でpidが取得できます。 343 | 344 | ### 戻り値 345 | `init` 以外の各関数に戻り値は存在せず、引数の `reply` を操作して、呼び出し元に値を受け渡します。 346 | `ReplyEmpty, ReplyData, ReplyAttr` のように、関数に応じて `reply` の型が決まっています。 347 | 348 | `reply.ok()` `reply.error(ENOSYS)` `reply.attr(...)` 等 `reply` の型に応じたメソッドを実行します。 349 | 350 | エラーの場合、 `libc::ENOSYS` `libc::ENOENT` のような定数を `reply.error()` の引数に指定します。 351 | 352 | ## lookup 353 | ```rust 354 | fn lookup(&mut self, _req: &Request, parent: u64, name: &OsStr, reply: ReplyEntry); 355 | ``` 356 | 357 | 引数の `parent` で親ディレクトリのinode番号、 `name` で当該ディレクトリ/ファイルの名前が与えられるので、メタデータを返します。 358 | lookup実行時には `lookup count` をファイルシステム側で用意して、増やしたりしなければなりませんが、 359 | 今回はreadonlyのファイルシステムなので無視します。 360 | `lookup count` については `unlink` 実装時に説明します。 361 | 362 | replyに必要なデータは以下になります。 363 | 364 | ``` 365 | //正常 366 | reply.entry(&TTL, &ATTR, &GENERATION); 367 | エラーの場合 368 | reply.error(ENOENT); 369 | ``` 370 | 371 | ### Replyの引数 372 | `reply.entry()` の3つの引数について説明します。 373 | 374 | #### TTL 375 | `time::Timespec` で期間を指定します。 376 | TTLの間はカーネルは再度問い合わせに来ません。 377 | 378 | 今回は、以下のような `ONE_SEC` という定数を作って返しています。 379 | 380 | ``` 381 | const ONE_SEC: Timespec = Timespec{ 382 | sec: 1, 383 | nsec: 0 384 | }; 385 | ``` 386 | 387 | #### ATTR 388 | 対象のメタデータ。 `fuse::FileAttr` を返します。 389 | 390 | #### GENERATION 391 | inodeの世代情報を `u64` で返します。削除されたinodeに別のファイルを割り当てた場合、 392 | 前のファイルと違うファイルである事を示すために、generationに別の値を割り当てます。 393 | ただし、この値をチェックするのは(知られているものでは)nfsしかありません。 394 | 今回は常時 `0` に設定します。 395 | 396 | [libfuseの説明](https://libfuse.github.io/doxygen/structfuse__entry__param.html#a4c673ec62c76f7d63d326407beb1b463) 397 | も参考にしてください。 398 | 399 | #### エラー 400 | 401 | 対象のディレクトリエントリが存在しない場合、 `reply.error(ENOENT)` でエラーを返します。 402 | 403 | ### 実装 404 | 実装は以下のようになります。 405 | 406 | ```rust 407 | fn lookup(&mut self, _req: &Request, parent: u64, name: &OsStr, reply: ReplyEntry) { 408 | match self.db.lookup(parent as u32, name.to_str().unwrap()) { 409 | Ok(attr) => { 410 | reply.entry(&Timespec{sec: 1, nsec: 0}, &attr.get_file_attr() , 0); 411 | }, 412 | Err(_err) => reply.error(ENOENT) 413 | }; 414 | } 415 | ``` 416 | 417 | ## getattr 418 | ```rust 419 | fn getattr(&mut self, _req: &Request, ino: u64, reply: ReplyAttr); 420 | ``` 421 | 422 | 引数の `ino` でinode番号が指定されるので、ファイルのメタデータを返します。 423 | メタデータの内容については `lookup` で返す `ATTR` と同じです。 424 | 425 | ```rust 426 | fn getattr(&mut self, _req: &Request, ino: u64, reply: ReplyAttr) { 427 | match self.db.get_inode(ino as u32) { 428 | Ok(attr) => { 429 | reply.attr(&ONE_SEC, &attr.get_file_attr()); 430 | }, 431 | Err(_err) => reply.error(ENOENT) 432 | }; 433 | } 434 | ``` 435 | 436 | ## read 437 | ```rust 438 | fn read(&mut self, _req: &Request, ino: u64, _fh: u64, offset: i64, size: u32, reply: ReplyData); 439 | ``` 440 | 441 | 引数の `ino` のinode番号で指定されたファイルを、 `offset` で指定されたバイトから `size` で指定されたバイト分読み込みます。 442 | 読み込んだデータは `reply.data(&data)` を実行して返します。 443 | 444 | EOFまたはエラーを返す場合を除いて、 `read` 関数は引数の `size` で指定されたサイズのデータを返さないといけません。 445 | 例えば、長さ200byteのファイルに対して、4096byteの要求が来ることがあります。 446 | この場合EOFなので、200byte返す事が許されます。また、200byte以上返しても切り捨てられます。 447 | それ以外の場合で要求された長さのデータを用意できない場合は、エラーを返さないといけません。 448 | 449 | libfuseやfuse-rsの説明では、「もし要求されたサイズより短いサイズのデータを返した場合、0埋めされる」と書いてありますが、 450 | 手元の環境では0埋めされず、短いサイズが `read(2)` の結果として返ってきました。 451 | [カーネルのこのコミット](https://github.com/torvalds/linux/commit/5c5c5e51b26413d50a9efae2ca7d6c5c6cd453ac#diff-a00aec43f56686c876d5fec8bb227e10) 452 | で仕様が変わっているように見えます。 453 | 454 | 例外として、 `direct_io` をマウントオプションとして指定していた場合、または `direct_io` フラグを `open` の戻り値として指定した場合、 455 | カーネルは `read(2)` システムコールの戻り値としてファイルシステムの戻り値を直接使うので、ファイルシステムは実際に読み込んだ長さを返します。 456 | 諸事情(ストリーミングしてる等の理由)でファイルサイズと実際のデータの長さが異なる場合に、このオプションが利用できます。 457 | 458 | 引数の `fh` は `open` 時に戻り値としてファイルシステムが指定した値です。同じファイルに対して複数の `open` が来たときに、 459 | どの `open` に対しての `read` かを識別したり、ファイルオープン毎に状態を持つことができます。 460 | 今回は `open` を実装していないので常に0が来ます。 461 | 462 | ```rust 463 | fn read(&mut self, _req: &Request, ino: u64, _fh: u64, _offset: i64, _size: u32, reply: ReplyData) { 464 | let mut data: Vec = Vec::with_capacity(_size as usize); 465 | let block_size: u32 = self.db.get_db_block_size(); 466 | let mut size: u32 = _size; 467 | let mut offset: u32 = _offset as u32; 468 | // sizeが0になるまで1ブロックずつ読み込む 469 | while size > 0 { 470 | let mut b_data = match self.db.get_data(ino as u32, offset / block_size + 1, block_size) { 471 | Ok(n) => n, 472 | Err(_err) => {reply.error(ENOENT); return; } 473 | }; 474 | // ブロックの途中から読み込む、またはブロックの途中まで読む場合の対応 475 | let b_offset: u32 = offset % block_size; 476 | let b_end: u32 = if (size + b_offset) / block_size >= 1 {block_size} else {size + b_offset}; 477 | if b_data.len() < b_end as usize { 478 | b_data.resize(b_end as usize, 0); 479 | } 480 | data.append(&mut b_data[b_offset as usize..b_end as usize].to_vec()); 481 | offset += b_end - b_offset; 482 | size -= b_end - b_offset; 483 | } 484 | reply.data(&data); 485 | } 486 | ``` 487 | 488 | ## readdir 489 | ```rust 490 | fn readdir(&mut self, _req: &Request, ino: u64, _fh: u64, offset: i64, mut reply: ReplyDirectory); 491 | ``` 492 | 493 | 指定されたinodeのディレクトリのディレクトリエントリを返します。 494 | ディレクトリ内の全てのファイルまたはディレクトリの、 495 | 「名前」、「ファイル種別(ファイル/ディレクトリ/シンボリックリンク/etc.)」、「inode番号」を返します。 496 | `ls` コマンドの結果を返すイメージです。 497 | 一定サイズのバッファが渡されるので、一杯になるまでディレクトリエントリを入れて返します。 498 | 499 | 引数の `fh` は `opendir` でファイルシステムが渡した値です。今回は `opendir` を実装していないので0です。 500 | 501 | cでは `fuse_add_direntry()` という関数を使用してバッファを埋めますが、rustでは引数で渡された `reply: ReplyDirectory` を使用します。 502 | 具体的には以下のように使います。 503 | 504 | ```rust 505 | let target_inode = 11; // inode番号 506 | let filename = "test.txt"; // ファイル名 507 | let fileType = FileType.RegularFile; //ファイル種別 508 | result = reply.add(target_inode, offset, fileType, filename); 509 | ``` 510 | 511 | `reply.add()` でバッファにデータを追加していき、最終的に `reply.ok()` を実行すると、データが返せます。 512 | 513 | バッファが一杯の時、 `ReplyDirectory.add()` は `true` を返します。 514 | 515 | `reply.add()` の引数の `offset` はファイルシステムが任意に決めたオフセットです。 516 | 大抵はディレクトリエントリ一覧内のインデックスや次のエントリへのポインタ(cの場合)が使われます。 517 | 同じディレクトリエントリ内で `offset` は一意でなければなりません。また、offsetは決まった順番を持たなければなりません。 518 | カーネルが`readdir`の 引数として `offset` に0でない値を指定してきた場合、 519 | 該当の `offset` を持つディレクトリエントリの、次のディレクトリエントリを返さなければならないからです。 520 | `readdir` の引数に `0` が来た場合「最初のディレクトリエントリ」を返さないといけないので、ファイルシステムは `offset` に0を入れてはならないです。 521 | 522 | 厳密に実装する場合、 `opendir` 時の状態を返さないといけないので、 `opendir` の実装と状態の保持が必要になります。 523 | 524 | `.` と `..` は返さなくともよいですが、返さなかった場合の処理は呼び出し側のプログラムに依存します。 525 | 526 | ```rust 527 | fn readdir(&mut self, _req: &Request, ino: u64, _fh: u64, offset: i64, mut reply: ReplyDirectory) { 528 | let db_entries: Vec = match self.db.get_dentry(ino as u32) { 529 | Ok(n) => n, 530 | Err(err) => {reply.error(ENOENT); debug!("{}", err); return;} 531 | }; 532 | for (i, entry) in db_entries.into_iter().enumerate().skip(offset as usize) { 533 | let full = reply.add(entry.child_ino as u64, (i + 1) as i64, entry.file_type, &entry.filename); 534 | if full { 535 | break; 536 | } 537 | } 538 | reply.ok(); 539 | } 540 | ``` 541 | 542 | ## マウント 543 | main関数で `fuse::mount()` を実行すると、マウントできます。 544 | 545 | fuse-rsは [env_logger](https://github.com/sebasmagri/env_logger/) に対応しているので、最初に有効にしておきます。 546 | `RUST_LOG=debug [コマンド]` のように、環境変数でレベルを設定できます。 547 | `DEBUG` レベルにすると各関数の呼び出しを記録してくれます。 548 | 549 | 引数は雑に取得していますが、 550 | マウントオプションの処理などがあるので、後々 [clap](https://github.com/clap-rs/clap) などを使って解析することにします。 551 | 552 | ```rust 553 | fn main() { 554 | // ログを有効にする 555 | env_logger::init(); 556 | // 引数からマウントポイントを取得 557 | let mountpoint = env::args_os().nth(1).unwrap(); 558 | // 引数からDBファイルのパスを取得 559 | let db_path = env::args_os().nth(2).unwrap(); 560 | // マウントオプションの設定 561 | let options = ["-o", "ro", "-o", "fsname=sqlitefs"] 562 | .iter() 563 | .map(|o| o.as_ref()) 564 | .collect::>(); 565 | // ファイルシステムの初期化 566 | let fs: SqliteFs = match SqliteFs::new(db_path.to_str().unwrap()) { 567 | Ok(n) => n, 568 | Err(err) => {println!("{:?}", err); return;} 569 | }; 570 | // マウント 571 | fuse::mount(fs, &mountpoint, &options).unwrap(); 572 | } 573 | ``` 574 | 575 | ## 初期データ登録 576 | 自動でテーブルを作成する機能をまだ実装していません。初期化用の [init.sql](https://github.com/narumatt/sqlitefs/blob/hello/init.sql) と、 577 | hello.txt追加用の [hello.sql](https://github.com/narumatt/sqlitefs/blob/hello/hello.sql)` 578 | を作成して、実行してデータベースを作成します。 579 | 580 | ```text 581 | $ sqlite3 ~/filesystem.sqlite < init.sql 582 | $ sqlite3 ~/filesystem.sqlite < hello.sql 583 | ``` 584 | 585 | ## ビルド及び実行 586 | `[プログラム名] [マウント先] [データベースファイル名]` で実行できます。 587 | 588 | ```text:コマンド 589 | # バックグラウンドで実行 590 | $ ./sqlite-fs ~/mount ~/filesystem.sqlite & 591 | # lsしてhello.txtがあるのを確認 592 | $ ls ~/mount 593 | hello.txt 594 | # hello.txtの内容が読み込めることを確認 595 | $ cat ~/mount/hello.txt 596 | Hello World! 597 | ``` 598 | 599 | また、 `$ RUST_LOG=debug cargo run ~/mount` でビルドと実行( `~/mount` にマウントして、デバッグログを出力)ができます。 600 | 試しに `cat ~/mount/hello.txt` を実行すると、以下のようなログが出力されます。 `env_logger` のおかげで各関数に対する呼び出しが記録されています。 601 | 602 | ```text:ログ 603 | [2019-10-25T10:43:27Z DEBUG fuse::request] INIT(2) kernel: ABI 7.31, flags 0x3fffffb, max readahead 131072 604 | [2019-10-25T10:43:27Z DEBUG fuse::request] INIT(2) response: ABI 7.8, flags 0x1, max readahead 131072, max write 16777216 605 | [2019-10-25T10:43:42Z DEBUG fuse::request] LOOKUP(4) parent 0x0000000000000001, name "hello.txt" 606 | [2019-10-25T10:43:42Z DEBUG fuse::request] OPEN(6) ino 0x0000000000000002, flags 0x8000 607 | [2019-10-25T10:43:42Z DEBUG fuse::request] READ(8) ino 0x0000000000000002, fh 0, offset 0, size 4096 608 | [2019-10-25T10:43:42Z DEBUG fuse::request] FLUSH(10) ino 0x0000000000000002, fh 0, lock owner 12734418937618606797 609 | [2019-10-25T10:43:42Z DEBUG fuse::request] RELEASE(12) ino 0x0000000000000002, fh 0, flags 0x8000, release flags 0x0, lock owner 0 610 | ``` 611 | 612 | lookup -> open -> read -> close の順で関数が呼び出されている事が分かります。 613 | `close` に対応する関数である `flush` と `release` は実装していませんが、動作しています。 614 | 615 | ## ファイルシステムのアンマウント 616 | ファイルシステムは `fusermount -u [マウント先]` でアンマウントできます。アンマウントするとプログラムは終了します。 617 | `Ctrl + c` 等でプログラムを終了した場合でもマウントしたままになっているので、かならず `fusermount` を実行してください。 618 | 619 | ## まとめ 620 | 4つの関数を実装するだけで、Readonlyのファイルシステムが作成できました。 621 | 次回はファイルにデータの書き込みができるようにします。 622 | 623 | ここまでのコードは [github](https://github.com/narumatt/sqlitefs/tree/hello) に置いてあります。 624 | 625 | 626 | # ReadWrite 627 | ## 概要 628 | 前回は、ファイルの読み込みができるファイルシステムを作成しました。 629 | 今回は、それに加えてファイルの書き込みができるようにします。 630 | 631 | 必要なのは以下の関数です。 632 | 633 | ```rust 634 | fn write(&mut self, _req: &Request<'_>, _ino: u64, _fh: u64, _offset: i64, _data: &[u8], _flags: u32, reply: ReplyWrite) { 635 | ... 636 | } 637 | 638 | fn setattr(&mut self, _req: &Request<'_>, _ino: u64, _mode: Option, _uid: Option, _gid: Option, _size: Option, _atime: Option, _mtime: Option, _fh: Option, _crtime: Option, _chgtime: Option, _bkuptime: Option, _flags: Option, reply: ReplyAttr) { 639 | ... 640 | } 641 | ``` 642 | 643 | なお、以下では実装する関数と同名のシステムコールと区別をつけるために、 システムコールは `write(2)` のような表記をします。 644 | 645 | ## DB関数 646 | 今回追加したDB側の関数は以下になります。 647 | 648 | ``` 649 | /// inodeのメタデータを更新する。ファイルサイズが縮小する場合はtruncateをtrueにする 650 | fn update_inode(&self, attr: DBFileAttr, truncate: bool) -> Result<(), Error>; 651 | 652 | /// 1ブロック分のデータを書き込む 653 | fn write_data(&self, inode:u32, block: u32, data: &[u8], size: u32) -> Result<(), Error>; 654 | ``` 655 | 656 | ## write 657 | 658 | ```rust 659 | fn write(&mut self, _req: &Request<'_>, ino: u64, fh: u64, offset: i64, data: &[u8], flags: u32, reply: ReplyWrite); 660 | ``` 661 | 662 | 引数の `inode` で指定されたファイルに、引数の `data` で渡ってきたデータを書き込みます。 663 | 664 | `write(2)` のようなシステムコールを使う場合はファイルオフセットを意識する必要がありますが、 665 | FUSEではカーネルがオフセットの管理をしてくれているので、 `pwrite(2)` 相当の関数を一つ実装するだけで済むようになっています。 666 | 667 | マウントオプションに `direct_io` が設定されていない場合、エラーを返す場合を除いて、writeはsizeで指定された数字をreplyで返さないといけません。 668 | 指定されている場合は、実際に書き込んだバイト数を返します。 669 | 670 | 引数の `fh` は `open` 時にファイルシステムが指定した値です。今回はまだopenを実装していないので、常に0になります。 671 | 672 | また、 `open` 時のフラグに `O_APPEND` が設定されている場合は適切に処理しなければなりません。 673 | 674 | ちなみに、cpでファイルを上書きすると頭から後ろまで`write` 関数が実行されますが、 675 | アプリケーションによってはファイルの一部分だけ更新する、という処理はよく発生します。書き込みをキャッシュしたりしている場合は気をつけてください。 676 | 677 | ### O_APPEND 678 | ライトバックキャッシュが有効か無効かの場合で動作が異なります。 679 | マウントオプションに `-o writeback` がある場合、ライトバックキャッシュが有効になっています。 680 | 681 | ライトバックキャッシュが無効の時、ファイルシステムは `O_APPEND` を検知して、 682 | 全ての `write` の中で `offset` の値にかかわらずデータがファイル末尾に追記されるようにチェックします。 683 | 684 | ライトバックキャッシュが有効の時、 `offset` はカーネルが適切に設定してくれます。 `O_APPEND` は無視してください。 685 | 686 | (今のところ)カーネルは `offset` をきちんと設定してくれるようです。 687 | なので、現状は `O_APPEND` は無視し、 `open` 実装時に対応します。 688 | ただし、ネットワーク上のストレージを利用しているファイルシステムなどで複数のマシンから `O_APPEND` で書き込みがあった場合、カーネルの認知しているファイル末尾と 689 | 実際のファイル末尾がずれるので、問題が発生します。 690 | こういった問題が発生しうるファイルシステムを作る場合は、対処する必要があります。 691 | 692 | ### ここまでのコード 693 | ```rust 694 | fn write(&mut self, _req: &Request<'_>, ino: u64, _fh: u64, offset: i64, data: &[u8], flags: u32, reply: ReplyWrite) { 695 | let block_size = self.db.get_db_block_size(); 696 | let ino = ino as u32; 697 | let size = data.len() as u32; 698 | let offset = offset as u32; 699 | let start_block = offset / block_size + 1; 700 | let end_block = (offset + size - 1) / block_size + 1; 701 | // 各ブロックに書き込む 702 | for i in start_block..=end_block { 703 | let mut block_data: Vec = Vec::with_capacity(block_size as usize); 704 | let b_start_index = if i == start_block {offset % block_size} else {0}; 705 | let b_end_index = if i == end_block {(offset+size-1) % block_size +1} else {block_size}; 706 | let data_offset = (i - start_block) * block_size; 707 | 708 | // 書き込みがブロック全体に及ばない場合、一度ブロックのデータを読み込んで隙間を埋める 709 | if (b_start_index != 0) || (b_end_index != block_size) { 710 | let mut data_pre = match self.db.get_data(ino, i, block_size) { 711 | Ok(n) => n, 712 | Err(err) => {reply.error(ENOENT); debug!("{}", err); return;} 713 | }; 714 | if data_pre.len() < block_size as usize { 715 | data_pre.resize(block_size as usize, 0); 716 | } 717 | if b_start_index != 0 { 718 | block_data.extend_from_slice(&data_pre[0..b_start_index as usize]); 719 | } 720 | block_data.extend_from_slice(&data[data_offset as usize..(data_offset + b_end_index - b_start_index) as usize]); 721 | if b_end_index != block_size { 722 | block_data.extend_from_slice(&data_pre[b_end_index as usize..block_size as usize]); 723 | } 724 | } else { 725 | block_data.extend_from_slice(&data[data_offset as usize..(data_offset + block_size) as usize]); 726 | } 727 | // ここで書き込む 728 | match self.db.write_data(ino, i, &block_data, (i-1) * block_size + b_end_index) { 729 | Ok(n) => n, 730 | Err(err) => {reply.error(ENOENT); debug!("{}", err); return;} 731 | } 732 | } 733 | reply.written(size); 734 | } 735 | ``` 736 | 737 | ### マウントオプション 738 | `main.rs` のReadOnlyのマウントオプションを削除します。 739 | 740 | ``` 741 | let options = ["-o", "fsname=sqlitefs"] 742 | .iter() 743 | .map(|o| o.as_ref()) 744 | .collect::>(); 745 | ``` 746 | 747 | ### 実行結果 748 | - コマンド 749 | 750 | ``` 751 | // hello.txtに追記する 752 | $ echo "append" >> ~/mount/hello.txt 753 | // 追記された内容の確認 754 | $ cat ~/mount/hello.txt 755 | Hello world! 756 | append 757 | ``` 758 | 759 | - FUSEログ 760 | 761 | ``` 762 | [2019-10-28T11:52:08Z DEBUG fuse::request] INIT(2) kernel: ABI 7.31, flags 0x3fffffb, max readahead 131072 763 | [2019-10-28T11:52:08Z DEBUG fuse::request] INIT(2) response: ABI 7.8, flags 0x1, max readahead 131072, max write 16777216 764 | [2019-10-28T11:52:14Z DEBUG fuse::request] LOOKUP(4) parent 0x0000000000000001, name "hello.txt" 765 | [2019-10-28T11:52:14Z DEBUG fuse::request] OPEN(6) ino 0x0000000000000002, flags 0x8401 766 | [2019-10-28T11:52:14Z DEBUG fuse::request] FLUSH(8) ino 0x0000000000000002, fh 0, lock owner 9742156966771960265 767 | [2019-10-28T11:52:14Z DEBUG fuse::request] GETXATTR(10) ino 0x0000000000000002, name "security.capability", size 0 768 | [2019-10-28T11:52:14Z DEBUG fuse::request] WRITE(12) ino 0x0000000000000002, fh 0, offset 13, size 7, flags 0x0 769 | [2019-10-28T11:52:14Z DEBUG fuse::request] RELEASE(14) ino 0x0000000000000002, fh 0, flags 0x8401, release flags 0x0, lock owner 0 770 | ``` 771 | 772 | 773 | ## read, write時のメタデータの更新 774 | 一般的にファイルを `read` した時にはメタデータの `atime` を更新します。 775 | また、 `write` した時には、 `size` (必要な場合) `mtime` `ctime` の3つを更新します。 776 | DB関数側でこれらを更新できるようにしておきます。 777 | 778 | 今回はメタデータもデータもデータベース上にあり、元々パフォーマンスが悪い事が予想されるのであまり意識していませんが、 779 | メタデータの更新にある程度コストがかかる場合、ファイルサイズとタイムスタンプはメモリ上にキャッシュした方がいいです。 780 | キャッシュを書き込むのは `flush` が呼ばれたタイミングです。 781 | 782 | マウントオプションで `-o noatime` が指定された場合、 `atime` の更新は行いません。後々マウントオプションを追加する時に対応します。 783 | 784 | ### ファイルサイズ 785 | `write` 時に書き込まれたデータの末尾が、既存のファイルサイズより大きくなる場合は、ファイルサイズを更新する必要があります。 786 | また、書き込みのオフセットにファイルサイズより大きい値が指定された場合、ファイルに何も書かれていない穴ができます。 787 | このエリアのデータが読まれた場合、ファイルシステムは0(NULLバイト)の列を返します。 788 | 0埋めしたデータを書き込むか、そもそもその部分のデータを作らずに、読み込み時に検出して0のデータを返すようにします。 789 | 後者の方法はスパースファイルといい、見かけ上のファイルサイズより実ファイルサイズを小さくする事ができます。 790 | 791 | ファイルのブロックをばらばらの順番で書き込む、というのはよくある処理なので、0バイト目から順番に書き込まれていく事は期待しないでください。 792 | 特に `write` 実行時にファイルサイズを変更する場合は、現在のファイルサイズと比較して小さくならないように気をつけてください。 793 | 794 | ### タイムスタンプ 795 | 各関数とどのタイムスタンプを更新すべきかの対応表です。 796 | [Linuxプログラミングインターフェース](https://www.oreilly.co.jp/books/9784873115856/) 797 | のシステムコールとタイムスタンプの対応表を参考に、FUSEの関数にマップしました。 798 | 左側の `a, m, c` が操作対象のファイルまたはディレクトリのタイムスタンプ、 799 | 右側の `a, m, c` は親ディレクトリのタイムスタンプです。 800 | 801 | |関数名|a|m|c|親a|親m|親c|備考| 802 | |---|---|---|---|---|---|---|---| 803 | |setattr| | |o| | | | | 804 | |setattr(*)| |o|o| | | | * ファイルサイズが変わる場合 | 805 | |link| | |o| |o|o| | 806 | |mkdir|o|o|o| |o|o| | 807 | |mknod|o|o|o| |o|o| | 808 | |create|o|o|o| |o|o| | 809 | |read|o| | | | | | | 810 | |readdir|o| | | | | | | 811 | |setxattr| | |o| | | | | 812 | |removexattr| | |o| | | | | 813 | |rename| | |o| |o|o|移動前/移動後の両方の親ディレクトリを変更| 814 | |rmdir| | | | |o|o| | 815 | |symlink|o|o|o| |o|o|リンク自体のタイムスタンプで、リンク先は変更しない| 816 | |unlink| | |o| |o|o|参照カウントが2以上でinode自体が消えない場合、ファイルのctimeを更新| 817 | |write| |o|o| | | | | 818 | 819 | ## setattr 820 | 821 | ```rust 822 | fn setattr(&mut self, _req: &Request<'_>, ino: u64, mode: Option, uid: Option, gid: Option, size: Option, atime: Option, mtime: Option, fh: Option, crtime: Option, chgtime: Option, bkuptime: Option, flags: Option, reply: ReplyAttr); 823 | ``` 824 | 825 | `write` は実装しましたが、このままでは追記しかできません。 826 | ファイルを丸ごと更新するために、ファイルサイズを0にする(truncateに相当) 処理を実装します。 827 | 828 | fuse-rsでは、 `setattr` を実装する事でファイルサイズの変更が可能になります。 829 | ついでに `setattr` で変更できる全てのメタデータを変更できるようにします。 830 | 831 | `truncate(2)` でファイルサイズを変更する時と、 `open(2)` で `O_TRUNC` を指定した時も、この関数が呼ばれます。 832 | 833 | `setattr` は各引数に `Option` 型で値が指定されるので、中身がある場合はその値で更新していきます。 834 | `reply` に入れる値は、更新後のメタデータです。 835 | 836 | なお、 `ctime` は 現在のfuse-rsがプロトコルのバージョンの問題で未対応なので、引数には入っていません。 837 | 基本的に `ctime` は自由に設定する事ができず、 `setattr` を実行すると現在時刻になるはずなので、問題はありません。 838 | 839 | `open` 時に `O_TRUNC` を指定した場合のように、ファイルサイズに0が指定された場合は既存のデータを全て破棄すればいいですが、 840 | `truncate(2)` で元のファイルサイズより小さい0以外の値が指定された場合、 841 | 残すべきデータは残しつついらないデータがきちんと破棄されるように気をつけてください。 842 | また、元のファイルサイズより大きい値が指定された場合、間のデータが0(\0)で埋められるようにしてください。 843 | 844 | macOS用に `chgtime` と `bkuptime` が引数にありますが、今回はスルーします。 845 | 846 | ```rust 847 | fn setattr( 848 | &mut self, 849 | _req: &Request<'_>, 850 | ino: u64, 851 | mode: Option, 852 | uid: Option, 853 | gid: Option, 854 | size: Option, 855 | atime: Option, 856 | mtime: Option, 857 | _fh: Option, 858 | crtime: Option, 859 | _chgtime: Option, 860 | _bkuptime: Option, 861 | flags: Option, 862 | reply: ReplyAttr 863 | ) { 864 | // 現在のメタデータを取得 865 | let mut attr = match self.db.get_inode(ino as u32) { 866 | Ok(n) => n, 867 | Err(err) => {reply.error(ENOENT); debug!("{}", err); return;} 868 | }; 869 | // ファイルサイズの変更チェック 870 | let old_size = attr.size; 871 | // 引数で上書き 872 | if let Some(n) = mode {attr.perm = n as u16}; 873 | if let Some(n) = uid {attr.uid = n}; 874 | if let Some(n) = gid {attr.gid = n}; 875 | if let Some(n) = size {attr.size = n as u32}; 876 | if let Some(n) = atime {attr.atime = datetime_from_timespec(&n)}; 877 | if let Some(n) = mtime {attr.mtime = datetime_from_timespec(&n)}; 878 | if let Some(n) = crtime {attr.crtime = datetime_from_timespec(&n)}; 879 | if let Some(n) = flags {attr.flags = n}; 880 | // 更新 881 | match self.db.update_inode(attr, old_size > attr.size) { 882 | Ok(_n) => (), 883 | Err(err) => {reply.error(ENOENT); debug!("{}", err); return;} 884 | }; 885 | reply.attr(&ONE_SEC, &attr.get_file_attr()); 886 | } 887 | ``` 888 | 889 | 実行結果は以下のようになります。 890 | 891 | ``` 892 | $ echo "Update hello world" > ~/mount/hello.txt 893 | $ cat ~/mount/hello.txt 894 | Update hello world 895 | ``` 896 | 897 | ``` 898 | [2019-10-28T12:08:10Z DEBUG fuse::request] INIT(2) kernel: ABI 7.31, flags 0x3fffffb, max readahead 131072 899 | [2019-10-28T12:08:10Z DEBUG fuse::request] INIT(2) response: ABI 7.8, flags 0x1, max readahead 131072, max write 16777216 900 | [2019-10-28T12:08:37Z DEBUG fuse::request] LOOKUP(4) parent 0x0000000000000001, name "hello.txt" 901 | [2019-10-28T12:08:37Z DEBUG fuse::request] OPEN(6) ino 0x0000000000000002, flags 0x8001 902 | [2019-10-28T12:08:37Z DEBUG fuse::request] GETXATTR(8) ino 0x0000000000000002, name "security.capability", size 0 903 | [2019-10-28T12:08:37Z DEBUG fuse::request] SETATTR(10) ino 0x0000000000000002, valid 0x208 904 | [2019-10-28T12:08:37Z DEBUG fuse::request] FLUSH(12) ino 0x0000000000000002, fh 0, lock owner 17171727478964840688 905 | [2019-10-28T12:08:37Z DEBUG fuse::request] WRITE(14) ino 0x0000000000000002, fh 0, offset 0, size 19, flags 0x0 906 | [2019-10-28T12:08:37Z DEBUG fuse::request] RELEASE(16) ino 0x0000000000000002, fh 0, flags 0x8001, release flags 0x0, lock owner 0 907 | 908 | ``` 909 | 910 | ## まとめ 911 | これでファイルの書き込み(追記、上書き)ができるようになりました。 912 | 次回は、ファイルの作成と削除を実装します。 913 | 914 | # ファイルの作成と削除 915 | ## 概要 916 | ルートディレクトリ上にファイルの作成と削除が行えるようにします。 917 | 918 | 必要なのは以下の関数です。 919 | 920 | ``` 921 | fn init(&mut self, _req: &Request<'_>) -> Result<(), c_int> { 922 | ... 923 | } 924 | fn destroy(&mut self, _req: &Request<'_>) { 925 | ... 926 | } 927 | fn lookup(&mut self, _req: &Request, parent: u64, name: &OsStr, reply: ReplyEntry){ 928 | ...(既存のコードに追加) 929 | } 930 | fn forget(&mut self, _req: &Request<'_>, _ino: u64, _nlookup: u64) { 931 | ... 932 | } 933 | fn unlink(&mut self, _req: &Request<'_>, _parent: u64, _name: &OsStr, reply: ReplyEmpty) { 934 | ... 935 | } 936 | fn create(&mut self, _req: &Request<'_>, _parent: u64, _name: &OsStr, _mode: u32, _flags: u32, reply: ReplyCreate) { 937 | ... 938 | } 939 | ``` 940 | 941 | ファイルを作成する関数は `create` 、削除する関数は `unlink` ですが、 `lookup count` の都合で追加でいろいろ実装する必要があります。 942 | 943 | ## lookup count 944 | ファイル削除に絡む関数を実装する場合、 `lookup count` に注意する必要があります。 945 | 946 | 以下では lookup count と参照カウントという2種類の言葉を使っていますが、 947 | 大まかに説明すると、lookup count はいくつのプロセスがファイルを開いているか(または開く予定か)、 948 | 参照カウントはファイルがいくつハードリンクされているか、を示しています。 949 | 950 | `lib.rs` や `fuse_lowlevel.h` によると、 951 | 「lookup count が0でない内は、unlink, rmdir, rename(で上書き)されて参照カウントが0になってもinodeを削除しないでね」という事です。 952 | lookup countは最初は0で、ReplyEntryとReplyCreateがある全ての関数が呼ばれるたびに、1ずつ増やしていきます。 953 | 具体的には、 `lookup`, `mknod`, `mkdir`, `symlink`, `link`, `create` が実行されると1増えます。 954 | 955 | `forget` はlookup countを減らす関数です。 `forget` でlookup countが0になるまでは、ファイルシステムは削除を遅らせる必要があります。 956 | 例えば、カーネルはまだファイルをOpenしているプロセスがあると、 `forget` をファイルが閉じられるまで遅延させます。 957 | これにより、「別の誰かがファイルを削除して `ls` 等でファイルを見つけられなくなるが、削除前からファイルを開いていた場合は読み込み続ける事ができる」というアレが実現できます。 958 | 959 | lookup countを実装するために、ファイルシステムの構造体に次の変数を追加します。 960 | 961 | ```rust 962 | pub struct SqliteFs{ 963 | /// DBとやり取りする 964 | db: Sqlite, 965 | /// lookup countを保持する 966 | lookup_count: Mutex> 967 | } 968 | ``` 969 | 970 | keyがinode番号、valueがlookup count、であるHashMapを作成します。 971 | 972 | ## 追加したDB関数 973 | 今回は以下のようなDB関数を追加しました。 974 | 975 | ```rust 976 | /// ファイル/ディレクトリのinodeを追加し、新しく割り振ったinode番号を返す。 引数attrのinoは無視される。 977 | fn add_inode(&mut self, parent: u32, name: &str, attr: &DBFileAttr) -> Result; 978 | /// inodeをチェックし、参照カウントが0なら削除する 979 | fn delete_inode_if_noref(&mut self, inode: u32) -> Result<(), Error>; 980 | /// 親ディレクトリのinode番号、ファイル/ディレクトリ名で指定されたディレクトリエントリを削除し、 981 | /// 該当のinodeの参照カウントを1減らす 982 | /// 削除したファイル/ディレクトリのinode番号を返す 983 | fn delete_dentry(&mut self, parent: u32, name: &str) -> Result; 984 | /// 参照カウントが0である全てのinodeを削除する 985 | fn delete_all_noref_inode(&mut self) -> Result<(), Error>; 986 | ``` 987 | 988 | ## lookup 989 | `lookup` 関数を更新します。 990 | 関数が実行されるたびに、lookupで情報を持ってくる対象のファイル/ディレクトリのlookup countに1を足すようにします。 991 | 992 | コードは以下のようになります。 993 | 994 | ```rust 995 | fn lookup(&mut self, _req: &Request, parent: u64, name: &OsStr, reply: ReplyEntry) { 996 | // 既存のコード 997 | let parent = parent as u32; 998 | let child = match self.db.lookup(parent, name.to_str().unwrap()) { 999 | Ok(n) => { 1000 | if n.ino == 0 { 1001 | reply.error(ENOENT); 1002 | return; 1003 | } 1004 | reply.entry(&ONE_SEC, &n.get_file_attr() , 0); 1005 | n.ino 1006 | }, 1007 | Err(err) => {reply.error(ENOENT); debug!("{}", err); return;} 1008 | }; 1009 | 1010 | // *update* lookup countに1を足す。HashMapにkeyが無い場合は追加する 1011 | let mut lc_list = self.lookup_count.lock().unwrap(); 1012 | let lc = lc_list.entry(child).or_insert(0); 1013 | *lc += 1; 1014 | } 1015 | ``` 1016 | 1017 | ## create 1018 | 1019 | ```rust 1020 | fn create(&mut self, _req: &Request<'_>, parent: u64, name: &OsStr, mode: u32, flags: u32, reply: ReplyCreate); 1021 | ``` 1022 | 1023 | 引数の `parent` のinode番号で指定されたディレクトリ内の、 `name` で指定されたファイル名を持つファイルを作成します。 1024 | 1025 | `creat(2)` または `O_CREAT` を指定した `open(2)` 実行時に呼ばれます。 1026 | 1027 | 指定されたファイルが存在しない場合、引数の `mode` で指定されたモードでファイルを作成し、ファイルを開きます。 1028 | ファイルのオーナーに設定するユーザ、グループは、引数の `req` から `req.uid()` `req.gid()` で取得できます。 1029 | ただし、マウントオプションで `–o grpid` または `–o bsdgroups` が指定されている場合や、親ディレクトリにsgidが設定されている場合( `libc::S_ISGID` で判定)は、 1030 | 親ディレクトリと同じグループを設定しないといけません。 1031 | 1032 | ファイルが既に存在する場合、openと同じ動作を行います。 1033 | 1034 | ファイルを作成する以外は `open` と同じ動作のため、open時のフラグが `flags` で渡されます。 1035 | 1036 | `creat(2)` や `open(2)` ではフラグに `O_EXCL` が指定されている場合、指定した名前のファイルが既に存在するとエラーにしなければなりませんが、 1037 | この処理はカーネルがやってくれているようです。 1038 | 1039 | `create` が実装されていない場合、カーネルは `mknod` と `open` を実行します。 1040 | 1041 | なお、`create` が実装されている場合、libfuseは通常ファイルの `mknod` が実行されると `create` を呼び出しますが、 1042 | fuse-rsは呼び出してくれません。 1043 | 1044 | 実装したコードは以下のようになります。 1045 | 1046 | ```rust 1047 | fn create( 1048 | &mut self, 1049 | req: &Request<'_>, 1050 | parent: u64, 1051 | name: &OsStr, 1052 | mode: u32, 1053 | _flags: u32, 1054 | reply: ReplyCreate 1055 | ) { 1056 | let ino; 1057 | let parent = parent as u32; 1058 | let name = name.to_str().unwrap(); 1059 | // ファイルが既にあるかチェックする 1060 | let mut attr = match self.db.lookup(parent, name) { 1061 | Ok(n) => n, 1062 | Err(err) => {reply.error(ENOENT); debug!("{}", err); return;} 1063 | }; 1064 | if attr.ino == 0 { 1065 | // ファイル作成 1066 | let now = SystemTime::now(); 1067 | attr = DBFileAttr { 1068 | ino: 0, // 無視されるので0にする 1069 | size: 0, 1070 | blocks: 0, 1071 | atime: now, 1072 | mtime: now, 1073 | ctime: now, 1074 | crtime: now, 1075 | kind: FileType::RegularFile, 1076 | perm: mode as u16, 1077 | nlink: 0, 1078 | uid: req.uid(), 1079 | gid: req.gid(), 1080 | rdev: 0, 1081 | flags: 0 1082 | }; 1083 | ino = match self.db.add_inode(parent, name, &attr) { 1084 | Ok(n) => n, 1085 | Err(err) => { 1086 | reply.error(ENOENT); 1087 | debug!("{}", err); 1088 | return; 1089 | } 1090 | }; 1091 | attr.ino = ino; 1092 | } else { 1093 | ino = attr.ino; 1094 | } 1095 | // createもlookup countを+1する 1096 | let mut lc_list = self.lookup_count.lock().unwrap(); 1097 | let lc = lc_list.entry(ino).or_insert(0); 1098 | *lc += 1; 1099 | reply.created(&ONE_SEC, &attr.get_file_attr(), 0, 0, 0); 1100 | } 1101 | ``` 1102 | 1103 | ## unlink 1104 | 1105 | ```rust 1106 | fn unlink(&mut self, _req: &Request<'_>, parent: u64, name: &OsStr, reply: ReplyEmpty); 1107 | ``` 1108 | 1109 | 親ディレクトリのinode番号が引数の `parent`, 削除対象のファイル/ディレクトリの名前が `name` で指定されるので、 1110 | ファイルまたはディレクトリを削除します。 1111 | 1112 | 削除対象はディレクトリエントリと、該当のinodeのメタデータです。 1113 | ただし、inodeはハードリンクされて複数のディレクトリエントリから参照されている可能性があるので、参照カウント( `nlink` ) を1減らし、0になった場合に削除します。 1114 | また、 lookup count をチェックし、0になっていない場合は即座に削除を行いません。 1115 | 1116 | ```rust 1117 | fn unlink(&mut self, _req: &Request<'_>, parent: u64, name: &OsStr, reply: ReplyEmpty) { 1118 | // ディレクトリエントリを削除しつつ、対象のinode番号を得る 1119 | let ino = match self.db.delete_dentry(parent as u32, name.to_str().unwrap()) { 1120 | Ok(n) => n, 1121 | Err(err) => {reply.error(ENOENT); debug!("{}", err); return;} 1122 | }; 1123 | // lookup countのチェック 1124 | let lc_list = self.lookup_count.lock().unwrap(); 1125 | if !lc_list.contains_key(&ino) { 1126 | // 参照カウントが0の場合削除する。そうでない場合、unlink 内では削除しない 1127 | match self.db.delete_inode_if_noref(ino) { 1128 | Ok(n) => n, 1129 | Err(err) => {reply.error(ENOENT); debug!("{}", err); return;} 1130 | }; 1131 | } 1132 | reply.ok(); 1133 | } 1134 | ``` 1135 | 1136 | ## forget 1137 | 1138 | ```rust 1139 | fn forget(&mut self, _req: &Request<'_>, _ino: u64, _nlookup: u64); 1140 | ``` 1141 | 1142 | lookup countを減らします。 1143 | 1144 | 引数の `ino` で対象のinode番号、 `nlookup` で減らす数が指定されます。 1145 | inodeの削除が遅延されている場合、lookup countが0になったタイミングで削除します。 1146 | 1147 | ```rust 1148 | fn forget(&mut self, _req: &Request<'_>, ino: u64, nlookup: u64) { 1149 | let ino = ino as u32; 1150 | // lookup countのチェック 1151 | let mut lc_list = self.lookup_count.lock().unwrap(); 1152 | let lc = lc_list.entry(ino).or_insert(0); 1153 | *lc -= nlookup as u32; 1154 | if *lc == 0 { 1155 | // 0(以下)になった場合、lookup countの一覧から削除する 1156 | lc_list.remove(&ino); 1157 | // 参照カウントが0でinodeの削除が遅延されていた場合、改めて削除する 1158 | match self.db.delete_inode_if_noref(ino) { 1159 | Ok(n) => n, 1160 | Err(err) => debug!("{}", err) 1161 | } 1162 | } 1163 | } 1164 | ``` 1165 | 1166 | ## destroy 1167 | 1168 | ```rust 1169 | fn destroy(&mut self, _req: &Request<'_>); 1170 | ``` 1171 | 1172 | ファイルシステムの終了時に呼ばれる関数です。 1173 | 1174 | ファイルシステムのアンマウント時には、全ての lookup count が0になる事が期待されます。 1175 | 一方、 `forget` が呼ばれる事は保証されていないので、ファイルシステムが自分でチェックする必要があります。 1176 | 1177 | ```rust 1178 | fn destroy(&mut self, _req: &Request<'_>) { 1179 | let lc_list = self.lookup_count.lock().unwrap(); 1180 | // lookup countが残っている全てのinodeをチェック 1181 | for key in lc_list.keys() { 1182 | // 参照カウントが0でinodeの削除が遅延されていた場合、改めて削除する 1183 | match self.db.delete_inode_if_noref(*key) { 1184 | Ok(n) => n, 1185 | Err(err) => debug!("{}", err) 1186 | } 1187 | } 1188 | } 1189 | ``` 1190 | 1191 | ## init 1192 | 1193 | ```rust 1194 | fn init(&mut self, _req: &Request<'_>) -> Result<(), c_int>; 1195 | ``` 1196 | 1197 | ファイルシステムのマウント時に最初に呼ばれる関数です。 1198 | 1199 | 何らかの事情で `destroy` が呼ばれずにファイルシステムが突然終了した場合、参照カウントが0のままのinodeが残り続ける事になるので、 1200 | チェックして削除します。 1201 | 1202 | ```rust 1203 | fn init(&mut self, _req: &Request<'_>) -> Result<(), c_int> { 1204 | match self.db.delete_all_noref_inode() { 1205 | Ok(n) => n, 1206 | Err(err) => debug!("{}", err) 1207 | }; 1208 | Ok(()) 1209 | } 1210 | ``` 1211 | 1212 | ## 実行結果 1213 | ### ファイル作成 1214 | 1215 | - コマンド 1216 | 1217 | ``` 1218 | # ファイル作成 1219 | $ touch ~/mount/touch.txt 1220 | # ファイル作成 + 書き込み 1221 | $ echo "created" > ~/mount/test.txt 1222 | # ファイル作成の確認 1223 | $ ls ~/mount 1224 | hello.txt test.txt touch.txt 1225 | # 書き込み内容の確認 1226 | $ cat ~/mount/test.txt 1227 | created 1228 | ``` 1229 | 1230 | - FUSEログ 1231 | 1232 | ``` 1233 | [2019-10-30T11:21:59Z DEBUG fuse::request] INIT(2) kernel: ABI 7.31, flags 0x3fffffb, max readahead 131072 1234 | [2019-10-30T11:21:59Z DEBUG fuse::request] INIT(2) response: ABI 7.8, flags 0x1, max readahead 131072, max write 16777216 1235 | // touch ~/mount/touch.txt 1236 | [2019-10-30T11:22:14Z DEBUG fuse::request] LOOKUP(4) parent 0x0000000000000001, name "touch.txt" 1237 | [2019-10-30T11:22:14Z DEBUG fuse::request] CREATE(6) parent 0x0000000000000001, name "touch.txt", mode 0o100664, flags 0x8841 1238 | [2019-10-30T11:22:14Z DEBUG fuse::request] FLUSH(8) ino 0x0000000000000003, fh 0, lock owner 16194556409419452441 1239 | [2019-10-30T11:22:14Z DEBUG fuse::request] SETATTR(10) ino 0x0000000000000003, valid 0x1b0 1240 | [2019-10-30T11:22:14Z DEBUG fuse::request] RELEASE(12) ino 0x0000000000000003, fh 0, flags 0x8801, release flags 0x0, lock owner 0 1241 | // echo "created" > ~/mount/test.txt 1242 | [2019-10-30T11:22:28Z DEBUG fuse::request] LOOKUP(14) parent 0x0000000000000001, name "test.txt" 1243 | [2019-10-30T11:22:28Z DEBUG fuse::request] CREATE(16) parent 0x0000000000000001, name "test.txt", mode 0o100664, flags 0x8241 1244 | [2019-10-30T11:22:29Z DEBUG fuse::request] GETXATTR(18) ino 0x0000000000000004, name "security.capability", size 0 1245 | [2019-10-30T11:22:29Z DEBUG fuse::request] WRITE(20) ino 0x0000000000000004, fh 0, offset 0, size 8, flags 0x0 1246 | [2019-10-30T11:22:29Z DEBUG fuse::request] RELEASE(22) ino 0x0000000000000004, fh 0, flags 0x8001, release flags 0x0, lock owner 0 1247 | ``` 1248 | 1249 | ### ファイル削除 1250 | 1251 | - コマンド 1252 | 1253 | ``` 1254 | $ rm ~/mount/test.txt 1255 | $ ls ~/mount/test.txt 1256 | ls: cannot access '/home/jiro/mount/test.txt': No such file or directory 1257 | ``` 1258 | 1259 | - FUSEログ 1260 | 1261 | ``` 1262 | [2019-10-30T05:32:26Z DEBUG fuse::request] LOOKUP(48) parent 0x0000000000000001, name "test.txt" 1263 | [2019-10-30T05:32:26Z DEBUG fuse::request] ACCESS(50) ino 0x0000000000000004, mask 0o002 1264 | [2019-10-30T05:32:26Z DEBUG fuse::request] UNLINK(52) parent 0x0000000000000001, name "test.txt" 1265 | [2019-10-30T05:32:26Z DEBUG fuse::request] FORGET(54) ino 0x0000000000000004, nlookup 4 1266 | ``` 1267 | 1268 | ## まとめ 1269 | ファイルの作成、削除が問題なくできるようになりました。 1270 | 次回は、ディレクトリの作成/削除ができるようにします。 1271 | 1272 | # ディレクトリの作成/削除 1273 | ## 概要 1274 | 今まではルートディレクトリのみでファイル操作を行っていましたが、 1275 | 今回はディレクトリの作成/削除を実装して、サブディレクトリでいろいろできるようにします。 1276 | 1277 | ## 実装すべき関数 1278 | ```rust 1279 | fn mkdir(&mut self, req: &Request<'_>, parent: u64, name: &OsStr, mode: u32, reply: ReplyEntry) { 1280 | ... 1281 | } 1282 | fn rmdir(&mut self, _req: &Request<'_>, _parent: u64, _name: &OsStr, reply: ReplyEmpty) { 1283 | ... 1284 | } 1285 | ``` 1286 | 1287 | ## 追加したDB関数 1288 | 1289 | ```rust 1290 | /// ディレクトリが空かチェックする 1291 | fn check_directory_is_empty(&self, inode: u32) -> Result; 1292 | ``` 1293 | 1294 | ## mkdir 1295 | ```rust 1296 | fn mkdir(&mut self, req: &Request<'_>, parent: u64, name: &OsStr, mode: u32, reply: ReplyEntry); 1297 | ``` 1298 | 1299 | 引数の `parent` で親ディレクトリのinode番号、 `name` で作成するディレクトリ名、 `mode` でモードが指定されるので、ディレクトリを作成します。 1300 | 成功した場合、作成したディレクトリのメタデータを返します。 1301 | 1302 | 作成したユーザ、グループは、引数の `req` から `req.uid()` `req.gid()` で取得できます。 1303 | ただし、マウントオプションで `–o grpid` または `–o bsdgroups` が指定されている場合や、親ディレクトリにsgidが設定されている場合は、 1304 | 親ディレクトリと同じグループを設定しないといけません。 1305 | 1306 | また、親ディレクトリにSUIDが設定されていても、SUIDはディレクトリには関係ないので子ディレクトリは無視します。 1307 | SGID, スティッキービットが設定されている場合、子ディレクトリにも引き継がないといけません。 1308 | この辺りは処理系定義なので、Linux以外のシステムで、常にディレクトリ作成時にはoffにするものもあるようです。 1309 | 1310 | 既に同名のディレクトリやファイルがあるかどうか、はカーネル側でチェックしてくれているようです。 1311 | 1312 | `mkdir` のコードは以下のようになります。 1313 | 1314 | ```rust 1315 | fn mkdir(&mut self, req: &Request<'_>, parent: u64, name: &OsStr, mode: u32, reply: ReplyEntry) { 1316 | let now = SystemTime::now(); 1317 | // 初期メタデータ 1318 | let mut attr = DBFileAttr { 1319 | ino: 0, 1320 | size: 0, 1321 | blocks: 0, 1322 | atime: now, 1323 | mtime: now, 1324 | ctime: now, 1325 | crtime: now, 1326 | kind: FileType::Directory, 1327 | perm: mode as u16, 1328 | nlink: 0, 1329 | uid: req.uid(), 1330 | gid: req.gid(), 1331 | rdev: 0, 1332 | flags: 0 1333 | }; 1334 | // ディレクトリを作成してinode番号を取得 1335 | let ino = match self.db.add_inode(parent as u32, name.to_str().unwrap(), &attr) { 1336 | Ok(n) => n, 1337 | Err(err) => {reply.error(ENOENT); debug!("{}", err); return;} 1338 | }; 1339 | // inode番号を入れてメタデータを返却 1340 | attr.ino = ino; 1341 | reply.entry(&ONE_SEC, &attr.get_file_attr(), 0); 1342 | // lookup countを増やす 1343 | let mut lc_list = self.lookup_count.lock().unwrap(); 1344 | let lc = lc_list.entry(ino).or_insert(0); 1345 | *lc += 1; 1346 | } 1347 | ``` 1348 | 1349 | ## rmdir 1350 | ```rust 1351 | fn rmdir(&mut self, _req: &Request<'_>, parent: u64, name: &OsStr, reply: ReplyEmpty); 1352 | ``` 1353 | 1354 | 引数の `parent` で親ディレクトリのinode番号が、 `name` でディレクトリ名が指定されるので、ディレクトリを削除します。 1355 | 1356 | ディレクトリ内になにかある場合は削除できません。 1357 | カーネル側で確認はしてくれないようなので、ファイルシステム側でチェックを行い、ディレクトリが空ではない( `.` と `..` 以外のエントリがある) 場合はエラーを返します。 1358 | `rmdir(2)` のmanページによると、 `ENOTEMPTY` または `EEXIST` を返します。Linuxファイルシステムでは `ENOTEMPTY` がメジャーのようです。 1359 | 1360 | `unlink` と同様に、 `lookup count` が0でない場合、0になるタイミングまでinodeの削除を遅延します。 1361 | 今回のプログラムでは、 `forget` 等の内部でファイルとディレクトリの区別をしていないので、現状の実装でOKです。 1362 | 1363 | ```rust 1364 | fn rmdir(&mut self, _req: &Request<'_>, parent: u64, name: &OsStr, reply: ReplyEmpty) { 1365 | let parent = parent as u32; 1366 | let name = name.to_str().unwrap(); 1367 | let attr = match self.db.lookup(parent, name) { 1368 | Ok(n) => n, 1369 | Err(err) => {reply.error(ENOENT); debug!("{}", err); return;} 1370 | }; 1371 | // ディレクトリが空かどうかチェック 1372 | let empty = match self.db.check_directory_is_empty(attr.ino){ 1373 | Ok(n) => n, 1374 | Err(err) => {reply.error(ENOENT); debug!("{}", err); return;} 1375 | }; 1376 | if !empty { 1377 | reply.error(ENOTEMPTY); 1378 | return; 1379 | } 1380 | // dentry削除 1381 | let ino = match self.db.delete_dentry(parent, name) { 1382 | Ok(n) => n, 1383 | Err(err) => {reply.error(ENOENT); debug!("{}", err); return;} 1384 | }; 1385 | // lookup countの処理 1386 | let lc_list = self.lookup_count.lock().unwrap(); 1387 | if !lc_list.contains_key(&ino) { 1388 | match self.db.delete_inode_if_noref(ino) { 1389 | Ok(n) => n, 1390 | Err(err) => { 1391 | reply.error(ENOENT); 1392 | debug!("{}", err); 1393 | return; 1394 | } 1395 | }; 1396 | } 1397 | reply.ok(); 1398 | } 1399 | ``` 1400 | 1401 | ## 実行結果 1402 | ここまでの実行結果は以下のようになります。 1403 | 1404 | ```shell script 1405 | # ディレクトリ作成 1406 | $ mkdir ~/mount/testdir/ 1407 | $ echo "test" > ~/mount/testdir/test.txt 1408 | # 中身のあるディレクトリは削除できないことの確認 1409 | $ rmdir ~/mount/testdir 1410 | rmdir: failed to remove '/home/jiro/mount/testdir': Directory not empty 1411 | $ rm ~/mount/testdir/test.txt 1412 | # ディレクトリ削除 1413 | $ rmdir ~/mount/testdir 1414 | ``` 1415 | 1416 | ``` 1417 | // mkdir ~/mount/testdir/ 1418 | [2019-10-31T06:15:19Z DEBUG fuse::request] GETATTR(146) ino 0x0000000000000001 1419 | [2019-10-31T06:15:32Z DEBUG fuse::request] LOOKUP(148) parent 0x0000000000000001, name "testdir" 1420 | [2019-10-31T06:15:32Z DEBUG fuse::request] MKDIR(150) parent 0x0000000000000001, name "testdir", mode 0o775 1421 | [2019-10-31T06:15:32Z DEBUG fuse::request] GETATTR(152) ino 0x0000000000000001 1422 | // echo "test" > ~/mount/testdir/test.txt 1423 | [2019-10-31T06:15:56Z DEBUG fuse::request] LOOKUP(154) parent 0x0000000000000001, name "testdir" 1424 | [2019-10-31T06:15:56Z DEBUG fuse::request] LOOKUP(156) parent 0x0000000000000004, name "test.txt" 1425 | [2019-10-31T06:15:56Z DEBUG fuse::request] CREATE(158) parent 0x0000000000000004, name "test.txt", mode 0o100664, flags 0x8241 1426 | [2019-10-31T06:15:56Z DEBUG fuse::request] WRITE(160) ino 0x0000000000000005, fh 0, offset 0, size 5, flags 0x0 1427 | [2019-10-31T06:15:56Z DEBUG fuse::request] RELEASE(162) ino 0x0000000000000005, fh 0, flags 0x8001, release flags 0x0, lock owner 0 1428 | [2019-10-31T06:15:56Z DEBUG fuse::request] GETATTR(164) ino 0x0000000000000001 1429 | // rmdir(1回目) 1430 | [2019-10-31T06:16:07Z DEBUG fuse::request] LOOKUP(166) parent 0x0000000000000001, name "testdir" 1431 | [2019-10-31T06:16:07Z DEBUG fuse::request] RMDIR(168) parent 0x0000000000000001, name "testdir" 1432 | [2019-10-31T06:16:07Z DEBUG fuse::request] GETATTR(170) ino 0x0000000000000001 1433 | // rm test.txt 1434 | [2019-10-31T06:16:24Z DEBUG fuse::request] LOOKUP(174) parent 0x0000000000000001, name "testdir" 1435 | [2019-10-31T06:16:24Z DEBUG fuse::request] LOOKUP(176) parent 0x0000000000000004, name "test.txt" 1436 | [2019-10-31T06:16:24Z DEBUG fuse::request] ACCESS(178) ino 0x0000000000000005, mask 0o002 1437 | [2019-10-31T06:16:24Z DEBUG fuse::request] UNLINK(180) parent 0x0000000000000004, name "test.txt" 1438 | [2019-10-31T06:16:24Z DEBUG fuse::request] FORGET(182) ino 0x0000000000000005, nlookup 2 1439 | [2019-10-31T06:16:24Z DEBUG fuse::request] GETATTR(184) ino 0x0000000000000001 1440 | // rmdir(2回目) 1441 | [2019-10-31T06:16:34Z DEBUG fuse::request] LOOKUP(186) parent 0x0000000000000001, name "testdir" 1442 | [2019-10-31T06:16:34Z DEBUG fuse::request] RMDIR(188) parent 0x0000000000000001, name "testdir" 1443 | [2019-10-31T06:16:34Z DEBUG fuse::request] FORGET(190) ino 0x0000000000000004, nlookup 5 1444 | [2019-10-31T06:16:34Z DEBUG fuse::request] GETATTR(192) ino 0x0000000000000001 1445 | ``` 1446 | 1447 | ## まとめ 1448 | これでディレクトリの作成と削除ができるようになりました。 1449 | 次回は `rename` で名前の変更と移動ができるようにします。 1450 | 1451 | # 名前の変更と移動 1452 | ## 概要 1453 | 作成/削除の関数は一通り実装したので、今回はファイル/ディレクトリの移動ができるようにします。 1454 | 1455 | ## DB関数 1456 | 作成したDB関数は以下になります。 1457 | 1458 | ```rust 1459 | /// dentryを移動させる。移動先を上書きする場合、元からあったファイル/ディレクトリのinode番号を返す 1460 | fn move_dentry(&mut self, parent: u32, name: &str, new_parent: u32, new_name: &str) -> Result, Error>; 1461 | ``` 1462 | 1463 | ## rename 1464 | ```rust 1465 | fn rename(&mut self, _req: &Request, parent: u64, name: &OsStr, newparent: u64, newname: &OsStr, reply: ReplyEmpty); 1466 | ``` 1467 | 1468 | 引数 `parent` で親ディレクトリのinode番号、 `name` でファイルまたはディレクトリ名、 1469 | `newparent` で変更後の親ディレクトリのinode番号,、 `newname` で変更後の名前が指定されるので、 1470 | ファイルまたはディレクトリを移動し、名前を変更します。 1471 | 1472 | cの `fuse_lowlevel` の説明によると、変更先にファイルまたはディレクトリが存在する場合は自動で上書きしなければなりません。 1473 | つまり、変更先inodeのnlinkを1減らし、ディレクトリエントリから削除します。 1474 | こちらも削除処理と同様に、 `lookup count` が0でない場合は、0になるまでinodeの削除を遅延します。 1475 | 上書き時に変更前と変更先のファイルタイプが異なる場合のチェックはカーネル側がやってくれるようで、 `rename(2)` を実行しても `rename` が呼ばれずにエラーになります。 1476 | 1477 | ただし、変更前がディレクトリで、変更先のディレクトリを上書きする場合、変更先のディレクトリは空でないかファイルシステムがチェックする必要があります。 1478 | 中身がある場合は、エラーとして `ENOTEMPTY` を返します。 1479 | 1480 | `rename(2)` には他に、以下の制約があります。 1481 | 1482 | - 移動前と移動後のファイルが同じ(同じinode番号を指す)場合何もしない 1483 | - ディレクトリを自分自身のサブディレクトリに移動できない 1484 | 1485 | この辺りはカーネルが処理してくれているようで、 `rename` 関数が呼ばれずにエラーになります。 1486 | 1487 | libfuseでは上書き禁止を指定したりできる `flag` が引数に指定されますが、fuse-rsには該当する引数がありません。 1488 | 1489 | ```rust 1490 | fn rename( 1491 | &mut self, 1492 | _req: &Request<'_>, 1493 | parent: u64, 1494 | name: &OsStr, 1495 | newparent: u64, 1496 | newname: &OsStr, 1497 | reply: ReplyEmpty 1498 | ) { 1499 | let parent = parent as u32; 1500 | let name = name.to_str().unwrap(); 1501 | let newparent = newparent as u32; 1502 | let newname = newname.to_str().unwrap(); 1503 | // rename. 上書きされる場合は、上書き先のinodeを取得 1504 | let entry = match self.db.move_dentry(parent, name, newparent, newname) { 1505 | Ok(n) => n, 1506 | Err(err) => match err.kind() { 1507 | // 空の場合 1508 | ErrorKind::FsNotEmpty {description} => {reply.error(ENOTEMPTY); debug!("{}", &description); return;}, 1509 | // ファイル -> ディレクトリの場合(カーネルがチェックしているので発生しないはず) 1510 | ErrorKind::FsIsDir{description} => {reply.error(EISDIR); debug!("{}", &description); return;}, 1511 | // ディレクトリ -> ファイルの場合(カーネルがチェックしているので発生しないはず) 1512 | ErrorKind::FsIsNotDir{description} => {reply.error(ENOTDIR); debug!("{}", &description); return;}, 1513 | _ => {reply.error(ENOENT); debug!("{}", err); return;}, 1514 | } 1515 | }; 1516 | // 上書きがあった場合、各カウントを調べて、削除する必要がある場合は削除する 1517 | if let Some(ino) = entry { 1518 | let lc_list = self.lookup_count.lock().unwrap(); 1519 | if !lc_list.contains_key(&ino) { 1520 | match self.db.delete_inode_if_noref(ino) { 1521 | Ok(n) => n, 1522 | Err(err) => {reply.error(ENOENT); debug!("{}", err); return;}, 1523 | }; 1524 | } 1525 | } 1526 | reply.ok(); 1527 | } 1528 | ``` 1529 | 1530 | ## 実行結果 1531 | 1532 | ``` 1533 | $ mv ~/mount/touch.txt ~/mount/touch3.txt 1534 | $ ls ~/mount/ 1535 | hello.txt testdir touch3.txt 1536 | ``` 1537 | 1538 | ```text 1539 | [2019-10-31T10:54:17Z DEBUG fuse::request] LOOKUP(442) parent 0x0000000000000001, name "touch.txt" 1540 | [2019-10-31T10:54:17Z DEBUG fuse::request] LOOKUP(444) parent 0x0000000000000001, name "touch3.txt" 1541 | [2019-10-31T10:54:17Z DEBUG fuse::request] LOOKUP(446) parent 0x0000000000000001, name "touch3.txt" 1542 | [2019-10-31T10:54:17Z DEBUG fuse::request] LOOKUP(448) parent 0x0000000000000001, name "touch3.txt" 1543 | [2019-10-31T10:54:17Z DEBUG fuse::request] RENAME(450) parent 0x0000000000000001, name "touch.txt", newparent 0x0000000000000001, newname "touch3.txt" 1544 | [2019-10-31T10:54:17Z DEBUG fuse::request] GETATTR(452) ino 0x0000000000000001 1545 | ``` 1546 | 1547 | ```text 1548 | $ mv ~/mount/touch3.txt ~/mount/testdir 1549 | $ ls ~/mount/testdir 1550 | touch3.txt 1551 | ``` 1552 | 1553 | ```text 1554 | [2019-10-31T10:57:28Z DEBUG fuse::request] LOOKUP(500) parent 0x0000000000000001, name "touch3.txt" 1555 | [2019-10-31T10:57:28Z DEBUG fuse::request] LOOKUP(502) parent 0x0000000000000005, name "touch3.txt" 1556 | [2019-10-31T10:57:28Z DEBUG fuse::request] LOOKUP(504) parent 0x0000000000000005, name "touch3.txt" 1557 | [2019-10-31T10:57:28Z DEBUG fuse::request] LOOKUP(506) parent 0x0000000000000005, name "touch3.txt" 1558 | [2019-10-31T10:57:28Z DEBUG fuse::request] RENAME(508) parent 0x0000000000000001, name "touch3.txt", newparent 0x0000000000000005, newname "touch3.txt" 1559 | [2019-10-31T10:57:28Z DEBUG fuse::request] GETATTR(510) ino 0x0000000000000001 1560 | ``` 1561 | 1562 | ## まとめ 1563 | 今回はファイル移動を実装しました。 1564 | 次回はシンボリックリンク、ハードリンクを実装していきます。 1565 | 1566 | # シンボリックリンク・ハードリンク 1567 | シンボリックリンクとハードリンクを作成できるようにします。 1568 | 実装する関数は以下になります。 1569 | 1570 | ```rust 1571 | fn readlink(&mut self, _req: &Request<'_>, ino: u64, reply: ReplyData) { 1572 | ... 1573 | } 1574 | fn symlink(&mut self, _req: &Request<'_>, parent: u64, name: &OsStr, link: &Path, reply: ReplyEntry) { 1575 | ... 1576 | } 1577 | fn link(&mut self, _req: &Request<'_>, ino: u64, newparent: u64, newname: &OsStr, reply: ReplyEntry) { 1578 | ... 1579 | } 1580 | ``` 1581 | 1582 | ## DB関数 1583 | 追加したDB関数は以下になります。 1584 | 1585 | ```rust 1586 | /// ハードリンクを追加する。ディレクトリエントリを追加し、参照カウントを1増やす 1587 | fn link_dentry(&mut self, inode: u32, parent: u32, name: &str) -> Result; 1588 | ``` 1589 | 1590 | 1591 | ## link 1592 | ```rust 1593 | fn link(&mut self, _req: &Request<'_>, ino: u64, newparent: u64, newname: &OsStr, reply: ReplyEntry); 1594 | ``` 1595 | 1596 | 引数 `ino` で対象のinode番号、 `newparent` で親ディレクトリのinode、 `newname` で名前が与えられるので、ハードリンクを作成します。 1597 | 1598 | ハードリンクを作成することで、別のパスが全く同じファイルを指す事ができます。 1599 | inode番号が同じなので、ファイルパス以外のデータ、メタデータは同じになります。 1600 | 全てのハードリンクが削除されるまで、ファイルは削除されません。 1601 | 1602 | ハードリンクはディレクトリに適用する事はできません。また、ディレクトリのハードリンクを作成することはできません。 1603 | これらのチェックはカーネルがやっていて、 `link(2)` を実行した場合エラーになり、 `link` 関数が呼ばれません。 1604 | 1605 | `link` も `lookup count` を1増やす事に注意してください。 1606 | 1607 | ```rust 1608 | fn link(&mut self, _req: &Request<'_>, ino: u64, newparent: u64, newname: &OsStr, reply: ReplyEntry) { 1609 | // リンクの追加 1610 | let attr = match self.db.link_dentry(ino as u32, newparent as u32, newname.to_str().unwrap()) { 1611 | Ok(n) => n, 1612 | Err(err) => match err.kind() { 1613 | // 元のパスがディレクトリだった(カーネルがチェックしているので発生しないはず) 1614 | ErrorKind::FsParm{description} => {reply.error(EPERM); debug!("{}", &description); return;}, 1615 | // リンク先にファイルまたはディレクトリがある(カーネルがチェックしているので発生しないはず) 1616 | ErrorKind::FsFileExist{description} => {reply.error(EEXIST); debug!("{}", &description); return;}, 1617 | _ => {reply.error(ENOENT); debug!("{}", err); return;} 1618 | } 1619 | }; 1620 | reply.entry(&ONE_SEC, &attr.get_file_attr(), 0); 1621 | // lookup countの追加 1622 | let mut lc_list = self.lookup_count.lock().unwrap(); 1623 | let lc = lc_list.entry(ino as u32).or_insert(0); 1624 | *lc += 1; 1625 | } 1626 | ``` 1627 | 1628 | ## symlink 1629 | ```rust 1630 | fn symlink(&mut self, _req: &Request<'_>, parent: u64, name: &OsStr, link: &Path, reply: ReplyEntry); 1631 | ``` 1632 | 1633 | 引数の `link` で指定されたパスに対するシンボリックリンクを、 1634 | `parent` で指定されたinode番号のディレクトリ内に、 `name` という名前で作成します。 1635 | 1636 | シンボリックリンクはリンク先のパスをデータに持つ特殊なファイルです。 1637 | ファイルシステムはパスを保存するだけで、リンク先に対して特に操作を行う必要はありません。 1638 | リンク先にファイルやディレクトリが存在していなくてもOKです。 1639 | 1640 | シンボリックリンクの内容が長すぎる場合、 `ENAMETOOLONG` を返すことができます。 1641 | どの程度の長さでエラーにするかはファイルシステムが決めますが、あまり長くても(4096を超えるぐらい)カーネルが別のエラーを返してくるので、 1642 | 1024~4096ぐらいの間に設定しておくといいです。 1643 | 1644 | `symlink` もlookup count を増やす必要がある事に注意してください。 1645 | 1646 | ```rust 1647 | fn symlink(&mut self, req: &Request, parent: u64, name: &OsStr, link: &Path, reply: ReplyEntry) { 1648 | let now = SystemTime::now(); 1649 | // メタデータの追加 1650 | let mut attr = DBFileAttr { 1651 | ino: 0, 1652 | size: 0, 1653 | blocks: 0, 1654 | atime: now, 1655 | mtime: now, 1656 | ctime: now, 1657 | crtime: now, 1658 | kind: FileType::Symlink, 1659 | perm: 0o777, // リンク自体のパーミッションは使われないので適当に設定する 1660 | nlink: 0, 1661 | uid: req.uid(), 1662 | gid: req.gid(), 1663 | rdev: 0, 1664 | flags: 0 1665 | }; 1666 | let ino = match self.db.add_inode(parent as u32, name.to_str().unwrap(), &attr) { 1667 | Ok(n) => n, 1668 | Err(err) => {reply.error(ENOENT); debug!("{}", err); return;} 1669 | }; 1670 | let data = link.to_str().unwrap().as_bytes(); 1671 | let block_size = self.db.get_db_block_size() as usize; 1672 | if data.len() > block_size { 1673 | reply.error(ENAMETOOLONG); 1674 | return; 1675 | } 1676 | // ファイルの内容(リンク先のパス)の書き込み 1677 | match self.db.write_data(ino, 1, &data, data.len() as u32) { 1678 | Ok(n) => n, 1679 | Err(err) => {reply.error(ENOENT); debug!("{}", err); return;} 1680 | } 1681 | attr.ino = ino; 1682 | reply.entry(&ONE_SEC, &attr.get_file_attr(), 0); 1683 | } 1684 | ``` 1685 | 1686 | ## readlink 1687 | 1688 | ```rust 1689 | fn readlink(&mut self, _req: &Request<'_>, ino: u64, reply: ReplyData); 1690 | ``` 1691 | 1692 | 引数の `ino` で指定されたシンボリックリンクの内容(シンボリックリンク先のパス) を返します。 1693 | 1694 | ```rust 1695 | fn readlink(&mut self, _req: &Request<'_>, ino: u64, reply: ReplyData) { 1696 | let ino = ino as u32; 1697 | let attr = match self.db.get_inode(ino) { 1698 | Ok(n) => match n { 1699 | Some(attr) => attr, 1700 | None => {reply.error(ENOENT); return;} 1701 | }, 1702 | Err(err) => {reply.error(ENOENT); debug!("{}", err); return;} 1703 | }; 1704 | 1705 | if attr.kind != FileType::Symlink { 1706 | reply.error(EINVAL); 1707 | return; 1708 | } 1709 | let size = attr.size; 1710 | let mut data = match self.db.get_data(ino as u32, 1, size) { 1711 | Ok(n) => n, 1712 | Err(_err) => {reply.error(ENOENT); return; } 1713 | }; 1714 | data.resize(size as usize, 0); 1715 | reply.data(&data); 1716 | } 1717 | ``` 1718 | 1719 | ## 実行結果 1720 | 1721 | ### ハードリンクの作成 1722 | 1723 | ```text 1724 | $ ln hello.txt hello.hardlink 1725 | $ cat hello.hardlink 1726 | Hello world! 1727 | ``` 1728 | 1729 | ```text 1730 | [2019-11-05T11:12:56Z DEBUG fuse::request] LOOKUP(104) parent 0x0000000000000001, name "hello.txt" 1731 | [2019-11-05T11:12:56Z DEBUG fuse::request] LOOKUP(106) parent 0x0000000000000001, name "hello.hardlink" 1732 | [2019-11-05T11:12:56Z DEBUG fuse::request] LINK(108) ino 0x0000000000000002, newparent 0x0000000000000001, newname "hello.hardlink" 1733 | [2019-11-05T11:12:56Z DEBUG fuse::request] GETATTR(110) ino 0x0000000000000001 1734 | [2019-11-05T11:13:01Z DEBUG fuse::request] OPEN(120) ino 0x0000000000000002, flags 0x8000 1735 | [2019-11-05T11:13:01Z DEBUG fuse::request] READ(122) ino 0x0000000000000002, fh 0, offset 0, size 4096 1736 | [2019-11-05T11:13:01Z DEBUG fuse::request] RELEASE(124) ino 0x0000000000000002, fh 0, flags 0x8000, release flags 0x0, lock owner 0 1737 | [2019-11-05T11:13:01Z DEBUG fuse::request] GETATTR(126) ino 0x0000000000000001 1738 | ``` 1739 | 1740 | ### シンボリックリンクの作成 1741 | 1742 | ```text 1743 | $ ln -s hello.txt hello.symlink 1744 | $ cat hello.symlink 1745 | Hello world! 1746 | ``` 1747 | 1748 | ```text 1749 | [2019-11-05T11:15:55Z DEBUG fuse::request] LOOKUP(134) parent 0x0000000000000001, name "hello.symlink" 1750 | [2019-11-05T11:15:55Z DEBUG fuse::request] SYMLINK(136) parent 0x0000000000000001, name "hello.symlink", link "hello.txt" 1751 | [2019-11-05T11:15:55Z DEBUG fuse::request] GETATTR(138) ino 0x0000000000000001 1752 | [2019-11-05T11:16:01Z DEBUG fuse::request] LOOKUP(146) parent 0x0000000000000001, name "hello.symlink" 1753 | [2019-11-05T11:16:01Z DEBUG fuse::request] READLINK(148) ino 0x000000000000000a 1754 | [2019-11-05T11:16:01Z DEBUG fuse::request] LOOKUP(150) parent 0x0000000000000001, name "hello.txt" 1755 | [2019-11-05T11:16:01Z DEBUG fuse::request] OPEN(152) ino 0x0000000000000002, flags 0x8000 1756 | [2019-11-05T11:16:01Z DEBUG fuse::request] READ(154) ino 0x0000000000000002, fh 0, offset 0, size 4096 1757 | [2019-11-05T11:16:01Z DEBUG fuse::request] RELEASE(156) ino 0x0000000000000002, fh 0, flags 0x8000, release flags 0x0, lock owner 0 1758 | [2019-11-05T11:16:01Z DEBUG fuse::request] GETATTR(158) ino 0x0000000000000001 1759 | ``` 1760 | 1761 | ## まとめ 1762 | 今回はシンボリックリンクとハードリンクの機能を作成しました。 1763 | 1764 | # 後回しにしていた機能 1765 | ## 概要 1766 | 今まで基本的な操作を実装してきましたが、いくつかの機能を後回しにしていました。 1767 | 今回はそれらの機能を見ていきます。 1768 | 内容は「何らかの機能に対応する」や、「ルールを厳密に守る」ためのものですが、 1769 | ファイルシステムの実装によっては必要がないものもあるので、必要に応じて実装していきます。 1770 | 1771 | ## マウントオプション 1772 | マウントオプションは `fuse::mount` の3番目の引数で指定します。 1773 | 各マウントオプションは、 `["-o", "some_option", "-o", "another_option"]` のように、頭に `"-o"` を付けます。 1774 | 1775 | ファイルシステムからカーネルに渡すオプションの中で有用なものをいくつか挙げます。 1776 | 1777 | ### allow_other 1778 | デフォルトでは、FUSEを使ったファイルシステムはマウントしたユーザしかアクセスできません。 1779 | マウントオプションに `allow_other` を指定することで、他のユーザもアクセスできるようになります。 1780 | この機能を使うには、 `/etc/fuse.conf` に `user_allow_other` を書き込む必要があります。 1781 | 1782 | また、rootのみアクセスを許可する `allow_root` もあります。 1783 | 1784 | ### default_permissions 1785 | デフォルトでは、FUSEはアクセス権のチェックを一切行わず、ファイルシステムがチェックする必要があります。 1786 | マウントオプションに `default_permissions` を指定することで、アクセス権チェックを全てカーネルに任せることができます。 1787 | カーネルは、ファイルオーナー、グループ、ファイルのモードから、ユーザがアクセスできるかをチェックします。 1788 | 1789 | ## open/close 1790 | 今までファイルやディレクトリのオープンについては一切無視してきました。 1791 | ここで、ファイルを開く/閉じる関数を実装していきます。 1792 | 1793 | ## open 1794 | ```rust 1795 | fn open(&mut self, _req: &Request<'_>, ino: u64, flags: u32, reply: ReplyOpen) { 1796 | reply.opened(0, 0); 1797 | } 1798 | ``` 1799 | 引数の `ino` で指定されたinode番号のファイルを、 `flags` で指定されたフラグで開きます。 1800 | 1801 | ### 引数のフラグ 1802 | フラグは `_flags` 引数で渡されます。 1803 | ただし、 `open` では `O_CREAT, O_EXCL, O_NOCTTY` の3つはカーネルで省かれるので、ファイルシステムは検知できません。 1804 | 1805 | マウントオプションで `-o default_permissions` が指定されている場合を除いて、 1806 | ファイルシステムは、アクセスモードのフラグを使ってアクセス権チェックを行わないといけません。 1807 | `O_RDONLY`, `O_WRONLY`, `O_RDWR` のフラグに応じて、 `read` `write` できるか決定します。 1808 | 1809 | ライトバックキャッシュが有効の時、カーネルは `O_WRONLY` でもreadしてくる事があるので、 1810 | マウントオプションで `-o writeback` が有効の場合は読めるようにしておく必要があります。 1811 | [libfuseのサンプルの修正例](https://github.com/libfuse/libfuse/commit/b3109e71faf2713402f70d226617352815f6c72e) 1812 | を参考にしてください。 1813 | 1814 | また、 `write` の時に説明した `O_APPEND` フラグにも注意してください。 1815 | 1816 | ここに書かれていないフラグも、 `open(2)` の定義通りの動作が要求されます。 1817 | また、状況に応じて `create` が呼ばれるので、そちらでも対処する必要があります。 1818 | 渡されるフラグは以下の通りです。 1819 | 1820 | |flag|説明| 1821 | |---|---| 1822 | |O_APPEND|書き込みは全て追記する| 1823 | |O_ASYNC|入出力可能になったとき、シグナルSIGIOを返す(ソケットまたはパイプの時)| 1824 | |O_DIRECT|ファイルシステムはキャッシュを最小限にする| 1825 | |O_DSYNC|writeの度に、データとデータの読み書きに必要なメタデータ(サイズなど)をディスクに書き込む| 1826 | |O_LARGEFILE|64ビットのサイズを持つファイルをオープン可能にする| 1827 | |O_NOATIME|read時にatimeを更新しない| 1828 | |O_NONBLOCK|処理を完全にブロックしない(ある程度でタイムアウトする)| 1829 | |O_SYNC|writeの度に、データと全てのメタデータをディスクに書き込む| 1830 | 1831 | 以下は対処不要なフラグです。 1832 | 1833 | |flag|説明| 1834 | |---|---| 1835 | |O_CREAT|状況に応じてcreateとopenに割り振られる| 1836 | |O_DIRECTORY|opendirが呼ばれる| 1837 | |O_EXCL|カーネルでチェックしてくれている| 1838 | |O_NOFOLLOW|カーネルでチェックしてくれている| 1839 | |O_TRUNC|setattrが呼ばれる| 1840 | 1841 | ### reply 1842 | openのreplyは、以下のようにして操作します。 1843 | 1844 | ```rust 1845 | reply.opened(fh, flags); 1846 | ``` 1847 | 1848 | `fh` はファイルハンドル、 `flags` はフラグです。 1849 | 1850 | #### ファイルハンドル 1851 | ファイルシステムはファイルハンドル `fh: u64` を戻り値に含めることができます。( `reply.opened()` の1番目の引数)。 1852 | 1853 | `open(2)` の実行結果として `3` のようなファイルディスクリプタ(fd)が返ってきますが、 1854 | カーネルがこのfdとfhの対応を覚えていて、同じfdに対する `write` や `read` の引数として、このfhを入力してくれます。 1855 | fhは自由に決めることができ、ポインタ、リストのインデックス、その他好きな値をファイルシステム側で定める事ができます。 1856 | 1857 | #### フラグ 1858 | ファイルシステムはフラグを戻り値に含めることができます( `reply.opened()` の2番目の引数)。 1859 | `fuse-abi` の `FOPEN_DIRECT_IO` `FOPEN_KEEP_CACHE` `FOPEN_NONSEEKABLE` `FOPEN_PURGE_ATTR` `FOPEN_PURGE_UBC` 1860 | が相当します。(それぞれビットマスク) 1861 | 1862 | 通常はあまり使わないと思われるので、詳しく知りたい場合は [libfuseのfuse_common.h](https://github.com/libfuse/libfuse/blob/master/include/fuse_common.h) 1863 | を参照してください。 1864 | 1865 | ## flush 1866 | ```rust 1867 | fn flush(&mut self, _req: &Request<'_>, ino: u64, fh: u64, lock_owner: u64, reply: ReplyEmpty) { 1868 | ... 1869 | } 1870 | ``` 1871 | 1872 | `close(2)` システムコールの度に呼ばれます。 1873 | 1874 | 同じくファイルを閉じるための関数である `release` は値を返さないので、 1875 | `close(2)` に対してエラーを返したい場合はここで行う必要があります。 1876 | 1877 | `dup, dup2, fork` によりプロセスが複製される事で、一つの `open` に対して、複数の `flush` が呼ばれる場合があり、 1878 | どれが最後の `flush` なのか識別するのは不可能なので、後で(または `flush` 処理中に) 別の `flush` が呼ばれてもいいように対応します。 1879 | どうしても1度しか実行してはいけない処理がある場合は、 `release` で行います。 1880 | 1881 | 例えば、sshfsでは、`flush` でスレッド間でロックをかけて、競合しないように書き込み処理の後始末を行っています。 1882 | 1883 | `flush` という名前が付いてはいますが、 `fsync` のようにデータをディスクに書き込む事を義務付けられてはいません。 1884 | `close(2)` 時にデータが書き込まれているかどうかは使用者側の責任になります。 1885 | 1886 | `setlk` `getlk` のようなファイルロック機構をファイルシステムが実装している場合、引数の `lock_owner` が持つロックを全て開放します。 1887 | 1888 | ## relase 1889 | ```rust 1890 | fn release(&mut self, _req: &Request<'_>, _ino: u64, _fh: u64, _flags: u32, _lock_owner: u64, _flush: bool, reply: ReplyEmpty) { 1891 | ... 1892 | reply.ok(); 1893 | } 1894 | ``` 1895 | 1896 | ファイルを閉じます。 1897 | 一つの `open` に対して、必ず一つの `release` が呼ばれます。 1898 | 1899 | ファイルシステムはエラーを返してもよいですが、呼び出し元の `close(2)` には値が渡らないので、特に意味はありません。 1900 | 1901 | 引数の `fh` は `open` 時にファイルシステムが指定した値で、 `flags` は `open` 時の引数 `flag` と同一の値になります。 1902 | 1903 | ## opendir 1904 | ```rust 1905 | fn opendir(&mut self, _req: &Request<'_>, ino: u64, flags: u32, reply: ReplyOpen) { 1906 | ... 1907 | reply.opened(0, 0); 1908 | } 1909 | ``` 1910 | 1911 | 引数の `ino` で指定されたinode番号のディレクトリを開きます。 1912 | 1913 | ファイル同様、 `fh: u64` を戻り値に含めることができます( `reply.opened()` の1番目の引数)。 1914 | `fh` は `readdir` および `releasedir` の引数としてカーネルから渡されます。 1915 | `fh` に何も入れないことも可能ですが、`opendir` から `relasedir` までの間に 1916 | ディレクトリエントリが追加または削除された場合でも `readdir` の整合性を保つために、何らかの情報を入れておく事が推奨されます。 1917 | open中に追加または削除されたエントリは返しても返さなくても良いですが、追加または削除されていないエントリは必ず返さないといけないので、 1918 | 厳密に対応しようとするなら、ディレクトリエントリをコピーして、情報を保持しておくとよいです。 1919 | 1920 | ただし、MacOSでは一度opendirするとしばらく開いたままなので、readdirを実行するたびに最新の情報を返すようにします。 1921 | 1922 | 引数の `flags` は `open(2)` で `O_DIRECTORY` を選択した時に `opendir` が呼ばれるので、その引数です。 1923 | 手元の環境で `opendir(3)` を実行すると、 `O_NONBLOCK`, `O_DIRECTORY`, `O_LARGEFILE` が呼ばれました。 1924 | 1925 | ## releasedir 1926 | ```rust 1927 | fn releasedir(&mut self, _req: &Request<'_>, _ino: u64, _fh: u64, _flags: u32, reply: ReplyEmpty) { 1928 | ... 1929 | reply.ok(); 1930 | } 1931 | ``` 1932 | 1933 | `opendir` で確保したリソースを解放します。 1934 | 引数の `fh` は `opendir` でファイルシステムが渡した値です。 1935 | 1936 | 一度の `opendir` に対して、一度だけ `releasedir` が呼び出されます。 1937 | 1938 | ## fsync 1939 | ```rust 1940 | fn fsync(&mut self, _req: &Request<'_>, ino: u64, fh: u64, datasync: bool, reply: ReplyEmpty) { 1941 | ... 1942 | } 1943 | ``` 1944 | 1945 | 引数の `ino` で指定されたinode番号のファイルのキャッシュを永続領域に書き込みます。 1946 | 引数の `fh` は `open` でファイルシステムが渡した値です。 1947 | 1948 | fsyncが呼ばれるまでは、書き込まれたデータやメタデータはキャッシュしていてよいです。 1949 | つまり、なんらかの事情(kill, マシンの電源断)でファイルシステムのデーモンが即座に終了したとしても、データの保証はしません。 1950 | 1951 | 一方、fsyncに対して `reply.ok()` を返した時点で、 1952 | データがディスクやネットワークの先などどこかの領域に保存されている事を保証しなければなりません。 1953 | 1954 | 引数 `datasync` が `true` である場合、メタデータは書き込みません。 1955 | 1956 | ## fsyncdir 1957 | ```rust 1958 | fn fsyncdir (&mut self, _req: &Request<'_>, ino: u64, fh: u64, datasync: bool, reply: ReplyEmpty) { 1959 | ... 1960 | } 1961 | ``` 1962 | 1963 | 引数の `ino` で指定されたディレクトリ内のデータ(ディレクトリエントリ)をディスクに書き込みます。 1964 | 引数の `datasync` が `true` の時、ディレクトリ自体のメタデータは更新しません。 1965 | 1966 | この関数が呼ばれるまでは、ファイル作成時などに作成されるディレクトリエントリはディスクに書き込まれることを保証しません。 1967 | `fsync(2)` でディレクトリを引数に取った時に呼ばれます。 1968 | 1969 | ## statfs 1970 | ```rust 1971 | fn statfs(&mut self, _req: &Request<'_>, _ino: u64, reply: ReplyStatfs) { 1972 | ... 1973 | reply.statfs(blocks, bfree, bavail, files, ffree, bsize, namelen, frsize); 1974 | } 1975 | ``` 1976 | 1977 | `statfs(2)` で使うファイルシステムの情報を返します。 1978 | `df` コマンド等で出てくる奴です。 1979 | 1980 | replyの引数の意味は次のようになります。 1981 | 1982 | ``` 1983 | blocks: u64; // frsize単位でのファイルシステムの総ブロック数 (ex: 1024) 1984 | bfree: u64; // ファイルシステムの空きブロック数 1985 | bavail: u64; // スーパーユーザ用に予約されている領域を除いた空きブロック数 1986 | files: u64; // 総inode数 1987 | ffree: u64; // 空きinode数 1988 | bsize: u32; // 推奨されるI/Oで使用するブロックのバイト数 (ex: 4096) 1989 | namelen: u32; //ファイル名の最大長 1990 | frsize: u32; //最小のブロックのバイト数 (ex: 512, 1024, 2048, 4096) 1991 | ``` 1992 | 1993 | # 拡張ファイル属性 1994 | ## 概要 1995 | 拡張ファイル属性は、ユーザがkey-valueペアのメタデータを自由にファイルやディレクトリに付ける事が出来る機能です。 1996 | Linuxでは主にACLやselinuxが利用しています。 1997 | 1998 | 拡張ファイル属性の操作に必要な関数は以下の4つです。 1999 | 2000 | ```rust 2001 | fn setxattr(&mut self, _req: &Request<'_>, _ino: u64, _name: &OsStr, _value: &[u8], _flags: u32, _position: u32, reply: ReplyEmpty) { 2002 | ... 2003 | } 2004 | fn getxattr(&mut self, _req: &Request<'_>, _ino: u64, _name: &OsStr, _size: u32, reply: ReplyXattr) { 2005 | ... 2006 | } 2007 | fn listxattr(&mut self, _req: &Request<'_>, _ino: u64, _size: u32, reply: ReplyXattr) { 2008 | ... 2009 | } 2010 | fn removexattr(&mut self, _req: &Request<'_>, _ino: u64, _name: &OsStr, reply: ReplyEmpty) { 2011 | ... 2012 | } 2013 | ``` 2014 | 2015 | ## setxattr 2016 | ```rust 2017 | fn setxattr(&mut self, _req: &Request<'_>, ino: u64, name: &OsStr, value: &[u8], flags: u32, position: u32, reply: ReplyEmpty); 2018 | ``` 2019 | 拡張ファイル属性を設定します。 2020 | 引数は `setxattr(2)` と同様です。 2021 | 2022 | 実装しない( `ENOSYS` を返す) 場合、拡張ファイル属性をサポートしない( `ENOTSUP` と同様)と解釈され、 2023 | 以降はカーネルからファイルシステムの呼び出しを行わずに失敗するようになります。 2024 | 2025 | 拡張属性は `name: value` の形式で与えられます。 2026 | 2027 | 引数の `position` はmacのリソースフォークで使用されている値で、 2028 | 基本は0です。osxfuseにのみ存在する引数です。(現在のrustの実装では、mac以外は0を返す) 2029 | fuse-rsでは、 `getxattr` の方に [実装されていないまま](https://github.com/zargony/fuse-rs/issues/40) なので、 2030 | とりあえず放置でよいと思われます。 2031 | 2032 | 引数の `flags` には `XATTR_CREATE` または `XATTR_REPLACE` が指定されます。 2033 | `XATTR_CREATE` が指定された場合、既に属性が存在する場合は `EEXIST` を返して失敗します。 2034 | `XATTR_REPLACE` が指定された場合、属性が存在しない場合 `ENODATA` を返して失敗します。 2035 | デフォルトでは、属性が存在しない場合は拡張ファイル属性を作成し、既に存在する場合は値を置き換えます。 2036 | 2037 | 実装は以下のようになります。 2038 | 2039 | ```rust 2040 | fn setxattr(&mut self, _req: &Request<'_>, ino: u64, name: &OsStr, value: &[u8], flags: u32, _position: u32, reply: ReplyEmpty) { 2041 | let ino = ino as u32; 2042 | let name = name.to_str().unwrap(); 2043 | // フラグチェック 2044 | if flags & XATTR_CREATE as u32 > 0 || flags & XATTR_REPLACE as u32 > 0 { 2045 | match self.db.get_xattr(ino, name) { 2046 | Ok(_) => { 2047 | if flags & XATTR_CREATE as u32 > 0 { 2048 | reply.error(EEXIST); 2049 | return; 2050 | } 2051 | }, 2052 | Err(err) => { 2053 | match err.kind() { 2054 | ErrorKind::FsNoEnt {description: _} => { 2055 | if flags & XATTR_REPLACE as u32 > 0 { 2056 | reply.error(ENODATA); 2057 | return; 2058 | } 2059 | }, 2060 | _ => { 2061 | reply.error(ENOENT); 2062 | return; 2063 | } 2064 | } 2065 | } 2066 | }; 2067 | } 2068 | match self.db.set_xattr(ino, name, value) { 2069 | Ok(n) => n, 2070 | Err(err) => {reply.error(ENOENT); debug!("{}", err); return;} 2071 | }; 2072 | reply.ok(); 2073 | } 2074 | ``` 2075 | 2076 | ## getxattr 2077 | ```rust 2078 | fn getxattr(&mut self, _req: &Request<'_>, ino: u64, name: &OsStr, size: u32, reply: ReplyXattr); 2079 | ``` 2080 | 2081 | 引数の`ino` で指定されたinode番号のファイルの、 `name` で指定された拡張ファイル属性の値を取得します。 2082 | 2083 | 引数の `size` が0の場合、値のデータのバイト数を `reply.size()` に入れます。 2084 | 2085 | `size` が0でない場合、以下のような処理になります。 2086 | 値のデータのバイト数が `size` 以下の場合、 `reply.data()` に値を入れて返します。 2087 | `size` を超える場合、 `reply.error(ERANGE)` を返します。 2088 | 2089 | ```rust 2090 | fn getxattr(&mut self, _req: &Request<'_>, ino: u64, name: &OsStr, size: u32, reply: ReplyXattr) { 2091 | let ino = ino as u32; 2092 | let name = name.to_str().unwrap(); 2093 | let value = match self.db.get_xattr(ino, name) { 2094 | Ok(n) => n, 2095 | Err(err) => {reply.error(ENOENT); debug!("{}", err); return;} 2096 | }; 2097 | if size == 0 { 2098 | reply.size(value.len() as u32); 2099 | } else if size < value.len() as u32 { 2100 | reply.error(ERANGE); 2101 | } else { 2102 | reply.data(value.as_slice()); 2103 | } 2104 | } 2105 | ``` 2106 | 2107 | ## listxattr 2108 | ```rust 2109 | fn listxattr(&mut self, _req: &Request<'_>, _ino: u64, _size: u32, reply: ReplyXattr); 2110 | ``` 2111 | 2112 | 引数の `ino` で指定されたinode番号のファイルにセットされている拡張ファイル属性の名前一覧を返します。 2113 | 2114 | 返すべきデータは、「ヌル終端された文字列が連続して並んでいる」フォーマットになります。 2115 | 例えば、 `user.xxx.data` と `user.yyy.name` という名前の拡張ファイル属性がある場合、データは以下のようになります。 2116 | ex: `user.xxx.data\0user.yyy.name\0` 2117 | 2118 | 引数の `size` が0の場合、連結した文字列のサイズ(末尾の `\0` も含める)を `reply.size()` に入れます。 2119 | 2120 | 0でない場合、データのサイズが `size` 以下の場合、 `reply.data()` にデータを入れて返します。 2121 | `size` を超える場合、 `reply.error(ERANGE)` を返します。 2122 | 2123 | ```rust 2124 | fn listxattr(&mut self, _req: &Request<'_>, ino: u64, size: u32, reply: ReplyXattr) { 2125 | let ino = ino as u32; 2126 | let names = match self.db.list_xattr(ino) { 2127 | Ok(n) => n, 2128 | Err(err) => {reply.error(ENOENT); debug!("{}", err); return;} 2129 | }; 2130 | let mut data: Vec = Vec::new(); 2131 | for v in names { 2132 | data.extend(v.bytes()); 2133 | data.push(0); 2134 | } 2135 | if size == 0 { 2136 | reply.size(data.len() as u32); 2137 | } else if size < data.len() as u32 { 2138 | reply.error(ERANGE); 2139 | } else { 2140 | reply.data(data.as_slice()); 2141 | } 2142 | } 2143 | ``` 2144 | 2145 | ## removexattr 2146 | ```rust 2147 | fn removexattr(&mut self, _req: &Request<'_>, _ino: u64, _name: &OsStr, reply: ReplyEmpty); 2148 | ``` 2149 | 2150 | 引数の`ino` で指定されたinode番号のファイルの、 `name` で指定された拡張ファイル属性を削除します。 2151 | 2152 | ```rust 2153 | fn removexattr(&mut self, _req: &Request<'_>, ino: u64, name: &OsStr, reply: ReplyEmpty) { 2154 | let ino = ino as u32; 2155 | let name = name.to_str().unwrap(); 2156 | match self.db.delete_xattr(ino, name) { 2157 | Ok(n) => n, 2158 | Err(err) => {reply.error(ENOENT); debug!("{}", err); return;} 2159 | }; 2160 | reply.ok(); 2161 | } 2162 | ``` 2163 | 2164 | # アクセス権のチェック 2165 | ## 概要 2166 | `allow_other` をマウントオプションで指定した場合、マウントしたユーザ以外がアクセスできるようになるため、 2167 | アクセス権のチェックが必要になってきます。 2168 | マウントオプションで `default_permissions` を指定すればカーネルがチェックしてくれるので特に何かする必要はありませんが、 2169 | 何かしら独自の機構を用意したい場合、チェックが必要な関数毎にチェックする必要があります。 2170 | 2171 | ## access 2172 | ```rust 2173 | fn access(&mut self, _req: &Request<'_>, _ino: u64, _mask: u32, reply: ReplyEmpty) { 2174 | ... 2175 | } 2176 | ``` 2177 | 2178 | プロセスの実行ユーザが、引数の `ino` で 2179 | 2180 | # ロック機構 2181 | ## 概要 2182 | fuseではカーネルがロックのチェックをしてくれています。 2183 | ただし、ネットワークでファイルを共有しているなどの理由で独自のロック機構が必要な場合は、自分で実装する必要があります。 2184 | -------------------------------------------------------------------------------- /misc/plan.md: -------------------------------------------------------------------------------- 1 | # plan 2 | 3 | ## ロードマップ 4 | 1. Hello 5 | 1. ReadWrite 6 | 1. create / delete file 7 | 1. create / delete directory 8 | 1. rename 9 | 1. link, symlink 10 | 1. additional functions and errors 11 | 1. permissions 12 | 1. lock operation 13 | 1. extended attributes 14 | 15 | ## 未実装リスト 16 | 17 | - flush 18 | - fsync 19 | - mknod 20 | - fsyncdir 21 | - statfs 22 | - setxattr 23 | - getxattr 24 | - listxattr 25 | - removexattr 26 | - access 27 | - getlk 28 | - setlk 29 | - bmap 30 | 31 | 32 | - sgid対応 33 | - O_APPEND 34 | - direct_io 35 | - マウントオプションの処理 36 | 37 | ## 参考リンク 38 | 39 | [rust-fuse](https://github.com/zargony/rust-fuse) : Rust版Fuseプロジェクト 40 | 41 | [libfuse](https://github.com/libfuse/libfuse) : C版のFuseインターフェースライブラリ 42 | 43 | [osxfuse](https://github.com/osxfuse/fuse) : MacOS向けのFuseインターフェースライブラリ 44 | 45 | [FUSEプロトコルの説明](https://john-millikin.com/the-fuse-protocol) : カーネルモジュール <-> Fuseライブラリ間のプロトコル 46 | 47 | [VFSの説明](https://ja.osdn.net/projects/linuxjf/wiki/vfs.txt) 48 | 49 | [lowlevel関数の説明(libfuseのヘッダ)](https://github.com/libfuse/libfuse/blob/master/include/fuse_lowlevel.h) 50 | 51 | [ファイルオープン時のもろもろの説明(libfuseのヘッダ)](https://github.com/libfuse/libfuse/blob/master/include/fuse_common.h) 52 | 53 | [Linuxプログラミングインターフェース(書籍)](https://www.oreilly.co.jp/books/9784873115856/) : システムコールの満たすべき要件 54 | 55 | [libfuseのメーリングリストのアーカイブ](https://sourceforge.net/p/fuse/mailman/fuse-devel/) 56 | 57 | [gcsf(rust-fuseの実装例)](https://github.com/harababurel/gcsf) 58 | 59 | ## データベース構造 60 | テーブルはメタデータ(MDT)とディレクトリエントリ(DET)とブロックデータ(BDT)と拡張属性データ(XATTRT)の4つに分ける。 61 | 62 | ### MDT 63 | メタデータは一般的なファイルシステムのメタデータと同様で、fuseが必要なデータを持つ。 64 | 65 | idをinteger primary keyにする。これをinode番号とする。 66 | 67 | 必要そうな情報達 68 | 69 | ``` 70 | pub struct FileAttr { 71 | /// Inode number 72 | pub ino: u64, 73 | /// Size in bytes 74 | pub size: u64, 75 | /// Size in blocks Sparse File に対応する場合、実際に使用しているブロック数を返す 76 | pub blocks: u64, 77 | /// Time of last access read(2)実行時に更新される 78 | pub atime: Timespec, 79 | /// Time of last modification write(2)またはtruncate(2)実行時に更新される 80 | pub mtime: Timespec, 81 | /// Time of last change メタデータ変更時に更新される。 write(2)またはtruncate(2)でファイル内容が変わるときも更新される 82 | pub ctime: Timespec, 83 | /// Time of creation (macOS only) 84 | pub crtime: Timespec, 85 | /// Kind of file (directory, file, pipe, etc) 86 | pub kind: FileType, 87 | /// Permissions 88 | pub perm: u16, 89 | /// Number of hard links 90 | pub nlink: u32, 91 | /// User id 92 | pub uid: u32, 93 | /// Group id 94 | pub gid: u32, 95 | /// Rdev 96 | pub rdev: u32, 97 | /// Flags (macOS only, see chflags(2)) 98 | pub flags: u32, 99 | } 100 | ``` 101 | 102 | |列名 | 型 | 概要| 103 | |---|---|---| 104 | |id|integer primary|ファイルのinode番号 (pkey)| 105 | |size|int|ファイルサイズ| 106 | |atime|text|アクセス時刻| 107 | |atime_nsec|int|アクセス時刻(小数点以下)| 108 | |mtime|text|修正時刻| 109 | |mtime_nsec|int|修正時刻(小数点以下)| 110 | |ctime|text|ステータス変更時刻| 111 | |ctime_nsec|int|ステータス変更時刻(小数点以下)| 112 | |crtime|text|作成時刻(mac用)| 113 | |crtime_nsec|int|作成時刻(小数点以下)| 114 | |kind|int|ファイル種別| 115 | |mode|int|パーミッション(ファイル種別含む)| 116 | |nlink|int|ハードリンク数| 117 | |uid|int|uid| 118 | |gid|int|gid| 119 | |rdev|int|デバイスタイプ| 120 | |flags|int|フラグ(mac用)| 121 | 122 | mknod時のkindはmodeから得る。 `libc::S_IFREG` 等を使うとよい。 123 | なぜか `S_ISREG` は無い… 124 | 125 | それ以外(create, mkdir)の場合ファイル種類は自明である。 126 | 127 | ### BDT 128 | BDTのblobにデータを格納する。 129 | BDTはファイルのinode, 何番目のブロックか、の列を持つ 130 | 131 | |列名 | 型 | 概要| 132 | |---|---|---| 133 | |file_id|int|ファイルのinode番号 (pkey)(foreign key)| 134 | |block_num|int|データのブロック番号(pkey)| 135 | |data|blob|データ(4kByte単位とする)| 136 | 137 | `foreign key (file_id) references metadata(id) on delete cascade` 138 | を指定する事で、ファイルのメタデータが消えたらデータも削除されるようにする。 139 | 140 | `primary key (file_id, block_num)` 141 | を指定する。 142 | 143 | ### DET 144 | ディレクトリ構造を表現する方法は、以下の2つの候補がある 145 | 146 | 1. 分散ファイルシステムでよくある、フルパスを各ファイルが持っていて、文字列操作で各ディレクトリの情報を得る方法 147 | 1. 一般的なファイルシステムのように、ディレクトリエントリを作る方法 148 | 149 | 今回は実装の楽そうな後者のディレクトリエントリ方式で行う。 150 | ext2のディレクトリエントリが分かりやすいので、似たようなのを作る。 151 | 152 | 必要そうなのは以下のデータ 153 | 154 | |列名 | 型 | 概要| 155 | |---|---|---| 156 | |parent_id|int|親ディレクトリのinode (pkey)(foreign key)| 157 | |child_id|int|子ファイル/子ディレクトリのinode (foreign key)| 158 | |file_type|int|ファイルタイプ| 159 | |name|text|ファイル/ディレクトリ名 (pkey)| 160 | 161 | あらゆるディレクトリは `.` と `..` のエントリを持つ 162 | 163 | ### XATTRT 164 | 拡張ファイル属性を格納する。 165 | 166 | |列名 | 型 | 概要| 167 | |---|---|---| 168 | |file_id|int|ファイルのinode番号 (pkey)(foreign key)| 169 | |name|text|属性名(pkey)| 170 | |value|blob|値| 171 | 172 | ## ルートディレクトリ 173 | fuseではルートディレクトリのinodeは1である。 174 | 175 | また、一般的にルートディレクトリの `..` はルートディレクトリ自身を指す 176 | 177 | ## fuseの関数 178 | 179 | 用意されている関数は、cの `fuse_lowlevel` 内の関数と同じである。 180 | トレイトの関数は以下の通り。詳しい内容は `lib.rs` のコメントを参照すること。 181 | なお、以下の関数全てを実装する必要はない。実装しない関数は失敗するだけである。 182 | 183 | 以降の説明で、「カーネル」とは、カーネルコールに応じてfuseの関数を呼び出す存在であり、 184 | 「ファイルシステム」とは、あなたの書いたコードであることに注意する。 185 | 186 | システムコールやlibcの同名の関数と区別するため、システムコールは `open(2)` 、標準Cライブラリ関数は `opendir(3)` のように表記する。 187 | 188 | ``` 189 | pub trait Filesystem { 190 | fn init(&mut self, _req: &Request<'_>) -> Result<(), c_int> { 191 | Ok(()) 192 | } 193 | fn destroy(&mut self, _req: &Request<'_>) {} 194 | fn lookup(&mut self, _req: &Request<'_>, _parent: u64, _name: &OsStr, reply: ReplyEntry) { 195 | reply.error(ENOSYS); 196 | } 197 | fn forget(&mut self, _req: &Request<'_>, _ino: u64, _nlookup: u64) {} 198 | fn getattr(&mut self, _req: &Request<'_>, _ino: u64, reply: ReplyAttr) { 199 | reply.error(ENOSYS); 200 | } 201 | fn setattr(&mut self, _req: &Request<'_>, _ino: u64, _mode: Option, _uid: Option, _gid: Option, _size: Option, _atime: Option, _mtime: Option, _fh: Option, _crtime: Option, _chgtime: Option, _bkuptime: Option, _flags: Option, reply: ReplyAttr) { 202 | reply.error(ENOSYS); 203 | } 204 | fn readlink(&mut self, _req: &Request<'_>, _ino: u64, reply: ReplyData) { 205 | reply.error(ENOSYS); 206 | } 207 | fn mknod(&mut self, _req: &Request<'_>, _parent: u64, _name: &OsStr, _mode: u32, _rdev: u32, reply: ReplyEntry) { 208 | reply.error(ENOSYS); 209 | } 210 | fn mkdir(&mut self, _req: &Request<'_>, _parent: u64, _name: &OsStr, _mode: u32, reply: ReplyEntry) { 211 | reply.error(ENOSYS); 212 | } 213 | fn unlink(&mut self, _req: &Request<'_>, _parent: u64, _name: &OsStr, reply: ReplyEmpty) { 214 | reply.error(ENOSYS); 215 | } 216 | fn rmdir(&mut self, _req: &Request<'_>, _parent: u64, _name: &OsStr, reply: ReplyEmpty) { 217 | reply.error(ENOSYS); 218 | } 219 | fn symlink(&mut self, _req: &Request<'_>, _parent: u64, _name: &OsStr, _link: &Path, reply: ReplyEntry) { 220 | reply.error(ENOSYS); 221 | } 222 | fn rename(&mut self, _req: &Request<'_>, _parent: u64, _name: &OsStr, _newparent: u64, _newname: &OsStr, reply: ReplyEmpty) { 223 | reply.error(ENOSYS); 224 | } 225 | fn link(&mut self, _req: &Request<'_>, _ino: u64, _newparent: u64, _newname: &OsStr, reply: ReplyEntry) { 226 | reply.error(ENOSYS); 227 | } 228 | fn open(&mut self, _req: &Request<'_>, _ino: u64, _flags: u32, reply: ReplyOpen) { 229 | reply.opened(0, 0); 230 | } 231 | fn read(&mut self, _req: &Request<'_>, _ino: u64, _fh: u64, _offset: i64, _size: u32, reply: ReplyData) { 232 | reply.error(ENOSYS); 233 | } 234 | fn write(&mut self, _req: &Request<'_>, _ino: u64, _fh: u64, _offset: i64, _data: &[u8], _flags: u32, reply: ReplyWrite) { 235 | reply.error(ENOSYS); 236 | } 237 | fn flush(&mut self, _req: &Request<'_>, _ino: u64, _fh: u64, _lock_owner: u64, reply: ReplyEmpty) { 238 | reply.error(ENOSYS); 239 | } 240 | fn release(&mut self, _req: &Request<'_>, _ino: u64, _fh: u64, _flags: u32, _lock_owner: u64, _flush: bool, reply: ReplyEmpty) { 241 | reply.ok(); 242 | } 243 | fn fsync(&mut self, _req: &Request<'_>, _ino: u64, _fh: u64, _datasync: bool, reply: ReplyEmpty) { 244 | reply.error(ENOSYS); 245 | } 246 | fn opendir(&mut self, _req: &Request<'_>, _ino: u64, _flags: u32, reply: ReplyOpen) { 247 | reply.opened(0, 0); 248 | } 249 | fn readdir(&mut self, _req: &Request<'_>, _ino: u64, _fh: u64, _offset: i64, reply: ReplyDirectory) { 250 | reply.error(ENOSYS); 251 | } 252 | fn releasedir(&mut self, _req: &Request<'_>, _ino: u64, _fh: u64, _flags: u32, reply: ReplyEmpty) { 253 | reply.ok(); 254 | } 255 | fn fsyncdir (&mut self, _req: &Request<'_>, _ino: u64, _fh: u64, _datasync: bool, reply: ReplyEmpty) { 256 | reply.error(ENOSYS); 257 | } 258 | fn statfs(&mut self, _req: &Request<'_>, _ino: u64, reply: ReplyStatfs) { 259 | reply.statfs(0, 0, 0, 0, 0, 512, 255, 0); 260 | } 261 | fn setxattr(&mut self, _req: &Request<'_>, _ino: u64, _name: &OsStr, _value: &[u8], _flags: u32, _position: u32, reply: ReplyEmpty) { 262 | reply.error(ENOSYS); 263 | } 264 | fn getxattr(&mut self, _req: &Request<'_>, _ino: u64, _name: &OsStr, _size: u32, reply: ReplyXattr) { 265 | reply.error(ENOSYS); 266 | } 267 | fn listxattr(&mut self, _req: &Request<'_>, _ino: u64, _size: u32, reply: ReplyXattr) { 268 | reply.error(ENOSYS); 269 | } 270 | fn removexattr(&mut self, _req: &Request<'_>, _ino: u64, _name: &OsStr, reply: ReplyEmpty) { 271 | reply.error(ENOSYS); 272 | } 273 | fn access(&mut self, _req: &Request<'_>, _ino: u64, _mask: u32, reply: ReplyEmpty) { 274 | reply.error(ENOSYS); 275 | } 276 | fn create(&mut self, _req: &Request<'_>, _parent: u64, _name: &OsStr, _mode: u32, _flags: u32, reply: ReplyCreate) { 277 | reply.error(ENOSYS); 278 | } 279 | fn getlk(&mut self, _req: &Request<'_>, _ino: u64, _fh: u64, _lock_owner: u64, _start: u64, _end: u64, _typ: u32, _pid: u32, reply: ReplyLock) { 280 | reply.error(ENOSYS); 281 | } 282 | fn setlk(&mut self, _req: &Request<'_>, _ino: u64, _fh: u64, _lock_owner: u64, _start: u64, _end: u64, _typ: u32, _pid: u32, _sleep: bool, reply: ReplyEmpty) { 283 | reply.error(ENOSYS); 284 | } 285 | fn bmap(&mut self, _req: &Request<'_>, _ino: u64, _blocksize: u32, _idx: u64, reply: ReplyBmap) { 286 | reply.error(ENOSYS); 287 | } 288 | #[cfg(target_os = "macos")] 289 | fn setvolname(&mut self, _req: &Request<'_>, _name: &OsStr, reply: ReplyEmpty) { 290 | reply.error(ENOSYS); 291 | } 292 | #[cfg(target_os = "macos")] 293 | fn exchange(&mut self, _req: &Request<'_>, _parent: u64, _name: &OsStr, _newparent: u64, _newname: &OsStr, _options: u64, reply: ReplyEmpty) { 294 | reply.error(ENOSYS); 295 | } 296 | #[cfg(target_os = "macos")] 297 | fn getxtimes(&mut self, _req: &Request<'_>, _ino: u64, reply: ReplyXTimes) { 298 | reply.error(ENOSYS); 299 | } 300 | } 301 | ``` 302 | 303 | ### 戻り値 304 | 各関数に戻り値は存在せず、 `reply` 引数を操作して、呼び出し元に値を受け渡す。 305 | 306 | `reply.ok()` `reply.error(ENOSYS)` `reply.attr(...)` 等を使う。 307 | 308 | ### init 309 | マウント後最初に呼ばれる。初期化が必要な場合、ここで行う。 310 | 311 | 今回はデータベースの接続と、必要なら初期化を行う。 312 | 313 | ### destroy 314 | アンマウント時に呼ばれる。データベースから切断する。 315 | 316 | ### lookup 317 | 親ディレクトリのinode、当該ディレクトリ/ファイルの名前が与えられるので、ディレクトリエントリを返す。 318 | この時、inodeの lookup count を1増やさなければならない(forgetで0に戻す) 319 | 320 | lookup count については、 `lib.rs` によると、 321 | 「lookup count がある内は参照カウントが0になってもinodeを削除しないでね」という話 322 | 以降ReplyEntry と ReplyCreateがある全ての関数が呼ばれるたびに、1ずつ増やしていく。 323 | 324 | [forgetについての議論](http://fuse.996288.n3.nabble.com/forget-inodes-td9599.html) 325 | 326 | 必要なデータは以下の通り 327 | 328 | ``` 329 | //正常 330 | reply.entry(&TTL, &ATTR, &GENERATION); 331 | エラー 332 | reply.error(ENOENT); 333 | ``` 334 | 335 | - TTL 336 | 337 | `std::time::Duration` で期間を指定する。 338 | TTLの間はカーネルは再度問い合わせに来ない。 339 | 340 | - ATTR 341 | 342 | 対象の情報。 `fuse::FileAttr` を返す 343 | 344 | - generation 345 | 346 | inodeの世代情報。削除されたinodeに別のファイルを割り当てた場合、 347 | 前のファイルと違うファイルである事を示すために、generationに別の値を割り当てる。 348 | ただし、この値をチェックするのは(知られているものでは)nfsしかない。 349 | 今回はinodeの使い回しが無いので、常時 `0` に設定する 350 | 351 | [libfuseの説明](https://libfuse.github.io/doxygen/structfuse__entry__param.html#a4c673ec62c76f7d63d326407beb1b463) 352 | 353 | - ENOENT 354 | 355 | 対象のディレクトリエントリが存在しない場合 356 | 357 | ### forget 358 | 対象のinodeの参照カウントを nlookup だけ減らす。 359 | `The filesystem may ignore forget calls, if the inodes don't need to have a limited lifetime.` 360 | だそうです。ファイルが削除できるファイルシステムの場合は注意しないといけない。 361 | 362 | アンマウント時にはforgetが呼ばれる事が保証されないが、全てのinodeのnlookupが0になる事が期待される。 363 | 364 | ### getattr 365 | ファイルの属性を返す。 366 | 内容については `lookup` で返す `ATTR` と同じ。 367 | 368 | ### setattr 369 | ファイルの属性を設定する。 370 | 引数にOptionで各属性がぞろぞろとやってくるので、設定していく。 371 | 372 | ``` 373 | _ino: u64, 374 | _mode: Option, 375 | _uid: Option, 376 | _gid: Option, 377 | _size: Option, 378 | _atime: Option, 379 | _mtime: Option, 380 | _fh: Option, 381 | _crtime: Option, 382 | _chgtime: Option, 383 | _bkuptime: Option 384 | _flags: Option` 385 | 386 | 387 | ``` 388 | 389 | 返す値はgetattrと同じで、設定後の属性一覧を返す。 390 | 391 | ### readlink 392 | シンボリックリンクを読み込む。 393 | 対象のフルパスの文字列をReplyDataに入れる。 394 | 395 | ### mknod 396 | 親ディレクトリのinode, ファイル名, モード, デバイス番号が指定されるので、ファイルまたはスペシャルファイルを作成する。 397 | `create` が定義されている場合、通常ファイルについてはそちらが呼ばれる、と `libfuse` には書かれているが、rust-fuseはそういう動作をしない 398 | 大抵の仮想ファイルシステムではスペシャルファイルはエラーでよいと思われる。mknodを実装していないシステムも多い。 399 | 作成対象がどのファイルかは `_mode` で調べる。 例えば通常ファイルかどうか調べる場合は `libc::S_IFREG` を使うとよい。 400 | 401 | ### mkdir 402 | 親ディレクトリのinode, ディレクトリ名, モードが指定されるので、ディレクトリを作る。 403 | 成功した場合、attrを返す 404 | 405 | 動作、エラーなどは `mkdir(2)` に従う 406 | 407 | ### unlink 408 | 親ディレクトリのinode, ディレクトリ名が指定されるので、ファイルを削除する。 409 | 410 | `lookup count` が0でない場合、0になるタイミングまで削除を遅延する。 411 | 412 | ### rmdir 413 | 親ディレクトリのinode, ディレクトリ名が指定されるので、ディレクトリを削除する。 414 | 415 | 当然ながらディレクトリ内になにかある場合は削除できない。 416 | 417 | `lookup count` が0でない場合、0になるタイミングまで削除を遅延する。 418 | 419 | ### symlink 420 | 親ディレクトリのinode, シンボリックリンク名, シンボリックリンク先が与えられるので、シンボリックリンクを作成する。 421 | 422 | ### rename 423 | 親ディレクトリのinode, 名前, 変更後の親ディレクトリのinode, 変更後の名前が指定されるので、ファイルまたはディレクトリ名前を変更する。 424 | 425 | cの `fuse_lowlevel` の説明によると、変更先が存在する場合は自動で上書きしなければならない。 426 | 変更先の `lookup count` が0でない場合は、削除処理と同様0になるまでinodeの削除を遅延する。 427 | 428 | `ENOSYS` を返した場合、後続のbmap等の処理はファイルシステムに渡される前に失敗する。 429 | 430 | cだと 上書き禁止を指定したりできる `flag` が指定されるが、このライブラリには無いようである。 431 | 432 | ### link 433 | 対象のinode, 親ディレクトリのinode, 名前が与えられるので、ハードリンクを作成する。 434 | 435 | ### open 436 | inodeで指定されたファイルを開く。 437 | 438 | #### 引数のフラグ 439 | フラグは `_flags` 引数で渡される。 440 | ただし、 `O_CREAT, O_EXCL, O_NOCTTY` の3つはカーネルで省かれるので、ファイルシステムは検知できない。 441 | 442 | ファイルシステムは、アクセスモードのフラグを使ってアクセス権チェックを行わないといけない。 443 | ただし、マウントオプションで `-o default_permissions` が指定されている場合はカーネルがチェックしてくれるので、 444 | このオプションがある場合は何もしなくてよい。 445 | 446 | ライトバックキャッシュが有効の時、カーネルは `O_WRONLY` でもreadしてくる事がある。 447 | マウントオプションで `-o writeback` が有効の場合は読めるようにしておく。 448 | [libfuseのサンプルの修正例](https://github.com/libfuse/libfuse/commit/b3109e71faf2713402f70d226617352815f6c72e) 449 | を見るとよい。 450 | 451 | ライトバックキャッシュが無効の時、ファイルシステムは `O_APPEND` フラグを適切に扱う必要がある。 452 | つまり、 `O_APPEND` を検知して、全ての `write` の中で `offset` の値にかかわらずデータがファイル末尾に追記されるようにチェックしなければならない。 453 | 454 | ライトバックキャッシュが有効の時、 `O_APPEND` はカーネルが扱う。 `offset` はカーネルが適切に設定してくれる。 455 | ファイルシステムは無視するか、エラーを返さないといけない。 456 | 先述のlibfuseのサンプルの修正例を参考にすること。 457 | 458 | ここに書かれていないフラグも、 `open(2)` の定義通りに動作しなければならない。 459 | [このページ](https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=236340) によると、Linux4.9.0ではフラグの伝達は以下のような挙動になる 460 | 461 | |flag|create|open| 462 | |---|---|---| 463 | |O_CREAT|yes|no| 464 | |O_EXCL|yes|no| 465 | |O_NOCTTY|no|no| 466 | |O_TRUNC|yes|yes| 467 | |O_APPEND|yes|yes| 468 | |O_NONBLOCK|yes|yes| 469 | |O_SYNC|yes|yes| 470 | |O_ASYNC|yes|yes| 471 | |O_LARGEFILE||yes, even if I don't ask for it!| 472 | |O_DIRECTORY|N/A|N/A. open is translated to OPENDIR| 473 | |O_NOFOLLOW|yes|yes| 474 | |O_CLOEXEC|no|no| 475 | |O_DIRECT|yes|yes| 476 | |O_NOATIME|yes|yes| 477 | |O_PATH|N/A|N/A doesn't actually open anything| 478 | |O_DSYNC|yes|yes| 479 | |O_TMPFILE|N/A|N/A includes O_DIRECTORY| 480 | |O_EXEC||Not implemented on Linux| 481 | 482 | 483 | 484 | #### ファイルハンドル 485 | ファイルシステムは `fh: u64` を戻り値に含めることができる( `reply.opened()` の1番目の引数)。 486 | 487 | fhには、ポインター、インデックス、その他好きな値をファイルシステム側で定める事ができる。 488 | この値は `read` `write` 等で引数として渡されるので、ファイルシステム自身で状態を持たずに済む。 489 | cでいうと、 `fi->fh` である。 490 | もちろんこの機能を使わなくともよい。 491 | 492 | #### 戻り値のフラグ 493 | ファイルシステムはフラグを戻り値に含めることができる( `reply.opened()` の2番目の引数)。 494 | `fuse-abi` の `FOPEN_DIRECT_IO` `FOPEN_KEEP_CACHE` `FOPEN_NONSEEKABLE` `FOPEN_PURGE_ATTR` `FOPEN_PURGE_UBC` 495 | が相当する。(それぞれビットマスク) 496 | 497 | 通常はあまり使わないと思われるので、詳しく知りたい場合は [libfuseのfuse_common.h](https://github.com/libfuse/libfuse/blob/master/include/fuse_common.h) 498 | を参照すること。 499 | 500 | ### read 501 | inodeで指定されたファイルをoffsetからsize分読み込む 502 | 503 | ファイルの読み込む位置を指定する方法は色々とあるが、fuseは `pread(2)` 相当の関数を一つ実装するだけで済むようにしてくれている。 504 | 505 | EOFまたはエラーを返す場合を除いて、readはsizeで指定されたサイズのデータを返さないといけない。実データが足りない場合は0埋めされる。 506 | 例えば、長さ200byteのデータに対して、4096byteの要求が来ることがあるが、200byte返すと3896byte分を0埋めしたとみなされる。 507 | 例外として、`direct_io` フラグを指定した場合、カーネルは `read(2)` システムコールの戻り値として、 508 | ファイルシステムの戻り値を直接使うので、sizeより小さいデータを返してもよい。 509 | 510 | 引数の `fh` は `open` 時にファイルシステムが指定した値である。 511 | 512 | ### write 513 | inodeで指定されたファイルにデータを書き込む 514 | 515 | ファイルの書き込む位置を指定する方法は色々とあるが、fuseは `pwrite(2)` 相当の関数を一つ実装するだけで済むようにしてくれている。 516 | 517 | `direct_io` が設定されていない場合、エラーを返す場合を除いて、writeはsizeで指定された数字を返さないといけない。 518 | 519 | 引数の `fh` は `open` 時にファイルシステムが指定した値である。 520 | 521 | `open` の項で述べたように、 `O_APPEND` が設定されている場合は適切に処理しなければならない。 522 | 523 | ### flush 524 | `close(2)` システムコールの度に呼ばれる。 525 | 526 | `release` は値を返さないので、 `close(2)` に対してエラーを返したい場合はここで行う。 527 | 528 | `dup, dup2, fork` によりプロセスが複製される事で、一つの `open` に対して、複数の `flush` が呼ばれる場合がある。 529 | どれが最後の `flush` なのか識別するのは不可能なので、後で(または `flush` 処理中に) 別の `flush` が呼ばれてもいいように対応しなければならない。 530 | 531 | 例えば、sshfsでは、スレッド単位でロックをかけて書き込み処理の後始末を行っている。 532 | 533 | `flush` という名前が付いてはいるが、 `fsync` のようにデータをディスクに書き込む事を義務付けられてはいない。 534 | `close(2)` 時にデータが書き込まれているかどうかは使用者側の責任である。 535 | 536 | `setlk` `getlk` のようなファイルロック機構をファイルシステムが実装している場合、引数の `_lock_owner` が持つロックを全て開放すること。 537 | 538 | ### release 539 | ファイルを閉じる。 540 | ファイルに対する参照が一つもなくなった場合に呼ばれる。一つの `open` に対して、一つの `release` が呼ばれる。 541 | 542 | ファイルシステムはエラーを返してもよいが、呼び出し元の `close(2)` や `munmap(2)` には値が渡らないので、無意味である。 543 | 544 | 引数の `_fh` は `open` 時にファイルシステムが指定した値であり、 `_flags` は `open` 時の引数と同一の値である。 545 | 546 | ### fsync 547 | ファイルを永続領域に書き込む。 548 | 549 | fsyncが呼ばれるまでは、書き込まれたデータやメタデータはキャッシュしていてよい。 550 | つまり、なんらかの事情(kill, マシンの電源断)でファイルシステムのデーモンが即座に終了したとしても、データの保証はしなくてよい。 551 | 552 | 一方、fsyncに対して `reply.ok()` を返した時点で、データがディスクやネットワークの先などどこかの領域に保存されている事を保証しなければならない。 553 | 554 | 引数 `_datasync` が `true` である場合、メタデータは書き込まなくてもよい。 555 | 556 | ### opendir 557 | ディレクトリを開く。 558 | 559 | ファイル同様、 `fh: u64` を戻り値に含めることができる( `reply.opened()` の1番目の引数)。 560 | `fh` に何も入れないことも可能だが、 `opendir` から `relasedir` までの間に 561 | ディレクトリエントリが追加または削除された場合でも `readdir` の整合性を保つために、何らかの情報を入れておく事が推奨される。 562 | open中に追加または削除されたエントリは返しても返さなくても良いが、追加または削除されていないエントリは必ず返さないといけないので、 563 | ディレクトリエントリをコピーして、先頭のポインタを格納する、等をするとよい。 564 | 565 | ### readdir 566 | 指定されたinodeのディレクトリのディレクトリエントリを返す。 567 | バッファが渡されるので、一杯になるまでディレクトリエントリを入れて返す。 568 | 569 | 引数の `_fh` は `opendir` でファイルシステムが渡した値である。 570 | 571 | cでは `fuse_add_direntry()` を使用してバッファを埋めるが、rustでは渡された `reply: ReplyDirectory` を使用する。 572 | 573 | ``` 574 | result = reply.add(target_inode, offset, FileType.RegularFile, filename); 575 | ``` 576 | 577 | バッファが一杯の時、 `ReplyDirectory.add()` は `true` を返す。 578 | 579 | `offset` はファイルシステムが任意に決めたオフセットである。 580 | 何らかの意味を持つ値でなくともよいが、ファイルシステムは `offset` が与えられたとき、対応する一意のディレクトリエントリを求められなければならない。 581 | カーネルが`readdir`の 引数として `_offset` に0でない値を指定してきた場合、 582 | 該当の `offset` を持つディレクトリエントリの次のディレクトリエントリから返さなければならない。 583 | つまり、 `offset` は「次のディレクトリエントリのoffset」を意味する。 584 | `0` は「最初のディレクトリエントリ」を指すので、 `offset` に0を入れてはならない。 585 | 586 | `.` と `..` は返さなくともよいが、返さなかった場合の処理は呼び出し側のプログラムに依存する。 587 | 588 | `reply.add()` でデータを追加していき、最終的に `reply.ok()` を実行すると、データが返せる。 589 | 590 | ### releasedir 591 | `opendir` で確保したリソースを解放する。 592 | 引数の `_fh` は `opendir` でファイルシステムが渡した値である。 593 | 594 | 一度の `opendir` に対して、一度だけ `releasedir` が呼び出される。 595 | 596 | ### fsyncdir 597 | ディレクトリのデータ(ディレクトリエントリ)をディスクに書き込む。 598 | 599 | 引数の `_datasync` が `true` の時、メタデータを更新しない。 600 | 601 | サンプルを見るとディレクトリに `fsync(2)` した時の挙動でいい様な感じがする。 602 | `sshfs` や `s3fs` で実装されていないので、実装の優先度は低い。 603 | 604 | ### statfs 605 | `statfs(2)` で使うファイルシステムの情報を返す。 606 | 607 | ``` 608 | blocks: u64; // frsize単位での総ブロック数 (ex: 1024) 609 | bfree: u64; // 空きブロック数 610 | bavail: u64; // スーパーユーザ用に予約されている領域を除いた空きブロック数 611 | files: u64; // 総inode数 612 | ffree: u64; // 空きinode数 613 | bsize: u32; // 推奨されるI/Oで使用するブロックのバイト数 (ex: 4096) 614 | namelen: u32; //ファイル名の最大長 615 | frsize: u32; //最小のブロックのバイト数 616 | reply.statfs(blocks, bfree, bavail, files, ffree, bsize, namelen, frsize); 617 | ``` 618 | 619 | ### setxattr 620 | 拡張ファイル属性を設定する。 621 | 引数は `setxattr(2)` と同様である。 622 | 623 | 実装しない( `ENOSYS` を返す) 場合、拡張ファイル属性をサポートしない( `ENOTSUP` と同様)と解釈され、 624 | 以降カーネルからファイルシステムの呼び出しを行わずに失敗する。 625 | 626 | 拡張属性は `_name: _value` 形式で与えられる。 627 | 628 | 引数の `_position` はmacのリソースフォークで使用されている値で、 629 | 基本は0である。osxfuseにのみ存在する引数である。(現在のrustの実装では、mac以外は0を返す) 630 | rust-fuseでは、 `getxattr` の方に [実装されていないまま](https://github.com/zargony/rust-fuse/issues/40) なので、 631 | とりあえず放置でよいと思われる。 632 | 633 | 引数の `_flags` には `XATTR_CREATE` または `XATTR_REPLACE` が指定される。 634 | `XATTR_CREATE` が指定された場合、既に属性が存在する場合は失敗する。 635 | `XATTR_REPLACE` が指定された場合、属性が存在しない場合失敗する。 636 | デフォルトでは、属性が存在しない場合作成し、存在する場合は値を置き換える。 637 | 638 | ### getxattr 639 | 拡張ファイル属性を取得する。 640 | 641 | 引数の `_size` が0の場合、値のサイズを `reply.size()` に入れる。 642 | 643 | 0でない場合、値のサイズが `_size` 以下の場合、 `reply.data()` に値を入れて返す。 644 | `_size` を超える場合、 `reply.error(ERANGE)` を返す。 645 | 646 | ### listxattr 647 | セットされている拡張ファイル属性の名前一覧を得る。 648 | 649 | データは、「ヌル終端された文字列が連続して並んでいる」フォーマットである。 650 | ex: `xxx.data\0yyy.name\0` 651 | 652 | 引数の `_size` が0の場合、データのサイズを `reply.size()` に入れる。 653 | 654 | 0でない場合、データのサイズが `_size` 以下の場合、 `reply.data()` にデータを入れて返す。 655 | `_size` を超える場合、 `reply.error(ERANGE)` を返す。 656 | 657 | ### removexattr 658 | セットされている拡張ファイル属性を削除する 659 | 660 | ### access 661 | ファイルのアクセス権を確認する。 662 | 663 | 引数およびエラーの内容は、 `access(2)` に準ずる。 664 | 665 | `access(2)` および `chdir(2)` の時に呼ばれる。 666 | マウントオプションで `default_permissions` が指定されている場合は呼ばれない。 667 | 668 | ### create 669 | ファイルを作成する。 670 | 671 | ファイルが存在しない場合、引数の `_mode` で指定されたモードでファイルを作成し、開く。 672 | 673 | `open` と同じ動作のため、open時のフラグが `_flags` で渡される。その他処理は `open` に準ずる。 674 | 675 | `create` が実装されていない場合、カーネルは `mknod` と `open` を実行する。 676 | 677 | ### getlk 678 | POSIXのレコードロックのテストを行う (ロックに関しては `fcntl(2)` の `F_GETLK` を参照) 679 | `_lock_owner: u64, _start: u64, _end: u64, _typ: u32, _pid` 680 | 681 | `_typ` は `F_RDLCK, F_WRLCK, F_UNLCK` のいずれかである。 682 | 683 | ファイルの該当の範囲がロックできるか調べる。 684 | ユーザのチェックは `_lock_owner` のみで行い、 `pid` は値を返す目的でのみ使用すること。 685 | 686 | ### setlk 687 | POSIXのレコードロックを設定/解除する。 688 | 689 | なお、この関数を実装しない場合でも、カーネルは自前でロック処理を行ってくれる。 690 | ネットワーク越しのファイルを操作するなど、ファイルシステム側でロック処理を行う必要がある場合に実装する。 691 | 692 | `_ino: u64, _fh: u64, _lock_owner: u64, _start: u64, _end: u64, _typ: u32, _pid: u32, _sleep: bool` 693 | 694 | 引数の `_sleep` がtrueの場合、 `F_SETLKW` と同等の処理を行う。 695 | つまり、ロックが解除されるまで待たなければならない。シグナルを受けた場合は終了して `EINTR` を返す。 696 | 697 | ### bmap 698 | オブジェクト内の論理ブロックをデバイスの物理ブロックに結びつけるために使われる。 699 | つまり、 inodeとブロックのインデックスを与えると、ファイルシステム全体でどこのブロックを使っているかを返す。 700 | 701 | vfsではFIBMAP(ioctl)とswapファイルの操作に使われている。 702 | マウントオプションで `blkdev` を指定した場合(ユーザからはブロックデバイスとして見える)にのみ意味がある。 703 | 704 | ### mac専用関数 705 | `setvolname` `exchange` `getxtimes` はmacOS専用関数である。 706 | ドキュメントもあまり無いので無視する。 707 | 708 | ### 未実装の関数 709 | libfuseにはあるがrust-fuseでは未実装(0.3.1現在)の関数一覧を記す。 710 | 711 | `ioctl` `poll` `write_buf` `retrieve_reply` `forget_multi` `flock` `fallocate` `readdirplus` `copy_file_range` 712 | 713 | ## マウント 714 | サンプルの `HelloFS` を参考にマウントする。 715 | 716 | ``` 717 | 718 | struct SqliteFS; 719 | 720 | impl Filesystem for SqliteFS { 721 | //ここに実装 722 | } 723 | 724 | fn main() { 725 | let mountpoint = env::args_os().nth(1).unwrap(); // 引数からマウントポイントを取得 726 | let options = ["-o", "fsname=sqlitefs"] 727 | .iter() 728 | .map(|o| o.as_ref()) 729 | .collect::>(); // マウントオプションを設定 730 | fuse::mount(SqliteFS, mountpoint, &options).unwrap(); 731 | } 732 | ``` 733 | -------------------------------------------------------------------------------- /src/db_module.rs: -------------------------------------------------------------------------------- 1 | pub mod sqlite; 2 | use std::time::SystemTime; 3 | use crate::sqerror::Result; 4 | use fuse::{FileAttr, FileType}; 5 | use time::Timespec; 6 | use chrono::{DateTime, Utc, NaiveDateTime}; 7 | 8 | pub trait DbModule { 9 | /// Create tables (if not found) and add root directory (if not found) 10 | fn init(&mut self) -> Result<()>; 11 | /// Get metadata. If not found, return None 12 | fn get_inode(&self, inode: u32) -> Result>; 13 | /// Add a file or a directory. 14 | /// Update atime, mtime, ctime. Update mtime and ctime of the parent directory. 15 | fn add_inode_and_dentry(&mut self, parent: u32, name: &str, attr: &DBFileAttr) -> Result; 16 | /// Update file metadata. 17 | /// Update ctime. Update mtime if filesize is changed. 18 | fn update_inode(&mut self, attr: &DBFileAttr, truncate: bool) -> Result<()>; 19 | // Delete an inode if the link count is zero. 20 | fn delete_inode_if_noref(&mut self, inode: u32) -> Result<()>; 21 | /// Get directory entries 22 | fn get_dentry(&self, inode: u32) -> Result>; 23 | /// Add a new directory entry which is hard link 24 | /// Update mtime, Update mtime and ctime of the parent directory. 25 | fn link_dentry(&mut self, inode: u32, parent: u32, name: &str) -> Result; 26 | /// Delete a dentry. returns target inode. 27 | /// Update ctime. Update mtime and ctime of the parent directory. 28 | fn delete_dentry(&mut self, parent: u32, name: &str) -> Result; 29 | /// Move dentry to another parent or name. Return inode number if a new file is overwrote. 30 | /// Update ctime, and mtime and ctime of the parent directories. 31 | fn move_dentry(&mut self, parent: u32, name: &str, new_parent: u32, new_name: &str) -> Result>; 32 | /// check a directory if it is empty. 33 | fn check_directory_is_empty(&self, inode: u32) -> Result; 34 | /// lookup a directory entry table and get a file attribute. 35 | /// If not found, return None. 36 | /// Update atime. 37 | fn lookup(&mut self, parent: u32, name: &str) -> Result>; 38 | /// Read data from a whole block. 39 | /// Update atime. 40 | fn get_data(&mut self, inode: u32, block: u32, length: u32) -> Result>; 41 | /// Write data into a whole block. 42 | /// Update mtime and ctime. 43 | fn write_data(&mut self, inode:u32, block: u32, data: &[u8], size: u32) -> Result<()>; 44 | /// Release all data related to an inode number. 45 | fn release_data(&self, inode: u32) -> Result<()>; 46 | /// Delete all inodes which nlink is 0. 47 | fn delete_all_noref_inode(&mut self) -> Result<()>; 48 | /// Get block size of the filesystem 49 | fn get_db_block_size(&self) -> u32; 50 | /// Set xattr value. 51 | fn set_xattr(&mut self, inode: u32, key: &str, value: &[u8]) -> Result<()>; 52 | /// Get xattr value. 53 | fn get_xattr(&self, inode: u32, key: &str) -> Result>; 54 | /// List xattr name. 55 | fn list_xattr(&self, inode: u32) -> Result>; 56 | /// Delete xattr 57 | fn delete_xattr(&mut self, inode: u32, key: &str) -> Result<()>; 58 | } 59 | 60 | // Imported from rust-fuse 4.0-dev 61 | // This time format differs from v3.1 62 | #[derive(Clone, Copy, Debug, Hash, PartialEq)] 63 | pub struct DBFileAttr { 64 | /// Inode number 65 | pub ino: u32, 66 | /// Size in bytes 67 | pub size: u32, 68 | /// block size 69 | pub blocks: u32, 70 | /// Time of last access 71 | pub atime: SystemTime, 72 | /// Time of last modification 73 | pub mtime: SystemTime, 74 | /// Time of last change 75 | pub ctime: SystemTime, 76 | /// Time of creation (macOS only) 77 | pub crtime: SystemTime, 78 | /// file type 79 | pub kind: FileType, 80 | /// Permissions 81 | pub perm: u16, 82 | /// Number of hard links 83 | pub nlink: u32, 84 | /// User id 85 | pub uid: u32, 86 | /// Group id 87 | pub gid: u32, 88 | /// Rdev 89 | pub rdev: u32, 90 | /// Flags (macOS only, see chflags(2)) 91 | pub flags: u32, 92 | } 93 | 94 | impl DBFileAttr { 95 | fn timespec_from(&self, st: &SystemTime) -> Timespec { 96 | if let Ok(dur_since_epoch) = st.duration_since(std::time::UNIX_EPOCH) { 97 | Timespec::new(dur_since_epoch.as_secs() as i64, 98 | dur_since_epoch.subsec_nanos() as i32) 99 | } else { 100 | Timespec::new(0, 0) 101 | } 102 | } 103 | 104 | pub fn datetime_from(&self, ts: &Timespec) -> SystemTime { 105 | let dt = DateTime::::from_utc(NaiveDateTime::from_timestamp(ts.sec, ts.nsec as u32), Utc); 106 | SystemTime::from(dt) 107 | } 108 | 109 | pub fn get_file_attr(&self) -> FileAttr { 110 | FileAttr { 111 | ino: self.ino as u64, 112 | size: self.size as u64, 113 | blocks: self.blocks as u64, 114 | atime: self.timespec_from(&self.atime), 115 | mtime: self.timespec_from(&self.mtime), 116 | ctime: self.timespec_from(&self.ctime), 117 | crtime: self.timespec_from(&self.crtime), 118 | kind: self.kind, 119 | perm: self.perm, 120 | nlink: self.nlink, 121 | uid: self.uid, 122 | gid: self.gid, 123 | rdev: self.rdev, 124 | flags: self.flags, 125 | } 126 | } 127 | } 128 | 129 | pub struct DEntry { 130 | pub parent_ino: u32, 131 | pub child_ino: u32, 132 | pub filename: String, 133 | pub file_type: FileType, 134 | } 135 | -------------------------------------------------------------------------------- /src/db_module/sqlite.rs: -------------------------------------------------------------------------------- 1 | use std::path::Path; 2 | use std::time::SystemTime; 3 | use chrono::{Utc, DateTime, NaiveDateTime, Timelike}; 4 | use rusqlite::types::ToSql; 5 | use rusqlite::{params, Connection, NO_PARAMS, Statement}; 6 | use crate::db_module::{DbModule, DBFileAttr, DEntry}; 7 | use crate::sqerror::{Error, Result, ErrorKind}; 8 | use fuse::FileType; 9 | 10 | const DB_IFIFO: u32 = 0o0_010_000; 11 | const DB_IFCHR: u32 = 0o0_020_000; 12 | const DB_IFDIR: u32 = 0o0_040_000; 13 | const DB_IFBLK: u32 = 0o0_060_000; 14 | const DB_IFREG: u32 = 0o0_100_000; 15 | const DB_IFLNK: u32 = 0o0_120_000; 16 | const DB_IFSOCK: u32 = 0o0_140_000; 17 | 18 | const BLOCK_SIZE: u32 = 4096; 19 | 20 | fn string_to_systemtime(text: String, nsec: u32) -> SystemTime { 21 | SystemTime::from(DateTime::::from_utc( 22 | NaiveDateTime::parse_from_str(&text, "%Y-%m-%d %H:%M:%S").unwrap().with_nanosecond(nsec).unwrap(), Utc 23 | )) 24 | } 25 | 26 | fn file_type_to_const(kind: FileType) -> u32 { 27 | match kind { 28 | FileType::RegularFile => DB_IFREG, 29 | FileType::Socket => DB_IFSOCK, 30 | FileType::Directory => DB_IFDIR, 31 | FileType::Symlink => DB_IFLNK, 32 | FileType::BlockDevice => DB_IFBLK, 33 | FileType::CharDevice => DB_IFCHR, 34 | FileType::NamedPipe => DB_IFIFO, 35 | } 36 | } 37 | 38 | fn const_to_file_type(kind: u32) -> FileType { 39 | match kind { 40 | DB_IFREG => FileType::RegularFile, 41 | DB_IFSOCK => FileType::Socket, 42 | DB_IFDIR => FileType::Directory, 43 | DB_IFLNK => FileType::Symlink, 44 | DB_IFBLK => FileType::BlockDevice, 45 | DB_IFCHR => FileType::CharDevice, 46 | DB_IFIFO => FileType::NamedPipe, 47 | _ => FileType::RegularFile, 48 | } 49 | } 50 | 51 | /// Release all data in "inode", after "offset" byte. 52 | fn release_data(inode: u32, offset: u32, tx: &Connection) -> Result<()> { 53 | if offset == 0 { 54 | tx.execute("DELETE FROM data WHERE file_id=$1", params![inode])?; 55 | } else { 56 | let mut block = offset / BLOCK_SIZE; 57 | if offset % BLOCK_SIZE != 0 { 58 | block = offset / BLOCK_SIZE + 1; 59 | let sql = "SELECT data FROM data WHERE file_id=$1 and block_num = $2"; 60 | let mut stmt = tx.prepare(sql)?; 61 | let mut data: Vec = match stmt.query_row(params![inode, block], |row| row.get(0)) { 62 | Ok(n) => n, 63 | Err(err) => { 64 | if err == rusqlite::Error::QueryReturnedNoRows { 65 | vec![0; BLOCK_SIZE as usize] 66 | } else { 67 | return Err(Error::from(err)) 68 | } 69 | } 70 | }; 71 | data.resize((offset % BLOCK_SIZE) as usize, 0); 72 | tx.execute("REPLACE INTO data \ 73 | (file_id, block_num, data) 74 | VALUES($1, $2, $3)", 75 | params![inode, block, data])?; 76 | } 77 | tx.execute("DELETE FROM data WHERE file_id=$1 and block_num > $2", params![inode, block])?; 78 | } 79 | Ok(()) 80 | } 81 | 82 | fn update_time(inode: u32, sql: &str, time: DateTime, tx: &Connection) -> Result<()> { 83 | let mut stmt = tx.prepare(sql)?; 84 | let params = params![&time.format("%Y-%m-%d %H:%M:%S").to_string(), time.timestamp_subsec_nanos(), inode]; 85 | stmt.execute(params)?; 86 | Ok(()) 87 | } 88 | 89 | fn update_atime(inode: u32, time: DateTime, tx: &Connection) -> Result<()> { 90 | let sql = "UPDATE metadata SET atime=datetime($1), atime_nsec=$2 WHERE id=$3"; 91 | update_time(inode, sql, time, tx) 92 | } 93 | 94 | fn update_mtime(inode: u32, time: DateTime, tx: &Connection) -> Result<()> { 95 | let sql = "UPDATE metadata SET mtime=datetime($1), mtime_nsec=$2 WHERE id=$3"; 96 | update_time(inode, sql, time, tx) 97 | } 98 | 99 | fn update_ctime(inode: u32, time: DateTime, tx: &Connection) -> Result<()> { 100 | let sql = "UPDATE metadata SET ctime=datetime($1), ctime_nsec=$2 WHERE id=$3"; 101 | update_time(inode, sql, time, tx) 102 | } 103 | 104 | fn add_dentry(entry: DEntry, tx: &Connection) -> Result<()> { 105 | let sql = "INSERT INTO dentry VALUES($1, $2, $3, $4)"; 106 | tx.execute( 107 | sql, 108 | params![ 109 | entry.parent_ino, 110 | entry.child_ino, 111 | file_type_to_const(entry.file_type), 112 | entry.filename 113 | ] 114 | )?; 115 | Ok(()) 116 | } 117 | 118 | fn parse_attr(mut stmt: Statement, params: &[&dyn ToSql]) -> Result> { 119 | let rows = stmt.query_map(params, |row| { 120 | Ok(DBFileAttr { 121 | ino: row.get(0)?, 122 | size: row.get(1)?, 123 | blocks: row.get(17).unwrap_or(0), 124 | atime: string_to_systemtime(row.get(2)?, row.get(3)?), 125 | mtime: string_to_systemtime(row.get(4)?, row.get(5)?), 126 | ctime: string_to_systemtime(row.get(6)?, row.get(7)?), 127 | crtime: string_to_systemtime(row.get(8)?, row.get(9)?), 128 | kind: const_to_file_type(row.get(10)?), 129 | perm: row.get(11)?, 130 | nlink: row.get(12)?, 131 | uid: row.get(13)?, 132 | gid: row.get(14)?, 133 | rdev: row.get(15)?, 134 | flags: row.get(16)? 135 | }) 136 | })?; 137 | let mut attrs = Vec::new(); 138 | for row in rows { 139 | attrs.push(row?); 140 | } 141 | if attrs.is_empty() { 142 | Ok(None) 143 | } else { 144 | Ok(Some(attrs[0])) 145 | } 146 | } 147 | 148 | fn get_inode_local(inode: u32, tx: &Connection) -> Result> { 149 | let sql = "SELECT \ 150 | metadata.id,\ 151 | metadata.size,\ 152 | metadata.atime,\ 153 | metadata.atime_nsec,\ 154 | metadata.mtime,\ 155 | metadata.mtime_nsec,\ 156 | metadata.ctime,\ 157 | metadata.ctime_nsec,\ 158 | metadata.crtime,\ 159 | metadata.crtime_nsec,\ 160 | metadata.kind, \ 161 | metadata.mode,\ 162 | ncount.nlink,\ 163 | metadata.uid,\ 164 | metadata.gid,\ 165 | metadata.rdev,\ 166 | metadata.flags,\ 167 | blocknum.block_num \ 168 | FROM metadata \ 169 | LEFT JOIN (SELECT count(block_num) block_num FROM data WHERE file_id=$1) AS blocknum \ 170 | LEFT JOIN ( SELECT COUNT(child_id) nlink FROM dentry WHERE child_id=$1 GROUP BY child_id) AS ncount \ 171 | WHERE id=$1"; 172 | let stmt = tx.prepare(sql)?; 173 | let params = params![inode]; 174 | parse_attr(stmt, params) 175 | } 176 | 177 | fn get_dentry_single(parent: u32, name: &str, tx: &Connection) -> Result> { 178 | let sql = "SELECT child_id, file_type FROM dentry WHERE parent_id=$1 and name=$2"; 179 | let mut stmt = tx.prepare(sql)?; 180 | let res: Option = match stmt.query_row( 181 | params![parent, name], |row| Ok(Some(DEntry{ 182 | parent_ino: parent, 183 | child_ino: row.get(0)?, 184 | file_type: const_to_file_type(row.get(1)?), 185 | filename: name.to_string() 186 | })) 187 | ) { 188 | Ok(n) => n, 189 | Err(err) => { 190 | if err == rusqlite::Error::QueryReturnedNoRows { 191 | None 192 | } else { 193 | return Err(Error::from(err)) 194 | } 195 | } 196 | }; 197 | Ok(res) 198 | } 199 | 200 | fn delete_dentry_local(parent: u32, name: &str, tx: &Connection) -> Result<()> { 201 | let sql = "DELETE FROM dentry WHERE parent_id=$1 and name=$2"; 202 | tx.execute(sql, params![parent, name])?; 203 | Ok(()) 204 | } 205 | 206 | fn delete_sub_dentry(id: u32, tx: &Connection) -> Result<()> { 207 | let sql = "DELETE FROM dentry WHERE parent_id=$1"; 208 | tx.execute(sql, params![id])?; 209 | Ok(()) 210 | } 211 | 212 | fn check_directory_is_empty_local(inode: u32, tx: &Connection) -> Result { 213 | let sql = "SELECT name FROM dentry where parent_id=$1"; 214 | let mut stmt = tx.prepare(sql)?; 215 | let rows = stmt.query_map(params![inode], |row| { 216 | Ok({ 217 | let name: String; 218 | name = row.get(0)?; 219 | name 220 | }) 221 | })?; 222 | for row in rows { 223 | let name = row?; 224 | if &name != "." && &name != ".." { 225 | return Ok(false); 226 | } 227 | } 228 | Ok(true) 229 | } 230 | 231 | fn add_inode_local(attr: &DBFileAttr, tx: &Connection) -> Result { 232 | let sql = "INSERT INTO metadata \ 233 | (size,\ 234 | atime,\ 235 | atime_nsec,\ 236 | mtime,\ 237 | mtime_nsec,\ 238 | ctime,\ 239 | ctime_nsec,\ 240 | crtime,\ 241 | crtime_nsec,\ 242 | kind, \ 243 | mode,\ 244 | nlink,\ 245 | uid,\ 246 | gid,\ 247 | rdev,\ 248 | flags\ 249 | ) \ 250 | VALUES($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16)"; 251 | let atime = DateTime::::from(attr.atime); 252 | let mtime = DateTime::::from(attr.mtime); 253 | let ctime = DateTime::::from(attr.ctime); 254 | let crtime = DateTime::::from(attr.crtime); 255 | { 256 | tx.execute(sql, params![ 257 | attr.size, 258 | atime.format("%Y-%m-%d %H:%M:%S").to_string(), 259 | atime.timestamp_subsec_nanos(), 260 | mtime.format("%Y-%m-%d %H:%M:%S").to_string(), 261 | mtime.timestamp_subsec_nanos(), 262 | ctime.format("%Y-%m-%d %H:%M:%S").to_string(), 263 | ctime.timestamp_subsec_nanos(), 264 | crtime.format("%Y-%m-%d %H:%M:%S").to_string(), 265 | crtime.timestamp_subsec_nanos(), 266 | file_type_to_const(attr.kind), 267 | attr.perm, 268 | 0, 269 | attr.uid, 270 | attr.gid, 271 | attr.rdev, 272 | attr.flags, 273 | ])?; 274 | } 275 | let sql = "SELECT last_insert_rowid()"; 276 | let child: u32; 277 | { 278 | let mut stmt = tx.prepare(sql)?; 279 | child = stmt.query_row(params![], |row| row.get(0))?; 280 | } 281 | Ok(child) 282 | } 283 | 284 | 285 | pub struct Sqlite { 286 | conn: Connection 287 | } 288 | 289 | impl Sqlite { 290 | pub fn new(path: &Path) -> Result { 291 | let conn = Connection::open(path)?; 292 | // enable foreign key. Sqlite ignores foreign key by default. 293 | conn.execute("PRAGMA foreign_keys=ON", NO_PARAMS)?; 294 | Ok(Sqlite { conn }) 295 | } 296 | 297 | pub fn new_in_memory() -> Result { 298 | let conn = Connection::open_in_memory()?; 299 | // enable foreign key. Sqlite ignores foreign key by default. 300 | conn.execute("PRAGMA foreign_keys=ON", NO_PARAMS)?; 301 | Ok(Sqlite { conn }) 302 | } 303 | } 304 | 305 | impl DbModule for Sqlite { 306 | fn init(&mut self) -> Result<()> { 307 | let table_search_sql = "SELECT count(name) FROM sqlite_master WHERE type='table' AND name=$1"; 308 | { 309 | let row_count: u32 = self.conn.query_row(table_search_sql, params!["metadata"], |row| row.get(0) )?; 310 | if row_count == 0 { 311 | let sql = "CREATE TABLE metadata(\ 312 | id integer primary key,\ 313 | size int default 0 not null,\ 314 | atime text,\ 315 | atime_nsec int,\ 316 | mtime text,\ 317 | mtime_nsec int,\ 318 | ctime text,\ 319 | ctime_nsec int,\ 320 | crtime text,\ 321 | crtime_nsec int,\ 322 | kind int,\ 323 | mode int,\ 324 | nlink int default 0 not null,\ 325 | uid int default 0,\ 326 | gid int default 0,\ 327 | rdev int default 0,\ 328 | flags int default 0 \ 329 | )"; 330 | let res = self.conn.execute(sql, params![])?; 331 | debug!("metadata table: {}", res); 332 | } 333 | } 334 | { 335 | let row_count: u32 = self.conn.query_row(table_search_sql, params!["dentry"], |row| row.get(0) )?; 336 | if row_count == 0 { 337 | let sql = "CREATE TABLE dentry(\ 338 | parent_id int,\ 339 | child_id int,\ 340 | file_type int,\ 341 | name text,\ 342 | foreign key (parent_id) references metadata(id) on delete cascade,\ 343 | foreign key (child_id) references metadata(id) on delete cascade,\ 344 | primary key (parent_id, name) \ 345 | )"; 346 | self.conn.execute(sql, params![])?; 347 | } 348 | } 349 | { 350 | let row_count: u32 = self.conn.query_row(table_search_sql, params!["data"], |row| row.get(0) )?; 351 | if row_count == 0 { 352 | let sql = "CREATE TABLE data(\ 353 | file_id int,\ 354 | block_num int,\ 355 | data blob,\ 356 | foreign key (file_id) references metadata(id) on delete cascade,\ 357 | primary key (file_id, block_num) \ 358 | )"; 359 | self.conn.execute(sql, params![])?; 360 | } 361 | } 362 | { 363 | let row_count: u32 = self.conn.query_row(table_search_sql, params!["xattr"], |row| row.get(0) )?; 364 | if row_count == 0 { 365 | let sql = "CREATE TABLE xattr(\ 366 | file_id int,\ 367 | name text,\ 368 | value text,\ 369 | foreign key (file_id) references metadata(id) on delete cascade,\ 370 | primary key (file_id, name) \ 371 | )"; 372 | self.conn.execute(sql, params![])?; 373 | } 374 | } 375 | { 376 | let sql = "SELECT count(id) FROM metadata WHERE id=1"; 377 | let row_count: u32 = self.conn.query_row(sql, params![], |row| row.get(0) )?; 378 | if row_count == 0 { 379 | let now = SystemTime::now(); 380 | let root_dir = DBFileAttr { 381 | ino: 1, 382 | size: 0, 383 | blocks: 0, 384 | atime: now, 385 | mtime: now, 386 | ctime: now, 387 | crtime: now, 388 | kind: FileType::Directory, 389 | perm: 0o40777, 390 | nlink: 0, 391 | uid: 0, 392 | gid: 0, 393 | rdev: 0, 394 | flags: 0 395 | }; 396 | add_inode_local(&root_dir, &self.conn)?; 397 | } 398 | } 399 | { 400 | let sql = "SELECT count(parent_id) FROM dentry WHERE parent_id=1 and name='.'"; 401 | let row_count: u32 = self.conn.query_row(sql, params![], |row| row.get(0) )?; 402 | if row_count == 0 { 403 | let root_dir = DEntry{ 404 | parent_ino: 1, 405 | child_ino: 1, 406 | file_type: FileType::Directory, 407 | filename: ".".to_string() 408 | }; 409 | add_dentry(root_dir, &self.conn)?; 410 | } 411 | } 412 | { 413 | let sql = "SELECT count(parent_id) FROM dentry WHERE parent_id=1 and name='..'"; 414 | let row_count: u32 = self.conn.query_row(sql, params![], |row| row.get(0) )?; 415 | if row_count == 0 { 416 | let root_dir = DEntry{ 417 | parent_ino: 1, 418 | child_ino: 1, 419 | file_type: FileType::Directory, 420 | filename: "..".to_string() 421 | }; 422 | add_dentry(root_dir, &self.conn)?; 423 | } 424 | } 425 | Ok(()) 426 | } 427 | 428 | fn get_inode(&self, inode: u32) -> Result> { 429 | get_inode_local(inode, &self.conn) 430 | } 431 | 432 | fn add_inode_and_dentry(&mut self, parent: u32, name: &str, attr: &DBFileAttr) -> Result { 433 | let tx = self.conn.transaction()?; 434 | let child = add_inode_local(attr, &tx)?; 435 | let dentry = DEntry{parent_ino: parent, child_ino: child, filename: String::from(name), file_type: attr.kind}; 436 | add_dentry(dentry, &tx)?; 437 | if attr.kind == FileType::Directory { 438 | let dentry = DEntry{parent_ino: child, child_ino: parent, filename: String::from(".."), file_type: attr.kind}; 439 | add_dentry(dentry, &tx)?; 440 | let dentry = DEntry{parent_ino: child, child_ino: child, filename: String::from("."), file_type: attr.kind}; 441 | add_dentry(dentry, &tx)?; 442 | } 443 | let now = Utc::now(); 444 | update_mtime(parent, now, &tx)?; 445 | update_ctime(parent, now, &tx)?; 446 | tx.commit()?; 447 | Ok(child) 448 | } 449 | 450 | fn update_inode(&mut self, attr: &DBFileAttr, truncate: bool) -> Result<()> { 451 | let sql = "UPDATE metadata SET \ 452 | size=$1,\ 453 | atime=datetime($2),\ 454 | atime_nsec=$3,\ 455 | mtime=datetime($4),\ 456 | mtime_nsec=$5,\ 457 | ctime=datetime($6),\ 458 | ctime_nsec=$7,\ 459 | crtime=datetime($8),\ 460 | crtime_nsec=$9,\ 461 | mode=$10,\ 462 | uid=$11,\ 463 | gid=$12,\ 464 | rdev=$13,\ 465 | flags=$14 \ 466 | WHERE id=$15"; 467 | let tx = self.conn.transaction()?; 468 | let oldattr = get_inode_local(attr.ino, &tx)?; 469 | let oldattr = match oldattr { 470 | Some(n) => n, 471 | None => { 472 | return Err(Error::from(ErrorKind::FsNoEnt {description: format!( 473 | "{} is not exist", 474 | attr.ino 475 | )})); 476 | } 477 | }; 478 | let now = Utc::now(); 479 | let atime = DateTime::::from(attr.atime); 480 | let mtime= if oldattr.size != attr.size { 481 | now 482 | } else { 483 | DateTime::::from(attr.mtime) 484 | }; 485 | let ctime = now; 486 | let crtime = DateTime::::from(attr.crtime); 487 | { 488 | let mut stmt = tx.prepare(sql)?; 489 | stmt.execute(params![ 490 | attr.size, 491 | atime.format("%Y-%m-%d %H:%M:%S").to_string(), 492 | atime.timestamp_subsec_nanos(), 493 | mtime.format("%Y-%m-%d %H:%M:%S").to_string(), 494 | mtime.timestamp_subsec_nanos(), 495 | ctime.format("%Y-%m-%d %H:%M:%S").to_string(), 496 | ctime.timestamp_subsec_nanos(), 497 | crtime.format("%Y-%m-%d %H:%M:%S").to_string(), 498 | crtime.timestamp_subsec_nanos(), 499 | attr.perm, 500 | attr.uid, 501 | attr.gid, 502 | attr.rdev, 503 | attr.flags, 504 | attr.ino 505 | ])?; 506 | } 507 | if truncate { 508 | release_data(attr.ino, attr.size, &tx)?; 509 | } 510 | tx.commit()?; 511 | Ok(()) 512 | } 513 | 514 | fn delete_inode_if_noref(&mut self, inode: u32) -> Result<()> { 515 | let sql = "SELECT count(child_id) FROM dentry WHERE child_id=$1"; 516 | let tx = self.conn.transaction()?; 517 | let nlink: u32; 518 | { 519 | let mut stmt = tx.prepare(sql)?; 520 | nlink = stmt.query_row(params![inode], |row| row.get(0))?; 521 | } 522 | if nlink == 0 { 523 | let sql = "DELETE FROM metadata WHERE id=$1"; 524 | tx.execute(sql, params![inode])?; 525 | } 526 | tx.commit()?; 527 | Ok(()) 528 | } 529 | 530 | fn get_dentry(&self, inode: u32) -> Result> { 531 | let sql = "SELECT child_id, file_type, name FROM dentry WHERE parent_id=$1 ORDER BY name"; 532 | let mut stmt = self.conn.prepare(sql)?; 533 | let rows = stmt.query_map(params![inode], |row| { 534 | Ok(DEntry{parent_ino: inode, 535 | child_ino: row.get(0)?, 536 | file_type: const_to_file_type(row.get(1)?), 537 | filename: row.get(2)?, 538 | }) 539 | })?; 540 | let mut entries: Vec = Vec::new(); 541 | for row in rows { 542 | entries.push(row?); 543 | } 544 | Ok(entries) 545 | } 546 | 547 | fn link_dentry(&mut self, inode: u32, parent: u32, name: &str) -> Result { 548 | let now = Utc::now(); 549 | let tx = self.conn.transaction()?; 550 | let attr = match get_inode_local(inode, &tx)? { 551 | Some(n) => n, 552 | None => { 553 | return Err(Error::from(ErrorKind::FsNoEnt {description: format!( 554 | "old path {} is not exist", 555 | inode 556 | )})); 557 | } 558 | }; 559 | if attr.kind != FileType::RegularFile { 560 | return Err(Error::from(ErrorKind::FsParm {description: format!( 561 | "old path {} is not a regular file", 562 | inode 563 | )})); 564 | }; 565 | let new_inode = get_dentry_single(parent, name, &tx)?; 566 | if new_inode.is_some() { 567 | return Err(Error::from(ErrorKind::FsFileExist {description: format!( 568 | "new path {}/{} exist", 569 | parent, 570 | name 571 | )})); 572 | } 573 | let entry = DEntry{ 574 | parent_ino: parent, 575 | child_ino: inode, 576 | file_type: FileType::RegularFile, 577 | filename: name.to_string() 578 | }; 579 | add_dentry(entry, &tx)?; 580 | update_mtime(inode, now, &tx)?; 581 | update_mtime(parent, now, &tx)?; 582 | update_ctime(parent, now, &tx)?; 583 | tx.commit()?; 584 | Ok(attr) 585 | } 586 | 587 | fn delete_dentry(&mut self, parent: u32, name: &str) -> Result { 588 | let sql = "SELECT child_id FROM dentry WHERE parent_id=$1 and name=$2"; 589 | let now = Utc::now(); 590 | let tx = self.conn.transaction()?; 591 | let child: u32; 592 | { 593 | let mut stmt = tx.prepare(sql)?; 594 | child = stmt.query_row(params![parent, name], |row| row.get(0))?; 595 | } 596 | delete_dentry_local(parent, name, &tx)?; 597 | delete_sub_dentry(child, &tx)?; 598 | update_ctime(child, now, &tx)?; 599 | update_mtime(parent, now, &tx)?; 600 | update_ctime(parent, now, &tx)?; 601 | tx.commit()?; 602 | Ok(child) 603 | } 604 | 605 | fn move_dentry(&mut self, parent: u32, name: &str, new_parent: u32, new_name: &str) -> Result> { 606 | let sql = "UPDATE dentry SET parent_id=$1, name=$2 where parent_id=$3 and name=$4"; 607 | let now = Utc::now(); 608 | let tx = self.conn.transaction()?; 609 | let dentry = match get_dentry_single(parent, name, &tx)? { 610 | Some(n) => n, 611 | None => { 612 | return Err(Error::from(ErrorKind::FsNoEnt {description: format!("parent: {} name:{}", parent, name)})); 613 | } 614 | }; 615 | let mut res = None; 616 | let exist_entry = get_dentry_single(new_parent, new_name, &tx)?; 617 | if let Some(v) = exist_entry { 618 | let exist_id = v.child_ino; 619 | let exist_file_type = v.file_type; 620 | if dentry.file_type != exist_file_type { 621 | match exist_file_type { 622 | FileType::Directory => { 623 | return Err(Error::from(ErrorKind::FsIsDir { 624 | description: format!( 625 | "parent: {} name:{}", 626 | new_parent, new_name 627 | ) 628 | })); 629 | }, 630 | FileType::RegularFile => { 631 | return Err(Error::from(ErrorKind::FsIsNotDir { 632 | description: format!( 633 | "parent: {} name:{}", 634 | new_parent, 635 | new_name 636 | ) 637 | })); 638 | }, 639 | _ => { 640 | return Err(Error::from(ErrorKind::Undefined { 641 | description: format!( 642 | "parent: {} name:{} has invalid type: {:?}", 643 | new_parent, 644 | new_name, 645 | exist_file_type 646 | ) 647 | })); 648 | } 649 | }; 650 | } 651 | if exist_file_type ==FileType::Directory { 652 | let empty = check_directory_is_empty_local(exist_id, &tx)?; 653 | if !empty { 654 | return Err(Error::from(ErrorKind::FsNotEmpty {description: format!( 655 | "parent: {} name:{} is not empty", 656 | new_parent, 657 | new_name 658 | )})); 659 | } 660 | } 661 | delete_dentry_local(new_parent, new_name, &tx)?; 662 | res = Some(v.child_ino); 663 | } 664 | tx.execute(sql, params![new_parent, new_name, parent, name])?; 665 | if parent != new_parent && dentry.file_type == FileType::Directory { 666 | let sql = "UPDATE dentry set child_id=$1 WHERE parent_id=$2 and name='..'"; 667 | tx.execute(sql, params![new_parent, dentry.child_ino])?; 668 | } 669 | update_ctime(dentry.child_ino, now, &tx)?; 670 | update_mtime(parent, now, &tx)?; 671 | update_ctime(parent, now, &tx)?; 672 | if parent != new_parent { 673 | update_mtime(new_parent, now, &tx)?; 674 | update_ctime(new_parent, now, &tx)?; 675 | } 676 | tx.commit()?; 677 | Ok(res) 678 | } 679 | 680 | fn check_directory_is_empty(&self, inode: u32) -> Result { 681 | check_directory_is_empty_local(inode,&self.conn) 682 | } 683 | 684 | fn lookup(&mut self, parent: u32, name: &str) -> Result> { 685 | let sql = "SELECT \ 686 | metadata.id,\ 687 | metadata.size,\ 688 | metadata.atime,\ 689 | metadata.atime_nsec,\ 690 | metadata.mtime,\ 691 | metadata.mtime_nsec,\ 692 | metadata.ctime,\ 693 | metadata.ctime_nsec,\ 694 | metadata.crtime,\ 695 | metadata.crtime_nsec,\ 696 | metadata.kind, \ 697 | metadata.mode,\ 698 | ncount.nlink,\ 699 | metadata.uid,\ 700 | metadata.gid,\ 701 | metadata.rdev,\ 702 | metadata.flags, \ 703 | blocknum.block_num \ 704 | FROM dentry \ 705 | INNER JOIN metadata \ 706 | ON metadata.id=dentry.child_id \ 707 | AND dentry.parent_id=$1 \ 708 | AND dentry.name=$2 \ 709 | LEFT JOIN (SELECT file_id file_id, count(block_num) block_num from data) AS blocknum \ 710 | ON dentry.child_id = blocknum.file_id \ 711 | LEFT JOIN ( SELECT child_id, COUNT(child_id) nlink FROM dentry GROUP BY child_id) AS ncount \ 712 | ON dentry.child_id = ncount.child_id \ 713 | "; 714 | let tx = self.conn.transaction()?; 715 | let stmt = tx.prepare(sql)?; 716 | let params = params![parent, name]; 717 | let result = parse_attr(stmt, params); 718 | update_atime(parent, Utc::now(), &tx)?; 719 | tx.commit()?; 720 | result 721 | } 722 | 723 | fn get_data(&mut self, inode:u32, block: u32, length: u32) -> Result> { 724 | let tx = self.conn.transaction()?; 725 | let row: Vec; 726 | { 727 | let mut stmt = tx.prepare( 728 | "SELECT \ 729 | data FROM data WHERE file_id=$1 AND block_num=$2")?; 730 | row = match stmt.query_row(params![inode, block], |row| row.get(0)) { 731 | Ok(n) => n, 732 | Err(err) => { 733 | if err == rusqlite::Error::QueryReturnedNoRows { 734 | vec![0; length as usize] 735 | } else { 736 | return Err(Error::from(err)) 737 | } 738 | } 739 | }; 740 | } 741 | update_atime(inode, Utc::now(), &tx)?; 742 | tx.commit()?; 743 | Ok(row) 744 | } 745 | 746 | fn write_data(&mut self, inode:u32, block: u32, data: &[u8], size: u32) -> Result<()> { 747 | let tx = self.conn.transaction()?; 748 | { 749 | let db_size: u32 = tx.query_row("SELECT size FROM metadata WHERE id=$1", params![inode], |row| row.get(0))?; 750 | tx.execute("REPLACE INTO data \ 751 | (file_id, block_num, data) 752 | VALUES($1, $2, $3)", 753 | params![inode, block, data])?; 754 | if size > db_size { 755 | tx.execute("UPDATE metadata SET size=$1 WHERE id=$2", params![size, inode])?; 756 | } 757 | } 758 | let time = Utc::now(); 759 | update_mtime(inode, time, &tx)?; 760 | update_ctime(inode, time, &tx)?; 761 | tx.commit()?; 762 | Ok(()) 763 | } 764 | 765 | fn release_data(&self, inode: u32) -> Result<()> { 766 | self.conn.execute("DELETE FROM data WHERE file_id=$1", params![inode])?; 767 | Ok(()) 768 | } 769 | 770 | fn delete_all_noref_inode(&mut self) -> Result<()> { 771 | self.conn.execute( 772 | "DELETE FROM metadata WHERE NOT EXISTS (SELECT 'x' FROM dentry WHERE metadata.id = dentry.child_id)", 773 | params![] 774 | )?; 775 | Ok(()) 776 | } 777 | 778 | fn get_db_block_size(&self) -> u32 { 779 | BLOCK_SIZE 780 | } 781 | 782 | fn set_xattr(&mut self, inode: u32, key: &str, value: &[u8]) -> Result<()> { 783 | let tx = self.conn.transaction()?; 784 | { 785 | tx.execute("REPLACE INTO xattr \ 786 | (file_id, name, value) 787 | VALUES($1, $2, $3)", 788 | params![inode, key, value])?; 789 | } 790 | let time = Utc::now(); 791 | update_ctime(inode, time, &tx)?; 792 | tx.commit()?; 793 | Ok(()) 794 | } 795 | 796 | fn get_xattr(&self, inode: u32, key: &str) -> Result> { 797 | let mut stmt = self.conn.prepare( 798 | "SELECT \ 799 | value FROM xattr WHERE file_id=$1 AND name=$2")?; 800 | let row: Vec = match stmt.query_row(params![inode, key], |row| row.get(0)) { 801 | Ok(n) => n, 802 | Err(err) => { 803 | if err == rusqlite::Error::QueryReturnedNoRows { 804 | return Err(Error::from(ErrorKind::FsNoEnt { 805 | description: format!( 806 | "inode: {} name:{}", 807 | inode, key 808 | ) 809 | })) 810 | } else { 811 | return Err(Error::from(err)) 812 | } 813 | } 814 | }; 815 | Ok(row) 816 | } 817 | 818 | fn list_xattr(&self, inode: u32) -> Result> { 819 | let sql = "SELECT name FROM xattr WHERE file_id=$1 ORDER BY name"; 820 | let mut stmt = self.conn.prepare(sql)?; 821 | let rows = stmt.query_map(params![inode], |row| { 822 | Ok(row.get(0)?) 823 | })?; 824 | let mut name_list: Vec = Vec::new(); 825 | for row in rows { 826 | name_list.push(row?); 827 | } 828 | Ok(name_list) 829 | } 830 | 831 | fn delete_xattr(&mut self, inode: u32, key: &str) -> Result<()> { 832 | let tx = self.conn.transaction()?; 833 | { 834 | tx.execute("DELETE FROM xattr \ 835 | WHERE file_id = $1 AND name = $2", 836 | params![inode, key])?; 837 | } 838 | let time = Utc::now(); 839 | update_ctime(inode, time, &tx)?; 840 | tx.commit()?; 841 | Ok(()) 842 | } 843 | } 844 | -------------------------------------------------------------------------------- /src/filesystem.rs: -------------------------------------------------------------------------------- 1 | use fuse::{ 2 | Filesystem, 3 | ReplyAttr, 4 | ReplyData, 5 | ReplyDirectory, 6 | ReplyEntry, 7 | ReplyWrite, 8 | ReplyCreate, 9 | ReplyEmpty, 10 | ReplyOpen, 11 | ReplyStatfs, 12 | ReplyXattr, 13 | Request, 14 | FileType 15 | }; 16 | use libc::{ 17 | c_int, 18 | ENOENT, 19 | ENOTEMPTY, 20 | EISDIR, 21 | ENOTDIR, 22 | EPERM, 23 | EEXIST, 24 | EINVAL, 25 | ENAMETOOLONG, 26 | ENODATA, 27 | ERANGE, 28 | O_RDONLY, 29 | O_APPEND, 30 | S_ISGID, 31 | S_ISVTX, 32 | XATTR_CREATE, 33 | XATTR_REPLACE 34 | }; 35 | 36 | #[cfg(not(target_os = "macos"))] 37 | use libc::O_NOATIME; 38 | 39 | #[cfg(target_os = "macos")] 40 | const O_NOATIME: u32=0; 41 | 42 | use nix::sys::statvfs; 43 | use std::path::Path; 44 | use std::ffi::OsStr; 45 | use crate::db_module::{DbModule, DBFileAttr, DEntry}; 46 | use crate::db_module::sqlite::Sqlite; 47 | use crate::sqerror::{Error, ErrorKind}; 48 | use time::Timespec; 49 | use std::time::SystemTime; 50 | use std::sync::{Arc, Mutex}; 51 | use std::collections::HashMap; 52 | const ONE_SEC: Timespec = Timespec{ 53 | sec: 1, 54 | nsec: 0 55 | }; 56 | 57 | struct OpenFileStat { 58 | readonly: bool, 59 | append: bool, 60 | noatime: bool, 61 | } 62 | 63 | struct OpenFileHandler { 64 | count : u64, 65 | list: HashMap, 66 | } 67 | 68 | impl OpenFileStat { 69 | fn new() -> Self { 70 | Self{readonly: false, append: false, noatime: false} 71 | } 72 | } 73 | 74 | impl OpenFileHandler { 75 | fn new() -> Self { 76 | Self{count: 0, list: HashMap::::new()} 77 | } 78 | } 79 | 80 | struct OpenDirHandler { 81 | count: u64, 82 | list: HashMap>, 83 | } 84 | 85 | impl OpenDirHandler { 86 | fn new() -> Self { 87 | Self{count: 0, list: HashMap::>::new()} 88 | } 89 | } 90 | 91 | pub struct SqliteFs{ 92 | db: Sqlite, 93 | lookup_count: Arc>>, 94 | open_file_handler: Arc>>, 95 | open_dir_handler: Arc>>, 96 | } 97 | 98 | impl SqliteFs { 99 | pub fn new(path: & str) -> Result { 100 | let mut db = match Sqlite::new(Path::new(path)) { 101 | Ok(n) => n, 102 | Err(err) => return Err(err) 103 | }; 104 | db.init()?; 105 | let lookup_count = Arc::new(Mutex::new(HashMap::::new())); 106 | let open_file_handler = Arc::new(Mutex::new(HashMap::::new())); 107 | let open_dir_handler = Arc::new(Mutex::new(HashMap::::new())); 108 | Ok(SqliteFs{db, lookup_count, open_file_handler, open_dir_handler}) 109 | } 110 | 111 | pub fn new_with_db(db: Sqlite) -> Result { 112 | let lookup_count = Arc::new(Mutex::new(HashMap::::new())); 113 | let open_file_handler = Arc::new(Mutex::new(HashMap::::new())); 114 | let open_dir_handler = Arc::new(Mutex::new(HashMap::::new())); 115 | Ok(SqliteFs{db, lookup_count, open_file_handler, open_dir_handler}) 116 | } 117 | } 118 | 119 | impl Filesystem for SqliteFs { 120 | fn init(&mut self, _req: &Request<'_>) -> Result<(), c_int> { 121 | match self.db.delete_all_noref_inode() { 122 | Ok(n) => n, 123 | Err(err) => debug!("{}", err) 124 | }; 125 | Ok(()) 126 | } 127 | 128 | fn destroy(&mut self, _req: &Request<'_>) { 129 | let lc_list = self.lookup_count.lock().unwrap(); 130 | for key in lc_list.keys() { 131 | match self.db.delete_inode_if_noref(*key) { 132 | Ok(n) => n, 133 | Err(err) => debug!("{}", err) 134 | } 135 | } 136 | } 137 | 138 | fn lookup(&mut self, _req: &Request, parent: u64, name: &OsStr, reply: ReplyEntry) { 139 | let parent = parent as u32; 140 | let child = match self.db.lookup(parent, name.to_str().unwrap()) { 141 | Ok(n) => { 142 | match n { 143 | Some(v) => { 144 | reply.entry(&ONE_SEC, &v.get_file_attr() , 0); 145 | debug!("filesystem:lookup, return:{:?}", v.get_file_attr()); 146 | v.ino 147 | }, 148 | None => { reply.error(ENOENT); return;} 149 | } 150 | }, 151 | Err(err) => {reply.error(ENOENT); debug!("{}", err); return;} 152 | }; 153 | let mut lc_list = self.lookup_count.lock().unwrap(); 154 | let lc = lc_list.entry(child).or_insert(0); 155 | *lc += 1; 156 | debug!("filesystem:lookup, lookup count:{:?}", *lc); 157 | } 158 | 159 | fn forget(&mut self, _req: &Request<'_>, ino: u64, nlookup: u64) { 160 | let ino = ino as u32; 161 | let mut lc_list = self.lookup_count.lock().unwrap(); 162 | let lc = lc_list.entry(ino).or_insert(0); 163 | *lc -= nlookup as u32; 164 | debug!("filesystem:forget, lookup count:{:?}", *lc); 165 | if *lc == 0 { 166 | lc_list.remove(&ino); 167 | match self.db.delete_inode_if_noref(ino) { 168 | Ok(n) => n, 169 | Err(err) => debug!("{}", err) 170 | } 171 | } 172 | } 173 | 174 | fn getattr(&mut self, _req: &Request, ino: u64, reply: ReplyAttr) { 175 | match self.db.get_inode(ino as u32) { 176 | Ok(n) => { 177 | match n { 178 | Some(v) => { 179 | reply.attr(&ONE_SEC, &v.get_file_attr()); 180 | debug!("filesystem:getattr, return:{:?}", v.get_file_attr()); 181 | }, 182 | None => reply.error(ENOENT) 183 | } 184 | 185 | }, 186 | Err(_err) => reply.error(ENOENT) 187 | }; 188 | } 189 | 190 | fn setattr( 191 | &mut self, 192 | _req: &Request<'_>, 193 | ino: u64, 194 | mode: Option, 195 | uid: Option, 196 | gid: Option, 197 | size: Option, 198 | atime: Option, 199 | mtime: Option, 200 | _fh: Option, 201 | crtime: Option, 202 | _chgtime: Option, 203 | _bkuptime: Option, 204 | flags: Option, 205 | reply: ReplyAttr 206 | ) { 207 | let mut attr = match self.db.get_inode(ino as u32) { 208 | Ok(n) => { 209 | match n { 210 | Some(v) => v, 211 | None => {reply.error(ENOENT); return;} 212 | } 213 | }, 214 | Err(err) => {reply.error(ENOENT); debug!("{}", err); return;} 215 | }; 216 | let old_size = attr.size; 217 | if let Some(n) = mode {attr.perm = n as u16}; 218 | if let Some(n) = uid {attr.uid = n}; 219 | if let Some(n) = gid {attr.gid = n}; 220 | if let Some(n) = size {attr.size = n as u32}; 221 | if let Some(n) = atime {attr.atime = attr.datetime_from(&n)}; 222 | if let Some(n) = mtime {attr.mtime = attr.datetime_from(&n)}; 223 | if let Some(n) = crtime {attr.crtime = attr.datetime_from(&n)}; 224 | if let Some(n) = flags {attr.flags = n}; 225 | match self.db.update_inode(&attr, old_size > attr.size) { 226 | Ok(_n) => (), 227 | Err(err) => {reply.error(ENOENT); debug!("{}", err); return;} 228 | }; 229 | reply.attr(&ONE_SEC, &attr.get_file_attr()); 230 | } 231 | 232 | fn readlink(&mut self, _req: &Request<'_>, ino: u64, reply: ReplyData) { 233 | let ino = ino as u32; 234 | let attr = match self.db.get_inode(ino) { 235 | Ok(n) => match n { 236 | Some(attr) => attr, 237 | None => {reply.error(ENOENT); return;} 238 | }, 239 | Err(err) => {reply.error(ENOENT); debug!("{}", err); return;} 240 | }; 241 | 242 | if attr.kind != FileType::Symlink { 243 | reply.error(EINVAL); 244 | return; 245 | } 246 | let size = attr.size; 247 | let mut data = match self.db.get_data(ino as u32, 1, size) { 248 | Ok(n) => n, 249 | Err(_err) => {reply.error(ENOENT); return; } 250 | }; 251 | data.resize(size as usize, 0); 252 | reply.data(&data); 253 | } 254 | 255 | fn mkdir(&mut self, req: &Request<'_>, parent: u64, name: &OsStr, mode: u32, reply: ReplyEntry) { 256 | let now = SystemTime::now(); 257 | let parent = parent as u32; 258 | let mut attr = DBFileAttr { 259 | ino: 0, 260 | size: 0, 261 | blocks: 0, 262 | atime: now, 263 | mtime: now, 264 | ctime: now, 265 | crtime: now, 266 | kind: FileType::Directory, 267 | perm: mode as u16, 268 | nlink: 0, 269 | uid: req.uid(), 270 | gid: req.gid(), 271 | rdev: 0, 272 | flags: 0 273 | }; 274 | let parent_attr = match self.db.get_inode(parent) { 275 | Ok(n) => match n { 276 | Some(n) => n, 277 | None => {reply.error(ENOENT); return;} 278 | }, 279 | Err(err) => {reply.error(ENOENT); debug!("{}", err); return;} 280 | }; 281 | if parent_attr.perm & S_ISGID as u16 > 0 { 282 | attr.perm |= S_ISGID as u16; 283 | attr.gid = parent_attr.gid; 284 | } 285 | if parent_attr.perm & S_ISVTX as u16 > 0 { 286 | attr.perm |= S_ISVTX as u16; 287 | } 288 | let ino = match self.db.add_inode_and_dentry(parent, name.to_str().unwrap(), &attr) { 289 | Ok(n) => n, 290 | Err(err) => {reply.error(ENOENT); debug!("{}", err); return;} 291 | }; 292 | attr.ino = ino; 293 | reply.entry(&ONE_SEC, &attr.get_file_attr(), 0); 294 | let mut lc_list = self.lookup_count.lock().unwrap(); 295 | let lc = lc_list.entry(ino).or_insert(0); 296 | *lc += 1; 297 | debug!("filesystem:mkdir, inode: {:?} lookup count:{:?}", ino, *lc); 298 | } 299 | 300 | fn unlink(&mut self, _req: &Request<'_>, parent: u64, name: &OsStr, reply: ReplyEmpty) { 301 | let ino = match self.db.delete_dentry(parent as u32, name.to_str().unwrap()) { 302 | Ok(n) => n, 303 | Err(err) => {reply.error(ENOENT); debug!("{}", err); return;} 304 | }; 305 | let lc_list = self.lookup_count.lock().unwrap(); 306 | if !lc_list.contains_key(&ino) { 307 | match self.db.delete_inode_if_noref(ino) { 308 | Ok(n) => n, 309 | Err(err) => { 310 | reply.error(ENOENT); 311 | debug!("{}", err); 312 | return; 313 | } 314 | }; 315 | } 316 | reply.ok(); 317 | } 318 | 319 | fn rmdir(&mut self, _req: &Request<'_>, parent: u64, name: &OsStr, reply: ReplyEmpty) { 320 | let parent = parent as u32; 321 | let name = name.to_str().unwrap(); 322 | let attr = match self.db.lookup(parent, name) { 323 | Ok(n) => { 324 | match n { 325 | Some(v) => v, 326 | None => {reply.error(ENOENT); return;} 327 | } 328 | }, 329 | Err(err) => {reply.error(ENOENT); debug!("{}", err); return;} 330 | }; 331 | let empty = match self.db.check_directory_is_empty(attr.ino){ 332 | Ok(n) => n, 333 | Err(err) => {reply.error(ENOENT); debug!("{}", err); return;} 334 | }; 335 | if !empty { 336 | reply.error(ENOTEMPTY); 337 | return; 338 | } 339 | let ino = match self.db.delete_dentry(parent, name) { 340 | Ok(n) => n, 341 | Err(err) => {reply.error(ENOENT); debug!("{}", err); return;} 342 | }; 343 | let lc_list = self.lookup_count.lock().unwrap(); 344 | if !lc_list.contains_key(&ino) { 345 | match self.db.delete_inode_if_noref(ino) { 346 | Ok(n) => n, 347 | Err(err) => { 348 | reply.error(ENOENT); 349 | debug!("{}", err); 350 | return; 351 | } 352 | }; 353 | } 354 | reply.ok(); 355 | } 356 | 357 | fn symlink(&mut self, req: &Request, parent: u64, name: &OsStr, link: &Path, reply: ReplyEntry) { 358 | let now = SystemTime::now(); 359 | let mut attr = DBFileAttr { 360 | ino: 0, 361 | size: 0, 362 | blocks: 0, 363 | atime: now, 364 | mtime: now, 365 | ctime: now, 366 | crtime: now, 367 | kind: FileType::Symlink, 368 | perm: 0o777, // never used 369 | nlink: 0, 370 | uid: req.uid(), 371 | gid: req.gid(), 372 | rdev: 0, 373 | flags: 0 374 | }; 375 | let ino = match self.db.add_inode_and_dentry(parent as u32, name.to_str().unwrap(), &attr) { 376 | Ok(n) => n, 377 | Err(err) => {reply.error(ENOENT); debug!("{}", err); return;} 378 | }; 379 | let data = link.to_str().unwrap().as_bytes(); 380 | let block_size = self.db.get_db_block_size() as usize; 381 | if data.len() > block_size { 382 | reply.error(ENAMETOOLONG); 383 | return; 384 | } 385 | match self.db.write_data(ino, 1, &data, data.len() as u32) { 386 | Ok(n) => n, 387 | Err(err) => {reply.error(ENOENT); debug!("{}", err); return;} 388 | } 389 | attr.ino = ino; 390 | reply.entry(&ONE_SEC, &attr.get_file_attr(), 0); 391 | let mut lc_list = self.lookup_count.lock().unwrap(); 392 | let lc = lc_list.entry(ino).or_insert(0); 393 | *lc += 1; 394 | debug!("filesystem:symlink, inode: {:?} lookup count:{:?}", ino, *lc); 395 | } 396 | 397 | fn rename( 398 | &mut self, 399 | _req: &Request<'_>, 400 | parent: u64, 401 | name: &OsStr, 402 | newparent: u64, 403 | newname: &OsStr, 404 | reply: ReplyEmpty 405 | ) { 406 | let parent = parent as u32; 407 | let name = name.to_str().unwrap(); 408 | let newparent = newparent as u32; 409 | let newname = newname.to_str().unwrap(); 410 | let entry = match self.db.move_dentry(parent, name, newparent, newname) { 411 | Ok(n) => n, 412 | Err(err) => match err.kind() { 413 | ErrorKind::FsNotEmpty {description} => {reply.error(ENOTEMPTY); debug!("{}", &description); return;}, 414 | ErrorKind::FsIsDir{description} => {reply.error(EISDIR); debug!("{}", &description); return;}, 415 | ErrorKind::FsIsNotDir{description} => {reply.error(ENOTDIR); debug!("{}", &description); return;}, 416 | _ => {reply.error(ENOENT); debug!("{}", err); return;}, 417 | } 418 | }; 419 | if let Some(ino) = entry { 420 | let lc_list = self.lookup_count.lock().unwrap(); 421 | if !lc_list.contains_key(&ino) { 422 | match self.db.delete_inode_if_noref(ino) { 423 | Ok(n) => n, 424 | Err(err) => {reply.error(ENOENT); debug!("{}", err); return;}, 425 | }; 426 | } 427 | } 428 | reply.ok(); 429 | } 430 | 431 | fn link(&mut self, _req: &Request<'_>, ino: u64, newparent: u64, newname: &OsStr, reply: ReplyEntry) { 432 | let attr = match self.db.link_dentry(ino as u32, newparent as u32, newname.to_str().unwrap()) { 433 | Ok(n) => n, 434 | Err(err) => match err.kind() { 435 | ErrorKind::FsParm{description} => {reply.error(EPERM); debug!("{}", &description); return;}, 436 | ErrorKind::FsFileExist{description} => {reply.error(EEXIST); debug!("{}", &description); return;}, 437 | _ => {reply.error(ENOENT); debug!("{}", err); return;} 438 | } 439 | }; 440 | reply.entry(&ONE_SEC, &attr.get_file_attr(), 0); 441 | let mut lc_list = self.lookup_count.lock().unwrap(); 442 | let lc = lc_list.entry(ino as u32).or_insert(0); 443 | *lc += 1; 444 | debug!("filesystem:link, lookup count:{:?}", *lc); 445 | } 446 | 447 | fn open(&mut self, _req: &Request<'_>, ino: u64, flags: u32, reply: ReplyOpen) { 448 | let ino = ino as u32; 449 | let mut stat = OpenFileStat::new(); 450 | if flags & O_APPEND as u32 > 0 { 451 | stat.append = true; 452 | } 453 | if flags & O_RDONLY as u32 > 0 { 454 | stat.readonly = true; 455 | } 456 | if flags & O_NOATIME as u32 > 0 { 457 | stat.noatime = true; 458 | } 459 | let mut handler = self.open_file_handler.lock().unwrap(); 460 | let handle_list = handler.entry(ino).or_insert_with(OpenFileHandler::new); 461 | let fh = handle_list.count; 462 | (*handle_list).list.insert(fh, stat); 463 | (*handle_list).count += 1; 464 | reply.opened(fh, 0); 465 | } 466 | 467 | fn read(&mut self, _req: &Request, ino: u64, _fh: u64, offset: i64, size: u32, reply: ReplyData) { 468 | let mut data: Vec = Vec::with_capacity(size as usize); 469 | let block_size = self.db.get_db_block_size(); 470 | let mut size = size; 471 | let mut offset = offset as u32; 472 | while size > 0 { 473 | let b_num = offset / block_size + 1; 474 | let mut block_data = match self.db.get_data(ino as u32, b_num, block_size) { 475 | Ok(n) => n, 476 | Err(_err) => {reply.error(ENOENT); return; } 477 | }; 478 | let b_offset = offset % block_size; 479 | let b_end = if (size + b_offset) / block_size >= 1 {block_size} else {size + b_offset}; 480 | if block_data.len() < b_end as usize { 481 | block_data.resize(b_end as usize, 0); 482 | } 483 | data.append(&mut block_data[b_offset as usize..b_end as usize].to_vec()); 484 | offset += b_end - b_offset; 485 | size -= b_end - b_offset; 486 | } 487 | reply.data(&data); 488 | } 489 | 490 | fn write(&mut self, _req: &Request<'_>, ino: u64, _fh: u64, offset: i64, data: &[u8], _flags: u32, reply: ReplyWrite) { 491 | let block_size = self.db.get_db_block_size(); 492 | let ino = ino as u32; 493 | let size = data.len() as u32; 494 | let offset = offset as u32; 495 | let start_block = offset / block_size + 1; 496 | let end_block = (offset + size - 1) / block_size + 1; 497 | for i in start_block..=end_block { 498 | let mut block_data: Vec = Vec::with_capacity(block_size as usize); 499 | let b_start_index = if i == start_block {offset % block_size} else {0}; 500 | let b_end_index = if i == end_block {(offset+size-1) % block_size +1} else {block_size}; 501 | let data_offset; 502 | if (i > start_block) { 503 | //The blocks don't need to be in perfect alignment. 504 | data_offset = 505 | ((i - start_block - 1) * block_size) + (block_size) - offset % block_size; 506 | } else { 507 | data_offset = 0; 508 | } 509 | 510 | if (b_start_index != 0) || (b_end_index != block_size) { 511 | let mut data_pre = match self.db.get_data(ino, i, block_size) { 512 | Ok(n) => n, 513 | Err(err) => {reply.error(ENOENT); debug!("{}", err); return;} 514 | }; 515 | if data_pre.len() < block_size as usize { 516 | data_pre.resize(block_size as usize, 0); 517 | } 518 | if b_start_index != 0 { 519 | block_data.extend_from_slice(&data_pre[0..b_start_index as usize]); 520 | } 521 | block_data.extend_from_slice(&data[data_offset as usize..(data_offset + b_end_index - b_start_index) as usize]); 522 | if b_end_index != block_size { 523 | block_data.extend_from_slice(&data_pre[b_end_index as usize..block_size as usize]); 524 | } 525 | } else { 526 | block_data.extend_from_slice(&data[data_offset as usize..(data_offset + block_size) as usize]); 527 | } 528 | match self.db.write_data(ino, i, &block_data, (i-1) * block_size + b_end_index) { 529 | Ok(n) => n, 530 | Err(err) => {reply.error(ENOENT); debug!("{}", err); return;} 531 | } 532 | } 533 | reply.written(size); 534 | } 535 | 536 | fn release(&mut self, _req: &Request<'_>, ino: u64, fh: u64, _flags: u32, _lock_owner: u64, _flush: bool, reply: ReplyEmpty) { 537 | let ino = ino as u32; 538 | let mut handler = self.open_file_handler.lock().unwrap(); 539 | let handle_list = handler.entry(ino).or_insert_with(OpenFileHandler::new); 540 | (*handle_list).list.remove(&fh); 541 | if (*handle_list).count == 0 { 542 | handler.remove(&ino); 543 | } 544 | reply.ok(); 545 | } 546 | 547 | fn opendir(&mut self, _req: &Request<'_>, ino: u64, _flags: u32, reply: ReplyOpen) { 548 | let ino = ino as u32; 549 | let dentries = match self.db.get_dentry(ino) { 550 | Ok(n) => n, 551 | Err(err) => {reply.error(ENOENT); debug!("{}", err); return;} 552 | }; 553 | let mut handler = self.open_dir_handler.lock().unwrap(); 554 | let handle_list = handler.entry(ino).or_insert_with(OpenDirHandler::new); 555 | let fh = handle_list.count; 556 | (*handle_list).list.insert(fh, dentries); 557 | (*handle_list).count += 1; 558 | reply.opened(fh, 0); 559 | } 560 | 561 | #[cfg(not(target_os = "macos"))] 562 | fn readdir(&mut self, _req: &Request, ino: u64, fh: u64, offset: i64, mut reply: ReplyDirectory) { 563 | /*let db_entries = match self.db.get_dentry(ino as u32) { 564 | Ok(n) => n, 565 | Err(err) => {reply.error(ENOENT); debug!("{}", err); return;} 566 | };*/ 567 | let ino = ino as u32; 568 | let handler = self.open_dir_handler.lock().unwrap(); 569 | let db_entries: &Vec = match match handler.get(&ino) { 570 | Some(n) => n.list.get(&fh), 571 | None => None, 572 | } { 573 | Some(n) => n, 574 | None => {reply.error(ENOENT); return;} 575 | }; 576 | 577 | for (i, entry) in db_entries.iter().enumerate().skip(offset as usize) { 578 | let full = reply.add(entry.child_ino as u64, (i + 1) as i64, entry.file_type, &entry.filename); 579 | if full { 580 | break; 581 | } 582 | debug!("filesystem:readdir, ino: {:?} offset: {:?} kind: {:?} name: {}", entry.child_ino as u64, (i + 1) as i64, entry.file_type, entry.filename); 583 | } 584 | reply.ok(); 585 | } 586 | 587 | #[cfg(target_os = "macos")] 588 | fn readdir(&mut self, _req: &Request, ino: u64, _fh: u64, offset: i64, mut reply: ReplyDirectory) { 589 | let ino = ino as u32; 590 | let db_entries = match self.db.get_dentry(ino) { 591 | Ok(n) => n, 592 | Err(err) => {reply.error(ENOENT); debug!("{}", err); return;} 593 | }; 594 | 595 | for (i, entry) in db_entries.iter().enumerate().skip(offset as usize) { 596 | let full = reply.add(entry.child_ino as u64, (i + 1) as i64, entry.file_type, &entry.filename); 597 | if full { 598 | break; 599 | } 600 | debug!("filesystem:readdir, ino: {:?} offset: {:?} kind: {:?} name: {}", entry.child_ino as u64, (i + 1) as i64, entry.file_type, entry.filename); 601 | } 602 | reply.ok(); 603 | } 604 | 605 | fn releasedir(&mut self, _req: &Request<'_>, ino: u64, fh: u64, _flags: u32, reply: ReplyEmpty) { 606 | let ino = ino as u32; 607 | let mut handler = self.open_dir_handler.lock().unwrap(); 608 | let handle_list = handler.entry(ino).or_insert_with(OpenDirHandler::new); 609 | (*handle_list).list.remove(&fh); 610 | if (*handle_list).count == 0 { 611 | handler.remove(&ino); 612 | } 613 | reply.ok(); 614 | } 615 | 616 | fn statfs(&mut self, _req: &Request<'_>, _ino: u64, reply: ReplyStatfs) { 617 | let stat = statvfs::statvfs("/").unwrap(); 618 | reply.statfs( 619 | stat.blocks() as u64, 620 | stat.blocks_free() as u64, 621 | stat.blocks_available() as u64, 622 | stat.files() as u64, 623 | stat.files_free() as u64, 624 | stat.block_size() as u32, 625 | stat.name_max() as u32, 626 | stat.fragment_size() as u32 627 | ); 628 | debug!("statfs {:?}", stat); 629 | } 630 | 631 | fn setxattr(&mut self, _req: &Request<'_>, ino: u64, name: &OsStr, value: &[u8], flags: u32, _position: u32, reply: ReplyEmpty) { 632 | let ino = ino as u32; 633 | let name = name.to_str().unwrap(); 634 | if flags & XATTR_CREATE as u32 > 0 || flags & XATTR_REPLACE as u32 > 0 { 635 | match self.db.get_xattr(ino, name) { 636 | Ok(_) => { 637 | if flags & XATTR_CREATE as u32 > 0 { 638 | reply.error(EEXIST); 639 | return; 640 | } 641 | }, 642 | Err(err) => { 643 | match err.kind() { 644 | ErrorKind::FsNoEnt {description: _} => { 645 | if flags & XATTR_REPLACE as u32 > 0 { 646 | reply.error(ENODATA); 647 | return; 648 | } 649 | }, 650 | _ => { 651 | reply.error(ENOENT); 652 | return; 653 | } 654 | } 655 | } 656 | }; 657 | } 658 | match self.db.set_xattr(ino, name, value) { 659 | Ok(n) => n, 660 | Err(err) => {reply.error(ENOENT); debug!("{}", err); return;} 661 | }; 662 | reply.ok(); 663 | } 664 | 665 | fn getxattr(&mut self, _req: &Request<'_>, ino: u64, name: &OsStr, size: u32, reply: ReplyXattr) { 666 | let ino = ino as u32; 667 | let name = name.to_str().unwrap(); 668 | let value = match self.db.get_xattr(ino, name) { 669 | Ok(n) => n, 670 | Err(err) => {reply.error(ENODATA); debug!("{}", err); return;} 671 | }; 672 | if size == 0 { 673 | reply.size(value.len() as u32); 674 | } else if size < value.len() as u32 { 675 | reply.error(ERANGE); 676 | } else { 677 | reply.data(value.as_slice()); 678 | } 679 | } 680 | 681 | fn listxattr(&mut self, _req: &Request<'_>, ino: u64, size: u32, reply: ReplyXattr) { 682 | let ino = ino as u32; 683 | let names = match self.db.list_xattr(ino) { 684 | Ok(n) => n, 685 | Err(err) => {reply.error(ENODATA); debug!("{}", err); return;} 686 | }; 687 | let mut data: Vec = Vec::new(); 688 | for v in names { 689 | data.extend(v.bytes()); 690 | data.push(0); 691 | } 692 | if size == 0 { 693 | reply.size(data.len() as u32); 694 | } else if size < data.len() as u32 { 695 | reply.error(ERANGE); 696 | } else { 697 | reply.data(data.as_slice()); 698 | } 699 | } 700 | 701 | fn removexattr(&mut self, _req: &Request<'_>, ino: u64, name: &OsStr, reply: ReplyEmpty) { 702 | let ino = ino as u32; 703 | let name = name.to_str().unwrap(); 704 | match self.db.delete_xattr(ino, name) { 705 | Ok(n) => n, 706 | Err(err) => {reply.error(ENOENT); debug!("{}", err); return;} 707 | }; 708 | reply.ok(); 709 | } 710 | 711 | fn create(&mut self, req: &Request<'_>, parent: u64, name: &OsStr, mode: u32, _flags: u32, reply: ReplyCreate) { 712 | let ino; 713 | let parent = parent as u32; 714 | let name = name.to_str().unwrap(); 715 | let lookup_result = match self.db.lookup(parent, name) { 716 | Ok(n) => n, 717 | Err(err) => {reply.error(ENOENT); debug!("{}", err); return;} 718 | }; 719 | let mut attr: DBFileAttr; 720 | match lookup_result { 721 | None => { 722 | let parent_attr = match self.db.get_inode(parent) { 723 | Ok(n) => match n { 724 | Some(n) => n, 725 | None => { 726 | reply.error(ENOENT); 727 | return; 728 | } 729 | }, 730 | Err(err) => { 731 | reply.error(ENOENT); 732 | debug!("{}", err); 733 | return; 734 | } 735 | }; 736 | let now = SystemTime::now(); 737 | attr = DBFileAttr { 738 | ino: 0, 739 | size: 0, 740 | blocks: 0, 741 | atime: now, 742 | mtime: now, 743 | ctime: now, 744 | crtime: now, 745 | kind: FileType::RegularFile, 746 | perm: mode as u16, 747 | nlink: 0, 748 | uid: req.uid(), 749 | gid: if parent_attr.perm & S_ISGID as u16 > 0 { parent_attr.gid } else { req.gid() }, 750 | rdev: 0, 751 | flags: 0 752 | }; 753 | ino = match self.db.add_inode_and_dentry(parent, name, &attr) { 754 | Ok(n) => n, 755 | Err(err) => { 756 | reply.error(ENOENT); 757 | debug!("{}", err); 758 | return; 759 | } 760 | }; 761 | attr.ino = ino; 762 | debug!("filesystem:create, created:{:?}", attr); 763 | }, 764 | Some(n) => { 765 | attr = n; 766 | ino = attr.ino; 767 | debug!("filesystem:create, existed:{:?}", attr); 768 | } 769 | }; 770 | let mut lc_list = self.lookup_count.lock().unwrap(); 771 | let lc = lc_list.entry(ino).or_insert(0); 772 | *lc += 1; 773 | reply.created(&ONE_SEC, &attr.get_file_attr(), 0, 0, 0); 774 | } 775 | } 776 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #[macro_use] 2 | extern crate failure; 3 | #[macro_use] 4 | extern crate log; 5 | extern crate nix; 6 | pub mod db_module; 7 | pub mod filesystem; 8 | pub mod sqerror; 9 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | #[macro_use] extern crate failure; 2 | #[macro_use] extern crate log; 3 | #[macro_use] extern crate clap; 4 | use std::env; 5 | use std::ffi::OsStr; 6 | use sqlite_fs::filesystem::SqliteFs; 7 | use clap::{Arg}; 8 | use sqlite_fs::db_module::sqlite::Sqlite; 9 | use sqlite_fs::db_module::DbModule; 10 | use std::path::PathBuf; 11 | 12 | fn main() { 13 | env_logger::init(); 14 | 15 | let mount_option_arg = Arg::new("mount_option") 16 | .short('o') 17 | .long("option") 18 | .help("Additional mount option for this filesystem") 19 | .value_parser(clap::builder::NonEmptyStringValueParser::new()) 20 | .num_args(1..); 21 | 22 | let mount_point_arg = Arg::new("mount_point") 23 | .help("Target mountpoint path") 24 | .index(1) 25 | .required(true); 26 | 27 | let db_path_arg = Arg::new("db_path") 28 | .help("Sqlite database file path. If not set, open database in memory.") 29 | .index(2); 30 | 31 | let matches = command!() 32 | .about("Sqlite database as a filesystem.") 33 | .version(crate_version!()) 34 | .arg(mount_option_arg) 35 | .arg(mount_point_arg) 36 | .arg(db_path_arg) 37 | .get_matches(); 38 | 39 | let mut option_vals = ["-o", "fsname=sqlitefs", "-o", "default_permissions", "-o", "allow_other"].to_vec(); 40 | if let Some(v) = matches.get_many::("mount_option") { 41 | for i in v { 42 | option_vals.push("-o"); 43 | option_vals.push(i); 44 | } 45 | } 46 | 47 | let mountpoint = matches.get_one::("mount_point").expect("Mount point path is missing."); 48 | let db_path = matches.get_one::("db_path"); 49 | let options = option_vals 50 | .iter() 51 | .map(|o| o.as_ref()) 52 | .collect::>(); 53 | let fs: SqliteFs; 54 | match db_path { 55 | Some(path) => { 56 | fs = match SqliteFs::new(path) { 57 | Ok(n) => n, 58 | Err(err) => {println!("{:?}", err); return;} 59 | }; 60 | } 61 | None => { 62 | let mut db = match Sqlite::new_in_memory() { 63 | Ok(n) => n, 64 | Err(err) => {println!("{:?}", err); return;} 65 | }; 66 | match db.init() { 67 | Ok(n) => n, 68 | Err(err) => {println!("{:?}", err); return;} 69 | }; 70 | fs = match SqliteFs::new_with_db(db) { 71 | Ok(n) => n, 72 | Err(err) => {println!("{:?}", err); return;} 73 | }; 74 | } 75 | } 76 | match fuse::mount(fs, &mountpoint, &options) { 77 | Ok(n) => n, 78 | Err(err) => error!("{}", err) 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/sqerror.rs: -------------------------------------------------------------------------------- 1 | use std::fmt; 2 | use std::fmt::Display; 3 | use std::error::Error as stdError; 4 | 5 | use failure::{Backtrace, Context, Fail}; 6 | 7 | pub type Result = ::std::result::Result; 8 | 9 | #[derive(Debug)] 10 | pub struct Error { 11 | inner: Context, 12 | } 13 | 14 | #[derive(Debug, Fail)] 15 | pub enum ErrorKind { 16 | #[fail(display = "A sqlite error occured: {}", description)] 17 | SqliteError{description: String}, 18 | #[fail(display = "Target is directory: {}", description)] 19 | FsIsDir{description: String}, 20 | #[fail(display = "Target is not directory: {}", description)] 21 | FsIsNotDir{description: String}, 22 | #[fail(display = "Target is not found: {}", description)] 23 | FsNoEnt{description: String}, 24 | #[fail(display = "Target is not empty: {}", description)] 25 | FsNotEmpty{description: String}, 26 | #[fail(display = "Target file is already exist: {}", description)] 27 | FsFileExist{description: String}, 28 | #[fail(display = "Invalid argument: {}", description)] 29 | FsParm{description: String}, 30 | #[fail(display = "Undefined error: {}", description)] 31 | Undefined{description: String}, 32 | } 33 | 34 | impl Fail for Error { 35 | fn cause(&self) -> Option<&dyn Fail> { 36 | self.inner.cause() 37 | } 38 | 39 | fn backtrace(&self) -> Option<&Backtrace> { 40 | self.inner.backtrace() 41 | } 42 | } 43 | 44 | impl Display for Error { 45 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 46 | Display::fmt(&self.inner, f) 47 | } 48 | } 49 | 50 | impl Error { 51 | pub fn kind(&self) -> &ErrorKind { 52 | self.inner.get_context() 53 | } 54 | } 55 | 56 | impl From for Error { 57 | fn from(kind: ErrorKind) -> Error { 58 | Error { 59 | inner: Context::new(kind), 60 | } 61 | } 62 | } 63 | 64 | impl From> for Error { 65 | fn from(inner: Context) -> Error { 66 | Error { inner } 67 | } 68 | } 69 | 70 | impl From for Error { 71 | fn from(err: rusqlite::Error) -> Error { 72 | Error { 73 | inner: Context::new( 74 | ErrorKind::SqliteError { 75 | description: String::from(format!("{} {:?}", err.description(), err)) 76 | } 77 | ) 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /tests/filesystem.rs: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /tests/helpers/mod.rs: -------------------------------------------------------------------------------- 1 | #![allow(dead_code)] 2 | extern crate tempfile; 3 | use nix::dir::Dir; 4 | use sqlite_fs::db_module::{sqlite, DbModule}; 5 | use std::fs::File; 6 | use std::mem; 7 | 8 | enum DirOrNot { 9 | Empty, 10 | Exist(tempfile::TempDir), 11 | } 12 | 13 | pub struct DBWithTempFile { 14 | pub db: sqlite::Sqlite, 15 | dir: DirOrNot, 16 | } 17 | 18 | impl DBWithTempFile { 19 | pub fn new() -> Self { 20 | let dir = tempfile::tempdir().unwrap(); 21 | let file_path = dir.path().join("filesystem.db"); 22 | let db = sqlite::Sqlite::new(file_path.as_path()).unwrap(); 23 | let dir = DirOrNot::Exist(dir); 24 | Self { db, dir } 25 | } 26 | } 27 | 28 | impl Drop for DBWithTempFile { 29 | fn drop(&mut self) { 30 | let dir = mem::replace(&mut self.dir, DirOrNot::Empty); 31 | match dir { 32 | DirOrNot::Empty => (), 33 | DirOrNot::Exist(temp) => { 34 | temp.close().unwrap(); 35 | } 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /tests/sqlite.rs: -------------------------------------------------------------------------------- 1 | use sqlite_fs::db_module::{sqlite, DbModule}; 2 | 3 | mod helpers; 4 | #[test] 5 | fn sqlite_create_db() { 6 | let db = sqlite::Sqlite::new_in_memory(); 7 | match db { 8 | Ok(_) => assert!(true), 9 | Err(_) => assert!(false, "failed to create db in memory"), 10 | } 11 | } 12 | 13 | #[test] 14 | fn sqlite_create_db_file() { 15 | let mut dbf = helpers::DBWithTempFile::new(); 16 | match dbf.db.init() { 17 | Ok(_) => assert!(true), 18 | Err(_) => assert!(false, "failed to create db file"), 19 | } 20 | } 21 | 22 | #[test] 23 | fn sqlite_init_db() { 24 | let mut db = match sqlite::Sqlite::new_in_memory() { 25 | Ok(n) => n, 26 | Err(_) => { 27 | assert!(false, "failed to create db in memory"); 28 | return; 29 | } 30 | }; 31 | match db.init() { 32 | Ok(_) => assert!(true), 33 | Err(_) => assert!(false, "failed to init db"), 34 | } 35 | } 36 | --------------------------------------------------------------------------------