diff --git a/Makefile b/Makefile index e7d4b84..37f1aa4 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,7 @@ CC := cc CPPFLAGS := -Iinclude -MMD -MP -CFLAGS := -std=c11 -Wall -Wextra -Wpedantic -Wconversion +CFLAGS := -std=c11 -Wall -Wextra -Wpedantic -Wconversion -ggdb LDFLAGS := LDLIBS := @@ -16,7 +16,8 @@ SOURCES := \ src/walk.c \ src/scan.c \ src/create.c \ - src/list.c + src/list.c \ + src/diff.c OBJECTS := $(SOURCES:%.c=$(BUILD_DIR)/%.o) DEPENDENCIES := $(OBJECTS:.o=.d) diff --git a/README.md b/README.md index 5e5bb65..4cec39f 100644 --- a/README.md +++ b/README.md @@ -17,18 +17,18 @@ today, and points at the spec where the two differ. ## What it does today -Three commands, and that is the whole feature set: +Four commands are implemented: | Command | Description | | --- | --- | | `fsnap scan ` | Recursively walk `` and print every entry to stdout. | | `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. | `list` is a parser and validator by design, not a pretty-printer — see -[SPEC.md](SPEC.md) §12. The two remaining commands, `fsnap diff` (compare two -snapshots) and `fsnap verify` (compare a snapshot against the live filesystem), -are later stages and are **not** implemented. See the [Roadmap](#roadmap). +[SPEC.md](SPEC.md) §12. `verify` (compare a snapshot against the live +filesystem) is not implemented. See the [Roadmap](#roadmap). ## Building @@ -68,11 +68,17 @@ L|0777|1000|1000|6|1785598700|main.c|0|/home/user/projects/example/symlink-test $ fsnap list snapshot.fsnap # silence means every record parsed $ fsnap list broken.fsnap broken.fsnap:3: invalid permissions + +$ 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 ``` -Exit status is `0` on success and `1` on failure (or `128` in case of malformed snapshots parsed by `list`), with the reason printed to -stderr. A malformed snapshot makes `list` exit with a failure code — there is no -distinct status for "the file was readable but its contents are not valid". +The program exits with `0` on success and `1` on failure. `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. ## Snapshot format @@ -89,23 +95,45 @@ type|permissions|uid|gid|size|time|target|fingerprint|path | `uid` / `gid` | Numeric owner and group | | `size` | Size in bytes, as reported by `lstat` | | `time` | Modification time, seconds since the Unix epoch | -| `target` | Symlink target (resolved via `readlink` and escaped; empty for non-symlink entries) | -| `fingerprint` | CRC32 checksum of file contents (computed for non-directory types; `0` for directories) | -| `path` | Absolute path, resolved through `realpath` and escaped | +| `target` | Symlink target returned by `readlink`; empty for non-symlink entries | +| `fingerprint` | CRC32 checksum read through `fopen(path, "r")` for every non-directory entry; `0` for directories | +| `path` | Absolute path: the input root is resolved with `realpath`, then child names are appended; it is escaped | ### Escaping rules -The snapshot format handles unusual paths and symlink targets safely by escaping delimiters and special characters: +Only the `path` field is escaped by the writer: - `\` is escaped to `\\` - `|` is escaped to `\|` - Newlines are escaped to `\n` -The `list` parser automatically unescapes these fields during validation. +The parser unescapes both `path` and `target`, but the writer does not escape +`target`. Consequently, a symlink target containing `|`, a newline, or a +backslash does not produce a reliably parseable snapshot. + +### `diff` output + +Each change is printed as `codepath` after both inputs have been sorted by +pathname: + +| Code | Current meaning | +| --- | --- | +| `A` | Present only in the new snapshot | +| `D` | Present only in the old snapshot | +| `P` | Permissions are the first differing field | +| `L` | Symlink target is the only differing field after the other compared fields match | +| `M` | Any other difference, including type, owner, size, time, or fingerprint | + +`diff` does not print a line number or field name when an input snapshot is +malformed; it fails with `EINVAL`. ## Behaviour worth knowing -- **Symlinks are recorded, and their targets are stored.** Metadata comes from `lstat`, so the walk does not descend into symlinks, but the symlink target is read using `readlink()` and saved in the `target` field. Broken symlinks are recorded normally. -- **Paths are absolute**, resolved through `realpath`. Snapshots are therefore - tied to the machine and the location they were taken from. +- **Symlinks are not followed by the walker.** Their metadata comes from + `lstat()` and their target is read using `readlink()`. The subsequent + fingerprint step opens the symlink target, however, so `create` fails for a + broken symlink and fingerprints the referent rather than the link target. +- **Paths are absolute.** The input directory is resolved through `realpath()` + before traversal; snapshots are tied to the machine and location where they + were taken. - **Entries appear in `readdir` order**, not sorted. Two snapshots of the same unchanged tree are not guaranteed to be byte-identical. - **Files whose name ends in `.fsnap` are skipped by `create`**, so an existing @@ -142,11 +170,17 @@ These are actual, reproduced problems, not hypotheticals: is unreadable, the result is an empty snapshot reported as success. - **No hard-link or inode information** is recorded, so hard links cannot be detected and identical files cannot be correlated. +- **`create` is unsafe for several non-regular entry types.** It attempts to + open every non-directory entry to fingerprint it. A FIFO can block forever; + devices, sockets, unreadable files, and broken symlinks can make creation + fail. +- **Symlink targets are not escaped by the writer.** A target containing `|`, a + newline, or a backslash can make the generated record unparsable by `list`. - **`list` counts the lines in a separate pass over the file.** If the snapshot grows between the counting pass and the parsing pass, the records past the original count are silently ignored and `list` still exits `0`. -- **No test suite.** The `tests/` directory exists but is empty, and none of the - tree shapes listed in [SPEC.md](SPEC.md) §22 (hard links, device nodes) are exercised automatically. +- **No test suite.** There is currently no `tests/` directory or automated + coverage for the tree shapes listed in [SPEC.md](SPEC.md) §22. ## Roadmap @@ -164,8 +198,6 @@ 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 diff ` — compare two snapshots and - classify each change ([SPEC.md](SPEC.md) §17). - [ ] `fsnap verify ` — compare a snapshot against the live filesystem, distinguishing `ENOENT`, `EACCES`, `ENOTDIR` and `ELOOP` rather than collapsing them ([SPEC.md](SPEC.md) §18). diff --git a/include/command.h b/include/command.h index 1c3e32d..4644ca1 100644 --- a/include/command.h +++ b/include/command.h @@ -4,5 +4,6 @@ #include "scan.h" #include "create.h" #include "list.h" +#include "diff.h" #endif diff --git a/include/diff.h b/include/diff.h new file mode 100644 index 0000000..5a46e21 --- /dev/null +++ b/include/diff.h @@ -0,0 +1,6 @@ +#ifndef DIFF_H +#define DIFF_H + +int diff(const char *file1, const char *file2); + +#endif diff --git a/include/types.h b/include/types.h index a0d5ba1..ceb6a34 100644 --- a/include/types.h +++ b/include/types.h @@ -1,6 +1,8 @@ #ifndef TYPE_H #define TYPE_H +#include + enum Fields { FILE_TYPE, PERMISSIONS, @@ -16,10 +18,23 @@ enum Fields { extern enum Fields field; -const char *field_name(enum Fields f); +const char *FieldName(enum Fields f); struct RecordObject; -struct RecordObject *unpack(char *s); -int release(struct RecordObject *obj); + +// Methods +struct RecordObject *NewRecordObject(); +int Unpack(struct RecordObject *, char *); +int Compare(struct RecordObject *, struct RecordObject *); +char GetFileType(const struct RecordObject *); +unsigned int GetPermissions(const struct RecordObject *); +uintmax_t GetUid(const struct RecordObject *); +uintmax_t GetGid(const struct RecordObject *); +intmax_t GetSize(const struct RecordObject *); +intmax_t GetTime(const struct RecordObject *); +const char *GetPath(const struct RecordObject *); +const char *GetTarget(const struct RecordObject *); +uintmax_t GetFingerPrint(const struct RecordObject *); +int Release(struct RecordObject *); #endif diff --git a/include/utility.h b/include/utility.h index 6e41bb7..2720b4c 100644 --- a/include/utility.h +++ b/include/utility.h @@ -7,4 +7,6 @@ char *resolve_path(const char *path); int copy(const char *src, const char *dst); +int count_lines(const char *file); + #endif diff --git a/src/diff.c b/src/diff.c new file mode 100644 index 0000000..970aa22 --- /dev/null +++ b/src/diff.c @@ -0,0 +1,187 @@ +#define _POSIX_C_SOURCE 200809L +#include "diff.h" +#include "types.h" +#include "utility.h" +#include +#include +#include +#include + +static int load_in_memory(const char *file, struct RecordObject ***records, + int *count) { + int exit_failure = -1; + FILE *stream = NULL; + char *buf = NULL; + + if ((stream = fopen(file, "r")) == NULL) + goto failure; + + *count = count_lines(file); + if (*count == 0) + goto success; + else if (*count < 0) + goto failure; + + *records = calloc((size_t)*count, sizeof(**records)); + if (*records == NULL) { + errno = ENOMEM; + goto failure; + } + + int i = 0; + size_t size = 0; + while (getline(&buf, &size, stream) != -1 && i < *count) { + struct RecordObject *objp = NewRecordObject(); + if (objp == NULL) { + errno = ENOMEM; + goto failure; + } + + int ret = Unpack(objp, buf); + if (ret == -1) { + errno = EINVAL; + Release(objp); + goto failure; + } + + (*records)[i] = objp; + i++; + } + + if (ferror(stream)) + goto failure; + +success: + if (stream != NULL) + fclose(stream); + if (buf != NULL) + free(buf); + + return 0; + +failure: + if (stream != NULL) + fclose(stream); + if (buf != NULL) + free(buf); + + return exit_failure; +} + +static int dealloc(struct RecordObject **records, int size) { + for (int j = 0; j < size; j++) { + Release(records[j]); + records[j] = NULL; + } + free(records); + return 0; +} + +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(GetPath(r1), GetPath(r2)); +} + +int diff(const char *file1, const char *file2) { + int exit_failure = -1; + struct RecordObject **records1 = NULL; + struct RecordObject **records2 = NULL; + + int len1 = 0; + int ret1 = load_in_memory(file1, &records1, &len1); + if (ret1 == -1) { + goto failure; + } else if (ret1 > 0) { + exit_failure = ret1; + goto failure; + } + + int len2 = 0; + int ret2 = load_in_memory(file2, &records2, &len2); + if (ret2 == -1) { + goto failure; + } else if (ret2 > 0) { + exit_failure = ret2; + goto failure; + } + + qsort(records1, (size_t)len1, sizeof(records1[0]), order_by_path); + qsort(records2, (size_t)len2, sizeof(records2[0]), order_by_path); + + int m = 0, n = 0; + while (m < len1 && n < len2) { + struct RecordObject *r1 = records1[m]; + struct RecordObject *r2 = records2[n]; + + char code = 0; + const char *path = NULL; + int c = strcmp(GetPath(r1), GetPath(r2)); + if (c < 0) { + code = 'D'; + path = GetPath(r1); + m++; + } else if (c > 0) { + code = 'A'; + path = GetPath(r2); + n++; + } else if (Compare(r1, r2) != 0) { + switch (field) { + case TARGET: + code = 'L'; + break; + case PERMISSIONS: + code = 'P'; + break; + default: + code = 'M'; + break; + } + path = GetPath(r1); + m++; + n++; + } else { + m++; + n++; + } + + if (code != 0) { + fprintf(stdout, "%c\t%s\n", code, path); + } + } + + while (m < len1) { + const struct RecordObject *r = records1[m]; + fprintf(stdout, "D\t%s\n", GetPath(r)); + m++; + } + + while (n < len2) { + const struct RecordObject *r = records2[n]; + fprintf(stdout, "A\t%s\n", GetPath(r)); + n++; + } + + if (records1 != NULL) { + dealloc(records1, len1); + records1 = NULL; + } + if (records2 != NULL) { + dealloc(records2, len2); + records2 = NULL; + } + + return 0; + +failure: + if (records1 != NULL) { + dealloc(records1, len1); + records1 = NULL; + } + if (records2 != NULL) { + dealloc(records2, len2); + records2 = NULL; + } + + return exit_failure; +} diff --git a/src/list.c b/src/list.c index e8da06a..39702c4 100644 --- a/src/list.c +++ b/src/list.c @@ -1,40 +1,13 @@ #define _POSIX_C_SOURCE 200809L #include "list.h" #include "types.h" +#include "utility.h" #include #include #include #include #include -static int count_lines(const char *file) { - FILE *f = fopen(file, "r"); - if (f == NULL) { - return -1; - } - - size_t size = 0; - int count = 0; - char *buf = NULL; - while (getline(&buf, &size, f) != -1) - count++; - - if (ferror(f)) { - /* Capture before the cleanup: free and fclose may both touch errno. */ - const int saved_errno = errno; - free(buf); - fclose(f); - errno = saved_errno; - return -1; - } - - free(buf); - if (fclose(f) != 0) { - return -1; - } - return count; -} - int list(const char *snapshot) { FILE *snapshot_file = fopen(snapshot, "r"); if (snapshot_file == NULL) { @@ -60,20 +33,26 @@ int list(const char *snapshot) { goto out; } while (getline(&buf, &size, snapshot_file) != -1 && i < arr_size) { - struct RecordObject *objp = unpack(buf); + struct RecordObject *objp = NewRecordObject(); if (objp == NULL) { + rc = -1; + goto out; + } + int ret = Unpack(objp, buf); + if (field != NONE) { + fprintf(stderr, "%s:%d: invalid %s\n", snapshot, i + 1, FieldName(field)); + rc = 128; + Release(objp); + break; + } + + if (ret == -1) { fprintf(stderr, "%s:%d: unparsable line\n", snapshot, i + 1); + Release(objp); rc = 128; break; } - if (field != NONE) { - fprintf(stderr, "%s:%d: invalid %s\n", snapshot, i + 1, - field_name(field)); - rc = 128; - release(objp); - break; - } records[i] = objp; i++; } @@ -95,7 +74,7 @@ out:; free(buf); if (records != NULL) { for (int j = 0; j < arr_size; j++) { - release(records[j]); + Release(records[j]); records[j] = NULL; } free(records); diff --git a/src/main.c b/src/main.c index 726b3b6..242cf6f 100644 --- a/src/main.c +++ b/src/main.c @@ -6,7 +6,7 @@ int main(int argc, char *argv[]) { if (argc < 2) { - fprintf(stderr, "%s: command not found [scan|create|list]\n", argv[0]); + fprintf(stderr, "%s: command not found [scan|create|list|diff]\n", argv[0]); return EXIT_FAILURE; } @@ -41,7 +41,7 @@ int main(int argc, char *argv[]) { } } else if (strcmp(cmd, "list") == 0) { if (argc < 3) { - fprintf(stderr, "%s: command %s expected param [snapshot_file]", argv[0], + fprintf(stderr, "%s: command %s expected param [snapshot_file]\n", argv[0], cmd); return EXIT_FAILURE; } @@ -54,6 +54,23 @@ int main(int argc, char *argv[]) { } else if (ret > 0) { return EXIT_FAILURE; } + } else if (strcmp(cmd, "diff") == 0) { + if (argc < 4) { + fprintf(stderr, + "%s: command %s expected params [snapshot_file1 snapshot_file2]\n", + argv[0], cmd); + return EXIT_FAILURE; + } + const char *snapshot1 = argv[2]; + const char *snapshot2 = argv[3]; + int ret = diff(snapshot1, snapshot2); + if (ret == -1) { + const int err = errno; + fprintf(stderr, "diff 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/types.c b/src/types.c index 7e5e9dd..9caa089 100644 --- a/src/types.c +++ b/src/types.c @@ -1,6 +1,5 @@ #include "types.h" #include -#include #include #include #include @@ -13,10 +12,12 @@ static const char *field_names[] = { "file type", "permissions", "uid", "gid", "size", "time", "target", "fingerprint", "path", "none"}; -const char *field_name(enum Fields f) { +const char *FieldName(enum Fields f) { return (f <= NONE) ? field_names[f] : "unknown"; } +//====================== static functions ===================================== + static int split_record(char *line, char *fields[NFIELDS], char delim) { char *p = line; @@ -170,6 +171,8 @@ static int parse_intmax_nonnegative(const char *s, intmax_t *out) { return 0; } +//========================= RecordObject ================================= + struct RecordObject { char file_type; unsigned int perm; @@ -182,46 +185,50 @@ struct RecordObject { uintmax_t fingerprint; }; -struct RecordObject *unpack(char *s) { +struct RecordObject *NewRecordObject() { + struct RecordObject *ret = calloc(1, sizeof(*ret)); + if (ret == NULL) + return NULL; + ret->path = NULL; + ret->target = NULL; + return ret; +} + +int Unpack(struct RecordObject *self, char *s) { char *fields[NFIELDS]; if (split_record(s, fields, '|') == -1) - return NULL; - - struct RecordObject *objp = calloc(1, sizeof(*objp)); - if (objp == NULL) { - return NULL; - } + return -1; field = NONE; - if (parse_file_type(fields[0], &objp->file_type) == -1) { + if (parse_file_type(fields[0], &self->file_type) == -1) { field = FILE_TYPE; - return objp; + return -1; } - if (parse_perm(fields[1], &objp->perm) == -1) { + if (parse_perm(fields[1], &self->perm) == -1) { field = PERMISSIONS; - return objp; + return -1; } - if (parse_uintmax(fields[2], &objp->uid) == -1) { + if (parse_uintmax(fields[2], &self->uid) == -1) { field = UID; - return objp; + return -1; } - if (parse_uintmax(fields[3], &objp->gid) == -1) { + if (parse_uintmax(fields[3], &self->gid) == -1) { field = GID; - return objp; + return -1; } - if (parse_intmax_nonnegative(fields[4], &objp->size) == -1) { + if (parse_intmax_nonnegative(fields[4], &self->size) == -1) { field = SIZE; - return objp; + return -1; } - if (parse_intmax_nonnegative(fields[5], &objp->time) == -1) { + if (parse_intmax_nonnegative(fields[5], &self->time) == -1) { field = TIME; - return objp; + return -1; } errno = 0; @@ -229,22 +236,21 @@ struct RecordObject *unpack(char *s) { if (target == NULL) { if (errno == EINVAL) { field = TARGET; - return objp; + return -1; } - release(objp); - return NULL; + return -1; } - objp->target = target; + self->target = target; - if (parse_uintmax(fields[7], &objp->fingerprint) == -1) { + if (parse_uintmax(fields[7], &self->fingerprint) == -1) { field = FINGERPRINT; - return objp; + return -1; } if (fields[8][0] == '\0') { field = PATH; - return objp; + return -1; } errno = 0; @@ -252,30 +258,91 @@ struct RecordObject *unpack(char *s) { if (path == NULL) { if (errno == EINVAL) { field = PATH; - return objp; + return -1; } - release(objp); - return NULL; + return -1; } - objp->path = path; + self->path = path; - return objp; -} - -int release(struct RecordObject *obj) { - if (obj == NULL) { - return 0; - } - if (obj->path != NULL) { - free(obj->path); - obj->path = NULL; - } - if (obj->target != NULL) { - free(obj->target); - obj->target = NULL; - } - - free(obj); return 0; } + +int Compare(struct RecordObject *self, struct RecordObject *other) { + field = NONE; + + if (self == NULL) + return 128; + if (other == NULL) + return 1; + + int exit_code = 0; + if (self->file_type != other->file_type) { + exit_code = ((int)(self->file_type - other->file_type)); + field = FILE_TYPE; + } else if (self->perm != other->perm) { + exit_code = ((int)(self->perm - other->perm)); + field = PERMISSIONS; + } else if (self->uid != other->uid) { + exit_code = ((int)(self->uid - other->uid)); + field = UID; + } else if (self->gid != other->gid) { + exit_code = ((int)(self->gid - other->gid)); + field = GID; + } else if (self->size != other->size) { + exit_code = ((int)(self->size - other->size)); + field = SIZE; + } else if (self->time != other->time) { + exit_code = ((int)(self->time - other->time)); + field = TIME; + } else if (self->fingerprint != other->fingerprint) { + exit_code = ((int)(self->fingerprint - other->fingerprint)); + field = FINGERPRINT; + } else { + int retp = strcmp(self->path, other->path); + if (retp != 0) { + exit_code = retp; + field = PATH; + } else { + int rett = strcmp(self->target, other->target); + if (rett != 0) { + exit_code = rett; + field = TARGET; + } + } + } + + return exit_code; +} + +int Release(struct RecordObject *self) { + if (self == NULL) { + return 0; + } + if (self->path != NULL) { + free(self->path); + self->path = NULL; + } + if (self->target != NULL) { + free(self->target); + self->target = NULL; + } + + free(self); + return 0; +} + +// Accessors +char GetFileType(const struct RecordObject *self) { return self->file_type; } +unsigned int GetPermissions(const struct RecordObject *self) { + return self->perm; +} +uintmax_t GetUid(const struct RecordObject *self) { return self->uid; } +uintmax_t GetGid(const struct RecordObject *self) { return self->gid; } +intmax_t GetSize(const struct RecordObject *self) { return self->size; } +intmax_t GetTime(const struct RecordObject *self) { return self->time; } +const char *GetPath(const struct RecordObject *self) { return self->path; } +const char *GetTarget(const struct RecordObject *self) { return self->target; } +uintmax_t GetFingerPrint(const struct RecordObject *self) { + return self->fingerprint; +} diff --git a/src/utility.c b/src/utility.c index dfdd1f1..31732e1 100644 --- a/src/utility.c +++ b/src/utility.c @@ -1,5 +1,6 @@ #define _XOPEN_SOURCE 700 #include "utility.h" +#include #include #include #include @@ -81,3 +82,31 @@ int copy(const char *src, const char *dst) { return rc; } + +int count_lines(const char *file) { + FILE *f = fopen(file, "r"); + if (f == NULL) { + return -1; + } + + size_t size = 0; + int count = 0; + char *buf = NULL; + while (getline(&buf, &size, f) != -1) + count++; + + if (ferror(f)) { + /* Capture before the cleanup: free and fclose may both touch errno. */ + const int saved_errno = errno; + free(buf); + fclose(f); + errno = saved_errno; + return -1; + } + + free(buf); + if (fclose(f) != 0) { + return -1; + } + return count; +}