diff --git a/Makefile b/Makefile index 9108fc1..1350c54 100644 --- a/Makefile +++ b/Makefile @@ -39,7 +39,8 @@ SOURCES := \ src/scan.c \ src/create.c \ src/list.c \ - src/diff.c + src/diff.c \ + src/verify.c TESTS := tests/run.sh diff --git a/README.md b/README.md index f3ffda9..ecf2a9f 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ today, and points at the spec where the two differ. ## What it does today -Four commands are implemented: +Five commands are implemented: | Command | Description | | --- | --- | @@ -25,10 +25,11 @@ Four commands are implemented: | `fsnap create ` | Recursively walk ``, compute fingerprints, and write one metadata record per entry into ``. | | `fsnap list ` | Read `` and validate every record. Reports the first malformed record on stderr; prints nothing when the snapshot is sound. | | `fsnap diff ` | Load both snapshots, sort their records by path, and print additions, deletions, and changes. | +| `fsnap verify ` | Compare a snapshot with the live tree rooted at `` and print every lost, new, or changed entry. | `list` is a parser and validator by design, not a pretty-printer — see -[SPEC.md](SPEC.md) §12. `verify` (compare a snapshot against the live -filesystem) is not implemented. See the [Roadmap](#roadmap). +[SPEC.md](SPEC.md) §12. `verify` is the live-filesystem counterpart of `diff`; +see [SPEC.md](SPEC.md) §18. ## Building @@ -40,13 +41,13 @@ make # produces build/fsnap make clean ``` -`make test` runs the suite in [tests/run.sh](tests/run.sh): 91 black-box checks +`make test` runs the suite in [tests/run.sh](tests/run.sh): 114 black-box checks driving the built binary over the tree shapes [SPEC.md](SPEC.md) §22 asks for — regular and empty files, nested directories, symlinks, broken symlinks, hard links, FIFOs, sockets, unusual filenames and permission errors — plus the -parser cases from §14 and §15 and the `diff` classifications. It is POSIX sh -with no dependencies, and skips rather than fails what the environment cannot -provide. +parser cases from §14 and §15, the `diff` classifications, and the `verify` +findings. It is POSIX sh with no dependencies, and skips rather than fails what +the environment cannot provide. `make valgrind` runs that same suite with every invocation under memcheck, which takes about 25 seconds against a fraction of a second for `make test`. It @@ -98,9 +99,15 @@ $ fsnap diff old.fsnap new.fsnap A /home/user/projects/example/new-file P /home/user/projects/example/README.md D /home/user/projects/example/old-file + +$ fsnap verify snapshot.fsnap ~/projects/example +A /home/user/projects/example/new-file +M /home/user/projects/example/README.md +D /home/user/projects/example/old-file ``` -The program exits with `0` on success and `1` on failure. `list` internally +The program exits with `0` on success and `1` on failure. `verify` also exits +`1` when it finds a difference, after reporting it on stdout. `list` internally returns `128` for a malformed record, but `main` maps it to exit status `1`. Diagnostics are written to stderr. A malformed snapshot has no distinct public exit status from another failure. @@ -151,6 +158,29 @@ pathname: `snapshot:line: invalid ` or `snapshot:line: unparsable line`, and returns `128` internally; `main` maps it to exit status `1`. +### `verify` output + +`verify` walks `` to find entries absent from the snapshot, then +`lstat`s every stored path. Each finding is printed as `codepath`, with an +extra reason for an access error. One line is printed per entry, in the first +field that differs. + +| Code | Meaning | +| --- | --- | +| `A` | Present in the live tree but absent from the snapshot | +| `D` | Present in the snapshot but absent from the live tree (`ENOENT`) | +| `T` | File type changed | +| `S` | Size changed | +| `P` | Permission bits changed | +| `O` | Owner or group changed | +| `L` | Symlink target changed (checked before size and mtime, which change with it) | +| `M` | Modification time changed | +| `E` | The entry could not be inspected: the path, the reason, and `strerror` are printed. `EACCES`, `ENOTDIR`, `ELOOP` and `ENAMETOOLONG` stay distinct instead of collapsing into "missing" | + +`verify` exits `0` when the tree matches, `1` when it finds a difference, and +`1` on a malformed or unreadable snapshot. A malformed snapshot is reported +with the same `snapshot:line:` diagnostic as `list` and `diff`. + ## Behaviour worth knowing - **Symlinks are not followed, anywhere.** Their metadata comes from `lstat()`, @@ -184,6 +214,19 @@ returns `128` internally; `main` maps it to exit status `1`. empty directory, `list` accepts it silently with exit `0`, and `diff` treats it as carrying no records, so every entry on the other side is reported as added or deleted. +- **`verify` compares paths, not contents.** The stored fingerprint is not + recomputed, so a regular file whose bytes changed while its size and mtime + stayed the same is not reported. +- **`verify` uses the absolute paths stored in the snapshot.** It walks the + given directory to find new entries, but every stored record is checked at + its recorded path, so the tree must still be at the location it was scanned + from. +- **`verify` ignores `.fsnap` files while looking for new entries**, for the + same reason `create` does: a snapshot living inside the tree is not part of + the tree's contents. +- **Every recorded metadata field except the fingerprint is compared**, + including a directory's size and mtime. Adding or removing a child can + therefore report its parent as well as the child itself. ## Known limitations @@ -224,7 +267,7 @@ Rough order of intent, no timeline: - [ ] Record inode, device ID, and link count so hard links can be identified. - [ ] Report a snapshot that grew between the counting pass and the parsing pass instead of silently ignoring the extra records. -- [ ] `fsnap verify ` — compare a snapshot against the live +- [x] `fsnap verify ` — compare a snapshot against the live filesystem, distinguishing `ENOENT`, `EACCES`, `ENOTDIR` and `ELOOP` rather than collapsing them ([SPEC.md](SPEC.md) §18). - [ ] Honour `TMPDIR` instead of hardcoding `/tmp`. diff --git a/include/command.h b/include/command.h index 4644ca1..d85f71a 100644 --- a/include/command.h +++ b/include/command.h @@ -5,5 +5,6 @@ #include "create.h" #include "list.h" #include "diff.h" +#include "verify.h" #endif diff --git a/include/verify.h b/include/verify.h new file mode 100644 index 0000000..827e93f --- /dev/null +++ b/include/verify.h @@ -0,0 +1,11 @@ +#ifndef VERIFY_H +#define VERIFY_H + +#include "status.h" + +/* Compare a snapshot with the live tree rooted at root_fs. + Returns 0 when they match, 1 when differences were found and reported on + stdout, -1 on a system/IO error, and FSNAP_EPARSE on a malformed snapshot. */ +int verify(const char *snapshot, const char *root_fs); + +#endif diff --git a/src/main.c b/src/main.c index 9bd23c7..9dc3dd6 100644 --- a/src/main.c +++ b/src/main.c @@ -6,7 +6,8 @@ int main(int argc, char *argv[]) { if (argc < 2) { - fprintf(stderr, "%s: command not found [scan|create|list|diff]\n", argv[0]); + fprintf(stderr, "%s: command not found [scan|create|list|diff|verify]\n", + argv[0]); return EXIT_FAILURE; } @@ -41,8 +42,8 @@ int main(int argc, char *argv[]) { } } else if (strcmp(cmd, "list") == 0) { if (argc < 3) { - fprintf(stderr, "%s: command %s expected param [snapshot_file]\n", argv[0], - cmd); + fprintf(stderr, "%s: command %s expected param [snapshot_file]\n", + argv[0], cmd); return EXIT_FAILURE; } const char *snapshot = argv[2]; @@ -56,9 +57,10 @@ int main(int argc, char *argv[]) { } } else if (strcmp(cmd, "diff") == 0) { if (argc < 4) { - fprintf(stderr, - "%s: command %s expected params [snapshot_file1 snapshot_file2]\n", - argv[0], cmd); + fprintf( + stderr, + "%s: command %s expected params [snapshot_file1 snapshot_file2]\n", + argv[0], cmd); return EXIT_FAILURE; } const char *snapshot1 = argv[2]; @@ -71,6 +73,23 @@ int main(int argc, char *argv[]) { } else if (ret > 0) { return EXIT_FAILURE; } + } else if (strcmp(cmd, "verify") == 0) { + if (argc < 4) { + fprintf(stderr, + "%s: command %s expected params [snapshot_file directory]\n", + argv[0], cmd); + return EXIT_FAILURE; + } + const char *snapshot = argv[2]; + const char *root_fs = argv[3]; + int ret = verify(snapshot, root_fs); + if (ret == -1) { + const int err = errno; + fprintf(stderr, "verify failed: %s\n", strerror(err)); + return EXIT_FAILURE; + } else if (ret > 0) { + return EXIT_FAILURE; + } } else { fprintf(stderr, "command %s is not valid\n", cmd); return EXIT_FAILURE; diff --git a/src/verify.c b/src/verify.c new file mode 100644 index 0000000..64ccd76 --- /dev/null +++ b/src/verify.c @@ -0,0 +1,384 @@ +#include "verify.h" +#include "status.h" +#include "types.h" +#include "utility.h" +#include "walk.h" +#include +#include +#include +#include +#include +#include +#include +#include + +/* Verification findings are printed as codepath, the same shape diff + uses. A finding is not an error: the snapshot was read and the filesystem + answered every question. Only a failure to do either returns -1. */ +struct VerifyContext { + struct RecordObject **records; + int count; + int differences; +}; + +static int order_by_path(const void *o1, const void *o2) { + const struct RecordObject *r1 = *(const struct RecordObject *const *)o1; + const struct RecordObject *r2 = *(const struct RecordObject *const *)o2; + return strcmp(RecordObjectPath(r1), RecordObjectPath(r2)); +} + +static int find_record(struct RecordObject *const *records, int count, + const char *path) { + int lo = 0; + int hi = count - 1; + + while (lo <= hi) { + const int mid = lo + (hi - lo) / 2; + const int c = strcmp(path, RecordObjectPath(records[mid])); + if (c == 0) + return 1; + if (c < 0) + hi = mid - 1; + else + lo = mid + 1; + } + return 0; +} + +/* create() ignores snapshot files so that a snapshot inside the tree does not + end up in its own successor. verify() has to ignore the same names, or the + snapshot it is reading would be reported as a newly added file. */ +static int is_snapshot_name(const char *path) { + const char *base = strrchr(path, '/'); + base = base ? base + 1 : path; + const size_t n = strlen(base); + return n >= 6 && strcasecmp(base + n - 6, ".fsnap") == 0; +} + +static int report(char code, const char *path, int *differences) { + if (fprintf(stdout, "%c\t%s\n", code, path) < 0) + return -1; + *differences = 1; + return 0; +} + +static int report_access(const char *path, int err, int *differences) { + if (fprintf(stdout, "E\t%s\t%s\n", path, strerror(err)) < 0) + return -1; + *differences = 1; + return 0; +} + +static int mark_new(const char *path, void *context) { + struct VerifyContext *ctx = context; + + if (is_snapshot_name(path)) + return 0; + + if (!find_record(ctx->records, ctx->count, path)) + return report('A', path, &ctx->differences); + + return 0; +} + +static int same_type(char type, mode_t mode) { + switch (type) { + case 'F': + return S_ISREG(mode) != 0; + case 'D': + return S_ISDIR(mode) != 0; + case 'L': + return S_ISLNK(mode) != 0; + case 'P': + return S_ISFIFO(mode) != 0; + case 'C': + return S_ISCHR(mode) != 0; + case 'B': + return S_ISBLK(mode) != 0; + case 'S': + return S_ISSOCK(mode) != 0; + case '?': + return !S_ISREG(mode) && !S_ISDIR(mode) && !S_ISLNK(mode) && + !S_ISFIFO(mode) && !S_ISCHR(mode) && !S_ISBLK(mode) && + !S_ISSOCK(mode); + default: + return 0; + } +} + +/* readlink() does not terminate its buffer and silently truncates when the + target does not fit. The reported st_size is not reliable on every + filesystem, so fall back to the limit of the filesystem holding the link. */ +static char *read_target(const char *path, const struct stat *st) { + size_t bufsiz = (size_t)st->st_size + 1; + + if (st->st_size == 0) { + errno = 0; + const long limit = pathconf(path, _PC_PATH_MAX); + if (limit <= 0) { + if (errno != 0) + return NULL; + bufsiz = PATH_MAX; + } else { + bufsiz = (size_t)limit; + } + } + + char *target = calloc(bufsiz, sizeof(char)); + if (target == NULL) { + errno = ENOMEM; + return NULL; + } + + const ssize_t n = readlink(path, target, bufsiz); + if (n == -1) { + const int saved_errno = errno; + free(target); + errno = saved_errno; + return NULL; + } + if ((size_t)n >= bufsiz) { + free(target); + errno = ENAMETOOLONG; + return NULL; + } + target[n] = '\0'; + return target; +} + +static int verify_target(const struct RecordObject *record, + const struct stat *st, int *differences) { + const char *path = RecordObjectPath(record); + char *target = read_target(path, st); + if (target == NULL) { + switch (errno) { + case EACCES: + case ENOENT: + case ENOTDIR: + case ELOOP: + case EINVAL: + case ENAMETOOLONG: + return report_access(path, errno, differences); + default: + return -1; + } + } + + const char *stored = RecordObjectTarget(record); + if (stored == NULL) + stored = ""; + + int rc = 0; + if (strcmp(target, stored) != 0) + rc = report('L', path, differences); + + free(target); + return rc; +} + +/* Compare one stored record with the live entry at the same path. A record + whose path no longer exists is a deletion; the errors that mean "there is + nothing usable here" are reported as findings, with their own reason, while + an unexpected lstat() failure is propagated as a system error. */ +static int verify_record(const struct RecordObject *record, int *differences) { + const char *path = RecordObjectPath(record); + struct stat st; + + if (lstat(path, &st) == -1) { + switch (errno) { + case ENOENT: + return report('D', path, differences); + case EACCES: + case ENOTDIR: + case ELOOP: + case ENAMETOOLONG: + return report_access(path, errno, differences); + default: + return -1; + } + } + + const char type = RecordObjectFileType(record); + + if (!same_type(type, st.st_mode)) + return report('T', path, differences); + + /* A symlink's size is the length of its target, and its mtime changes when + the link is rebuilt. The target string is the specific answer, so it is + checked before either and the size is left to it. */ + if (type == 'L') { + if (RecordObjectTarget(record) != NULL) { + const int rc = verify_target(record, &st, differences); + if (rc != 0) + return rc; + } + return 0; + } + + if ((intmax_t)st.st_size != RecordObjectSize(record)) + return report('S', path, differences); + + if ((unsigned int)(st.st_mode & 07777) != RecordObjectPermissions(record)) + return report('P', path, differences); + + if ((uintmax_t)st.st_uid != RecordObjectUid(record) || + (uintmax_t)st.st_gid != RecordObjectGid(record)) + return report('O', path, differences); + + if ((intmax_t)st.st_mtime != RecordObjectTime(record)) + return report('M', path, differences); + + return 0; +} + +static void release_records(struct RecordObject **records, int count) { + if (records == NULL) + return; + for (int i = 0; i < count; i++) + RecordObjectRelease(records[i]); + free(records); +} + +static int load_snapshot(const char *file, struct RecordObject ***out, + int *out_count) { + int rc = -1; + FILE *stream = NULL; + char *buf = NULL; + struct RecordObject **records = NULL; + int count = 0; + + if ((stream = fopen(file, "r")) == NULL) + goto cleanup; + + count = count_lines(file); + if (count < 0) + goto cleanup; + + if (count == 0) { + *out = NULL; + *out_count = 0; + rc = 0; + goto cleanup; + } + + records = calloc((size_t)count, sizeof(*records)); + if (records == NULL) { + errno = ENOMEM; + goto cleanup; + } + + int i = 0; + size_t size = 0; + while (i < count && getline(&buf, &size, stream) != -1) { + struct RecordObject *record = RecordObjectNew(); + if (record == NULL) + goto cleanup; + + enum Fields err = NONE; + errno = 0; + if (RecordObjectUnpack(record, buf, &err) == -1) { + /* An allocation failure is not a malformed record and must not be + reported as one; errno tells them apart. */ + if (errno != EINVAL) { + RecordObjectRelease(record); + goto cleanup; + } + + if (err != NONE) + fprintf(stderr, "%s:%d: invalid %s\n", file, i + 1, + RecordObjectFieldName(err)); + else + fprintf(stderr, "%s:%d: unparsable line\n", file, i + 1); + RecordObjectRelease(record); + rc = FSNAP_EPARSE; + goto cleanup; + } + + records[i] = record; + i++; + } + + if (ferror(stream)) + goto cleanup; + + *out = records; + *out_count = i; + records = NULL; + rc = 0; + +cleanup:; + const int saved_errno = errno; + int cleanup_errno = 0; + + if (stream != NULL && fclose(stream) != 0) + cleanup_errno = errno; + + release_records(records, count); + free(buf); + + if (rc == -1) { + errno = saved_errno; + return -1; + } + if (rc == 0 && cleanup_errno != 0) { + errno = cleanup_errno; + return -1; + } + return rc; +} + +int verify(const char *snapshot, const char *root_fs) { + if (snapshot == NULL || snapshot[0] == '\0' || root_fs == NULL || + root_fs[0] == '\0') { + errno = EINVAL; + return -1; + } + + int rc = -1; + char *resolved = NULL; + struct RecordObject **records = NULL; + int count = 0; + int differences = 0; + + resolved = resolve_path(root_fs); + if (resolved == NULL) + goto cleanup; + + rc = load_snapshot(snapshot, &records, &count); + if (rc != 0) + goto cleanup; + + if (records != NULL) + qsort(records, (size_t)count, sizeof(records[0]), order_by_path); + + struct VerifyContext ctx = {records, count, differences}; + if (walk(resolved, mark_new, &ctx) == -1) { + rc = -1; + goto cleanup; + } + differences = ctx.differences; + + for (int i = 0; i < count; i++) { + if (verify_record(records[i], &differences) == -1) { + rc = -1; + goto cleanup; + } + } + + /* stdout is block-buffered when redirected, so a write error can surface + only here. */ + if (fflush(stdout) == EOF) { + rc = -1; + goto cleanup; + } + + rc = differences ? 1 : 0; + +cleanup:; + const int saved_errno = errno; + release_records(records, count); + free(resolved); + if (rc == -1) + errno = saved_errno; + return rc; +} diff --git a/tests/run.sh b/tests/run.sh index 92c9f20..489d6f9 100755 --- a/tests/run.sh +++ b/tests/run.sh @@ -431,6 +431,123 @@ isnt "diff reports a real diagnostic, not Success" "$err" "diff failed: Success" fsnap diff /nonexistent.fsnap snap.fsnap >/dev/null 2>&1 is "diff fails on a missing input" "$?" "1" +# -------------------------------------------------------------------------- +# verify +# -------------------------------------------------------------------------- +# Each test starts from the same small tree, because a change to the live +# filesystem is what verify is asked to notice. +verify_fixture() { + rm -rf vtree vsnap.fsnap + mkdir -p vtree/sub + printf 'hello\n' >vtree/file.txt + printf 'nested\n' >vtree/sub/nested.txt + ln -s file.txt vtree/link.txt + fsnap create vtree vsnap.fsnap >/dev/null 2>&1 +} + +verify_fixture +out=$(fsnap verify vsnap.fsnap vtree 2>&1) +is "verify of an unchanged tree succeeds" "$?" "0" +is "verify of an unchanged tree is silent" "$out" "" + +printf 'new\n' >vtree/new.txt +out=$(fsnap verify vsnap.fsnap vtree 2>&1) +is "verify reports a difference with a failure status" "$?" "1" +contains "a new file is reported as A" "$out" \ + "$(printf 'A\t%s/vtree/new.txt' "$WORK")" + +verify_fixture +rm vtree/file.txt +out=$(fsnap verify vsnap.fsnap vtree 2>&1) +contains "a missing file is reported as D" "$out" \ + "$(printf 'D\t%s/vtree/file.txt' "$WORK")" + +verify_fixture +printf 'more\n' >>vtree/file.txt +out=$(fsnap verify vsnap.fsnap vtree 2>&1) +contains "a size change is reported as S" "$out" \ + "$(printf 'S\t%s/vtree/file.txt' "$WORK")" + +verify_fixture +chmod 600 vtree/file.txt +out=$(fsnap verify vsnap.fsnap vtree 2>&1) +contains "a permission change is reported as P" "$out" \ + "$(printf 'P\t%s/vtree/file.txt' "$WORK")" + +verify_fixture +if touch -t 200001010000 vtree/file.txt 2>/dev/null; then + out=$(fsnap verify vsnap.fsnap vtree 2>&1) + contains "an mtime change is reported as M" "$out" \ + "$(printf 'M\t%s/vtree/file.txt' "$WORK")" +else + skip "an mtime change is reported as M (touch -t unavailable)" +fi + +verify_fixture +ln -sf other-target vtree/link.txt +out=$(fsnap verify vsnap.fsnap vtree 2>&1) +contains "a changed symlink target is reported as L" "$out" \ + "$(printf 'L\t%s/vtree/link.txt' "$WORK")" + +verify_fixture +rm vtree/file.txt +mkdir vtree/file.txt +out=$(fsnap verify vsnap.fsnap vtree 2>&1) +contains "a changed file type is reported as T" "$out" \ + "$(printf 'T\t%s/vtree/file.txt' "$WORK")" + +verify_fixture +rm -rf vtree/sub +: >vtree/sub +out=$(fsnap verify vsnap.fsnap vtree 2>&1) +contains "ENOTDIR is distinguished from a missing file" "$out" \ + "$(printf 'E\t%s/vtree/sub/nested.txt\tNot a directory' "$WORK")" + +verify_fixture +if [ "$(id -u)" = "0" ]; then + skip "EACCES is distinguished from a missing file (running as root)" +else + chmod 000 vtree/sub + out=$(fsnap verify vsnap.fsnap vtree 2>&1) + contains "EACCES is distinguished from a missing file" "$out" \ + "$(printf 'E\t%s/vtree/sub/nested.txt\tPermission denied' "$WORK")" + chmod 755 vtree/sub +fi + +verify_fixture +: >vempty.fsnap +mkdir vempty +out=$(fsnap verify vempty.fsnap vempty 2>&1) +is "verify of an empty snapshot against an empty directory succeeds" "$?" "0" +is "verify of an empty snapshot against an empty directory is silent" "$out" "" + +out=$(fsnap verify vempty.fsnap vtree 2>&1) +is "verify of an empty snapshot against a populated tree fails" "$?" "1" +is "every entry is reported as new" \ + "$(printf '%s\n' "$out" | grep -c '^A ')" \ + "$(count_entries vtree)" + +verify_fixture +fsnap create vtree vtree/self.fsnap >/dev/null 2>&1 +out=$(fsnap verify vtree/self.fsnap vtree 2>&1) +isnt "verify does not report the snapshot file as new" "$out" \ + "$(printf 'A\t%s/vtree/self.fsnap' "$WORK")" +# Writing the snapshot changed the metadata of the directory holding it, so +# silence is not guaranteed here; the point is that no A line names the +# snapshot itself. +is "verify finds no new entries when only the snapshot changed" \ + "$(printf '%s\n' "$out" | grep -c '^A ')" "0" + +printf 'X|nope\n' >badv.fsnap +err=$(fsnap verify badv.fsnap vtree 2>&1) +is "verify fails on a malformed snapshot" "$?" "1" +contains "verify names the offending line" "$err" "badv.fsnap:1:" + +fsnap verify /nonexistent.fsnap vtree >/dev/null 2>&1 +is "verify fails on a missing snapshot" "$?" "1" +fsnap verify vsnap.fsnap /nonexistent-directory >/dev/null 2>&1 +is "verify fails on a missing directory" "$?" "1" + # -------------------------------------------------------------------------- # A failed create must not leave a stale snapshot looking like a fresh one. # -------------------------------------------------------------------------- @@ -452,6 +569,8 @@ fsnap create tree >/dev/null 2>&1 is "create without its second argument is an error" "$?" "1" fsnap diff snap.fsnap >/dev/null 2>&1 is "diff without its second argument is an error" "$?" "1" +fsnap verify snap.fsnap >/dev/null 2>&1 +is "verify without its second argument is an error" "$?" "1" # -------------------------------------------------------------------------- printf '\n1..%d\n' "$testno"