Improve snapshot handling and CLI workflows

This commit is contained in:
2026-11-01 16:52:17 +01:00
parent c63530da34
commit 2a1051980b
23 changed files with 944 additions and 495 deletions

View File

@@ -34,6 +34,7 @@ SOURCES := \
src/stack.c \
src/utility.c \
src/types.c \
src/snapshot.c \
src/hash.c \
src/walk.c \
src/scan.c \
@@ -58,12 +59,33 @@ $(BUILD_DIR)/%.o: %.c
@mkdir -p $(dir $@)
$(CC) $(CPPFLAGS) $(CFLAGS) -c $< -o $@
# Fault injection is compile-time libc redirection, not LD_PRELOAD or a GNU
# linker extension, so the error-path tests stay usable with POSIX toolchains.
FAULT_OBJECTS := $(filter-out $(BUILD_DIR)/src/main.o $(BUILD_DIR)/src/create.o \
$(BUILD_DIR)/src/snapshot.o,$(OBJECTS)) \
$(BUILD_DIR)/tests/create.o $(BUILD_DIR)/tests/snapshot.o $(BUILD_DIR)/tests/faults.o
DEPENDENCIES += $(BUILD_DIR)/tests/create.d $(BUILD_DIR)/tests/snapshot.d \
$(BUILD_DIR)/tests/faults.d
$(BUILD_DIR)/tests/create.o: src/create.c
@mkdir -p $(dir $@)
$(CC) $(CPPFLAGS) $(CFLAGS) -Dfsync=test_fsync -Drename=test_rename \
-Dfclose=test_fclose -c $< -o $@
$(BUILD_DIR)/tests/snapshot.o: src/snapshot.c
@mkdir -p $(dir $@)
$(CC) $(CPPFLAGS) $(CFLAGS) -Dfstat=test_fstat -Dfclose=test_fclose -c $< -o $@
$(BUILD_DIR)/tests/faults: $(FAULT_OBJECTS)
$(CC) $(LDFLAGS) $(FAULT_OBJECTS) $(LDLIBS) -o $@
run: $(TARGET)
./$(TARGET)
# Black-box: the suite drives the built binary, so it needs nothing but sh.
test: $(TARGET)
test: $(TARGET) $(BUILD_DIR)/tests/faults
@FSNAP='$(CURDIR)/$(TARGET)' sh $(TESTS)
@$(BUILD_DIR)/tests/faults
# The same suite with every invocation under memcheck. -q keeps stderr clean,
# which matters because several tests compare it; a distinct exit code turns any
@@ -71,10 +93,11 @@ test: $(TARGET)
MEMCHECK := valgrind -q --error-exitcode=99 --leak-check=full \
--errors-for-leak-kinds=all --track-origins=yes
valgrind: $(TARGET)
valgrind: $(TARGET) $(BUILD_DIR)/tests/faults
@command -v valgrind >/dev/null 2>&1 || { \
echo 'valgrind is not installed' >&2; exit 2; }
@FSNAP='$(CURDIR)/$(TARGET)' VALGRIND='$(MEMCHECK)' sh $(TESTS)
@$(MEMCHECK) $(BUILD_DIR)/tests/faults
install: $(TARGET)
$(INSTALL) -d $(DESTDIR)$(BINDIR)

136
README.md
View File

@@ -41,13 +41,16 @@ make # produces build/fsnap
make clean
```
`make test` runs the suite in [tests/run.sh](tests/run.sh): 114 black-box checks
`make test` runs the suite in [tests/run.sh](tests/run.sh): 172 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, the `diff` classifications, and the `verify`
findings. It is POSIX sh with no dependencies, and skips rather than fails what
the environment cannot provide.
findings. It is POSIX sh with no mandatory runtime dependencies, and skips
rather than fails what the environment cannot provide. A further 14 C fault
injection checks exercise failed sync/close/rename, the `EXDEV` fallback, and
snapshots modified during reading. Both suites run under `make test` and
`make valgrind`.
`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
@@ -86,10 +89,10 @@ $ fsnap scan ~/projects/example
$ fsnap create ~/projects/example snapshot.fsnap
$ head -4 snapshot.fsnap
F|0644|1000|1000|182|1785598700||4022421711|/home/user/projects/example/README.md
D|0755|1000|1000|80|1785598700||0|/home/user/projects/example/src
F|0644|1000|1000|1319|1785598700||2184918239|/home/user/projects/example/src/main.c
L|0777|1000|1000|6|1785598700|main.c|0|/home/user/projects/example/symlink-test
FSNAP|1
F|0644|1000|1000|182|1785598700||4022421711|2049|123|1|/home/user/projects/example/README.md
D|0755|1000|1000|80|1785598700||0|2049|124|2|/home/user/projects/example/src
F|0644|1000|1000|1319|1785598700||2184918239|2049|125|1|/home/user/projects/example/src/main.c
$ fsnap list snapshot.fsnap # silence means every record parsed
$ fsnap list broken.fsnap
@@ -106,20 +109,30 @@ 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. `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`.
The program exits with `0` on complete success, `1` on failure, and `2` when
`scan` or `create` completes with skipped entries and warnings on stderr.
An unreadable root is a failure (`1`), not a successful empty snapshot.
`verify` exits `1` for reported differences, or `2` for an incomplete walk
when no differences were found. `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
One record per line, nine `|`-separated fields:
New snapshots start with `FSNAP|1`, followed by one record per line with
twelve `|`-separated fields:
```
type|permissions|uid|gid|size|time|target|fingerprint|path
FSNAP|1
type|permissions|uid|gid|size|time|target|fingerprint|device|inode|links|path
```
`list`, `diff`, and `verify` also accept the previous headerless nine-field
format (`type` through `fingerprint`, then `path`), including zero-byte legacy
snapshots. Unknown versions and mixed record layouts are rejected. Diagnostics
use physical line numbers, including the header. Legacy records have no
identity metadata: comparison uses those fields only when both records have it.
| Field | Description |
| --- | --- |
| `type` | `F` regular file, `D` directory, `L` symlink, `P` FIFO, `C` character device, `B` block device, `S` socket, `?` anything else |
@@ -129,17 +142,18 @@ type|permissions|uid|gid|size|time|target|fingerprint|path
| `time` | Modification time, seconds since the Unix epoch |
| `target` | Symlink target returned by `readlink`; empty for non-symlink entries |
| `fingerprint` | CRC32 of the contents for a regular file, and of the target string for a symlink, which is what the link holds. `0` for a directory and for the types that cannot be read at all (FIFO, socket, device) |
| `device` / `inode` | Decimal `st_dev` and `st_ino`; matching pairs identify hard links |
| `links` | Positive decimal `st_nlink`, the number of hard links |
| `path` | Absolute path: the input root is resolved with `realpath`, then child names are appended; it is escaped |
### Escaping rules
Only the `path` field is escaped by the writer:
Both `path` and symlink `target` are escaped by the writer:
- `\` is escaped to `\\`
- `|` is escaped to `\|`
- Newlines are escaped to `\n`
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.
The parser splits on unescaped delimiters and reconstructs both fields,
including literal backslashes and newlines in symlink targets.
### `diff` output
@@ -152,7 +166,7 @@ pathname:
| `D` | Present only in the old snapshot |
| `P` | Permissions are the first differing field |
| `L` | The symlink target changed. Checked before the fingerprint, which for a link is derived from the target, so the specific answer wins over the generic one |
| `M` | Any other difference, including type, owner, size, time, or fingerprint |
| `M` | Any other difference, including type, owner, size, time, fingerprint, device, inode, or link count |
`diff` reports a malformed input the way `list` does, as
`snapshot:line: invalid <field_name>` or `snapshot:line: unparsable line`, and
@@ -175,11 +189,13 @@ field that differs.
| `O` | Owner or group changed |
| `L` | Symlink target changed (checked before size and mtime, which change with it) |
| `M` | Modification time changed |
| `I` | Device or inode changed (versioned snapshots, non-symlink entries) |
| `H` | Hard-link count changed (versioned snapshots, non-symlink entries) |
| `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`.
`verify` exits `0` when the tree matches completely, `1` for differences or
malformed/unreadable input, and `2` for an incomplete walk without findings.
A malformed snapshot is reported with the same `snapshot:line:` diagnostic as `list` and `diff`.
## Behaviour worth knowing
@@ -198,9 +214,18 @@ with the same `snapshot:line:` diagnostic as `list` and `diff`.
such filter and lists everything.
- **Unreadable directories do not abort the run.** If `opendir` fails with
`EACCES`, a warning goes to stderr, the directory's own record is still
written, and the walk continues with the rest of the tree.
- **The snapshot is written to a temporary file under `/tmp` first**, then copied
to the destination. `TMPDIR` is ignored.
written, and the walk continues with the rest of the tree, returning `2`.
An unreadable regular file is omitted with a warning rather than a fabricated
fingerprint. An unreadable root always fails without publishing a snapshot.
- **Snapshots are published atomically.** By default the work file is created
in the destination directory, flushed, synced, closed, and renamed into place.
A nonempty `TMPDIR` selects the work directory instead. If `rename` returns
`EXDEV`, fsnap copies to another private temporary file beside the destination,
syncs and closes it, then renames it. The old destination is never truncated.
Invalid `TMPDIR` values fail rather than being ignored. Temporary files are
cleaned on normal success and error paths; a killed process may leave one.
New snapshot files have mode `0600`, including replacements; existing output
symlinks and non-regular destinations are rejected.
- **`list` stops at the first bad record.** It reports the offending line and
field to stderr and gives up, so it is not a full report of everything wrong
with a snapshot.
@@ -210,10 +235,13 @@ with the same `snapshot:line:` diagnostic as `list` and `diff`.
- **Numeric fields must be bare digits.** Per [SPEC.md](SPEC.md) §14 the parser
rejects out-of-range values (`ERANGE`), negative `uid`/`gid`, and any leading
whitespace or `+` sign, rather than letting `strtoumax` wrap them.
- **An empty snapshot is valid.** `create` produces a zero-byte file for an
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.
- **An empty snapshot is valid.** `create` writes just `FSNAP|1` for an empty
directory. Readers also accept a zero-byte legacy file. Both carry no
records, so `diff` reports every entry on the other side as added or deleted.
- **Readers use a single pass through EOF**, with a growing record array, not
a separate line-counting pass. A regular snapshot whose size or modification/
change timestamp changes during reading is rejected with a diagnostic;
trailing records cannot silently fall outside a pre-counted allocation.
- **`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.
@@ -224,53 +252,43 @@ with the same `snapshot:line:` diagnostic as `list` and `diff`.
- **`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.
- **For non-symlink entries every metadata field except the fingerprint is
compared**, including device, inode, link count, and a directory's size and
mtime. Adding or removing a child can therefore report its parent too.
Symlink verification compares type and target only.
## Known limitations
These are actual, reproduced problems, not hypotheticals:
- **Writing the output is not atomic.** The destination is truncated before the
copy starts, so a failure partway through (full disk, killed process) leaves a
truncated file where the previous snapshot used to be.
- **No exit code for a partial snapshot.** When directories are skipped because
they are unreadable, the run still exits `0`. If the top-level directory itself
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.
- **An unreadable regular file aborts the whole run.** `create` opens every
regular file to checksum it, and a failure there stops the walk and leaves no
snapshot, even though the same run tolerates a directory it cannot enter.
Running `fsnap create /etc` as an ordinary user fails on the first of the 39
files it may not read.
- **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`.
- `verify` does not recompute content fingerprints; changed bytes with the same
inode, size and mtime can go undetected.
- A walk is not a point-in-time filesystem snapshot. Concurrent tree changes
can cause inconsistent metadata or fail a command. The reader's timestamp
checks are change detection, not a locking or integrity guarantee.
- Atomic publication does not promise power-loss durability: the destination
directory is not synced after `rename`.
- Snapshot paths remain absolute and tied to their original location.
## Roadmap
Rough order of intent, no timeline:
- [ ] Write the snapshot atomically — create the temporary file in the
destination directory and `rename` it into place, falling back to a copy
only across filesystems (`EXDEV`).
- [x] Write the snapshot atomically — create the temporary file in the
destination directory and `rename` it into place. With `TMPDIR` across
filesystems (`EXDEV`), copy to a private sibling before the final rename.
- [x] Stop holding a directory handle per level: close each directory before
recursing, or walk iteratively with an explicit stack.
- [ ] Introduce a distinct exit status for "completed with warnings", the way
- [x] Introduce a distinct exit status for "completed with warnings", the way
`tar` and `rsync` do, and fail outright when the root directory cannot be
read.
- [ ] Add a version header to the format (e.g. `FSNAP|1`).
- [ ] 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.
- [x] Add a version header to the format (e.g. `FSNAP|1`).
- [x] Record inode, device ID, and link count so hard links can be identified.
- [x] Report a snapshot that grew between the counting pass and the parsing pass
instead of silently ignoring the extra records (single-pass reading plus
change detection replaces the old counting pass).
- [x] `fsnap verify <snapshot> <directory>` — 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`.
- [x] Honour `TMPDIR`; default to the destination directory for atomic rename.
## License

42
SPEC.md
View File

@@ -854,3 +854,45 @@ By the end of the project, the implementation should demonstrate practical under
The project should favor correctness, explicit error handling, and understanding of Unix behavior over minimizing the amount of code.
---
# 26. Implemented Snapshot Format (Version 1)
New snapshots start with the exact header `FSNAP|1`, followed by records:
```text
type|permissions|uid|gid|size|mtime|target|fingerprint|device|inode|links|path
```
`device`, `inode`, and `links` hold decimal `st_dev`, `st_ino`, and `st_nlink`
converted through `uintmax_t`. A link count must be positive. A matching
`(device, inode)` pair identifies names for the same filesystem object.
Both `target` and `path` use the escaping defined in section 16. The fingerprint
is CRC32 of regular-file bytes or of a symlink's unescaped target string, and
zero for other entry types. An empty versioned snapshot contains only the header.
Readers retain support for the legacy headerless nine-field format (the first
eight fields above followed by `path`), including a zero-byte file. Unknown
versions and mixed layouts must fail, with physical line numbers in diagnostics.
Identity fields are compared only when present in both records. `verify` reports
non-symlink identity changes with `I` and link-count changes with `H`.
Readers consume a single stream through EOF with dynamic record storage. They
must not silently accept only an initially counted prefix. Changes to a regular
snapshot's size, mtime, or ctime during reading fail with `EAGAIN` and a diagnostic.
This detects ordinary concurrent writes; it does not replace filesystem locking.
`create` publishes a fully flushed, synced, and closed temporary file with
`rename`. By default the temporary file is beside the destination. A nonempty
`TMPDIR` overrides the working directory. Only `EXDEV` allows a copy fallback:
copy into another private temporary file beside the destination, sync and close
it, then rename. Never truncate the published destination. Destination symlinks
and non-regular files are rejected; output files have mode `0600`. This provides
atomic publication, not a promise of power-loss durability for the directory.
Public exit status is `0` for complete success, `1` for failure, and `2` for
completion with skipped entries. Unreadable child directories and unreadable
regular files produce diagnostics and status `2`; unreadable file records are
omitted rather than assigned a fabricated checksum. An unreadable root fails
without publishing. `verify` returns `1` for findings, or `2` if its traversal
was incomplete and found no differences.

View File

@@ -2,7 +2,8 @@
#define CREATE_H
/* Create a snapshot of a directory tree.
Returns 0 on success, -1 on failure. */
Returns 0 on success, FSNAP_WARNINGS (2) if entries were skipped,
-1 on failure. */
int create(const char *directory, const char *output_file);
#endif

View File

@@ -2,7 +2,8 @@
#define SCAN_H
/* Recursively scan a directory, printing all entries.
Returns 0 on success, -1 on failure. */
Returns 0 on success, FSNAP_WARNINGS (2) if entries were skipped,
-1 on failure. */
int scan(const char *directory);
#endif

13
include/snapshot.h Normal file
View File

@@ -0,0 +1,13 @@
#ifndef SNAPSHOT_H
#define SNAPSHOT_H
#include "types.h"
#include "status.h"
/* Read every record in a single pass. Supports FSNAP|1 and legacy headerless
snapshots. On success ownership passes to the caller; on failure outputs
remain empty. A regular file changed during the read fails with EAGAIN. */
int snapshot_load(const char *file, struct RecordObject ***out, int *count);
void snapshot_release(struct RecordObject **records, int count);
#endif

View File

@@ -1,13 +1,8 @@
#ifndef STATUS_H
#define STATUS_H
/* Command return values.
0 is success and -1 a system error, with errno set. FSNAP_EPARSE says the
input itself was malformed, which is the snapshot's problem rather than the
system's: errno carries nothing useful and the command has already written a
snapshot:line: diagnostic to stderr. main maps every failure to
EXIT_FAILURE, so the distinction is internal for now. */
enum { FSNAP_EPARSE = 128 };
/* Public status 2 means the command completed with skipped entries. Parse
errors stay internal: main maps them to public failure (1). */
enum { FSNAP_WARNINGS = 2, FSNAP_EPARSE = 128 };
#endif

View File

@@ -14,6 +14,9 @@ enum Fields {
TARGET,
FINGERPRINT,
PATH,
DEVICE,
INODE,
LINKS,
NONE,
};
@@ -25,13 +28,15 @@ struct RecordObject;
with errno set to ENOMEM. */
struct RecordObject *RecordObjectNew(void);
/* Unpack a pipe-delimited record string into self.
/* Unpack a pipe-delimited record string into self. version is 0 for legacy
nine-field records or 1 for the twelve-field versioned format.
Returns 0 on success, -1 on failure. On failure errno is EINVAL when the
record is malformed and something else, ENOMEM in practice, when the
failure is the parser's own; only in the first case is *err meaningful.
If err is non-NULL and the offending field could be identified, sets *err
to that field. */
int RecordObjectUnpack(struct RecordObject *self, char *s, enum Fields *err);
int RecordObjectUnpack(struct RecordObject *self, char *s, enum Fields *err,
unsigned version);
/* Populate self by stat-ing the file at path and writing to out.
Returns the number of bytes written on success, -1 on failure. */
@@ -47,6 +52,10 @@ int RecordObjectCompare(const struct RecordObject *self,
const struct RecordObject *other, enum Fields *err);
/* Accessors */
unsigned RecordObjectVersion(const struct RecordObject *self);
uintmax_t RecordObjectDevice(const struct RecordObject *self);
uintmax_t RecordObjectInode(const struct RecordObject *self);
uintmax_t RecordObjectLinks(const struct RecordObject *self);
char RecordObjectFileType(const struct RecordObject *self);
unsigned int RecordObjectPermissions(const struct RecordObject *self);
uintmax_t RecordObjectUid(const struct RecordObject *self);

View File

@@ -13,8 +13,4 @@ char *resolve_path(const char *path);
Returns 0 on success, -1 on failure. */
int copy(const char *src, const char *dst);
/* Count lines in a file.
Returns the line count on success, -1 on failure. */
int count_lines(const char *file);
#endif

View File

@@ -5,7 +5,8 @@
/* 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. */
stdout, FSNAP_WARNINGS (2) if traversal was incomplete but no differences
were found, -1 on a system/IO error, and FSNAP_EPARSE on a malformed snapshot. */
int verify(const char *snapshot, const char *root_fs);
#endif

View File

@@ -1,11 +1,14 @@
#ifndef WALK_H
#define WALK_H
#include "status.h"
typedef int (*WalkOp)(const char *, void *);
/* Recursively walk a directory, calling op for each entry.
Returns 0 on success, -1 on failure. Silently skips directories
where access is denied. */
Returns 0 on success, FSNAP_WARNINGS when a callback warns or a child
directory is skipped with EACCES, -1 on failure. An unreadable root fails.
A callback returns 0, FSNAP_WARNINGS, or -1. */
int walk(const char *directory, WalkOp op, void *context);
#endif

View File

@@ -1,95 +1,181 @@
#include "create.h"
#include "status.h"
#include "types.h"
#include "utility.h"
#include "walk.h"
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/stat.h>
#include <unistd.h>
struct CreateContext {
FILE *stream;
const char *temporary;
const char *destination;
};
static int write_record(const char *path, void *context) {
/* skip snapshot files */
struct CreateContext *ctx = context;
const char *base = strrchr(path, '/');
base = base ? base + 1 : path;
size_t n = strlen(base);
if (n >= 6 && strcasecmp(base + n - 6, ".fsnap") == 0)
if ((n >= 6 && strcasecmp(base + n - 6, ".fsnap") == 0) ||
strcmp(path, ctx->temporary) == 0 || strcmp(path, ctx->destination) == 0)
return 0;
struct RecordObject *r = RecordObjectNew();
if (r == NULL)
return -1;
int ret = RecordObjectWrite(r, path, (FILE *)context);
int ret = RecordObjectWrite(r, path, ctx->stream);
const int err = errno;
RecordObjectRelease(r);
if (ret < 0 && err == EACCES) {
/* No bytes are emitted until all metadata and the checksum are ready. */
fprintf(stderr, "access denied: %s (entry skipped)\n", path);
return FSNAP_WARNINGS;
}
errno = err;
return ret < 0 ? -1 : 0;
}
int create(const char *directory, const char *output_file) {
if (directory == NULL || directory[0] == '\0') {
errno = EINVAL;
/* Create an absolute temporary name, so the walker can exclude it even when
TMPDIR is relative or reached through a symlink. Only successful mkstemp
names are owned by the caller and may be unlinked. */
static int temporary_file(const char *directory, char **name) {
char *resolved = resolve_path(directory);
if (resolved == NULL)
return -1;
char *path = strconcat(resolved, 1, "/snapshot_XXXXXX");
free(resolved);
if (path == NULL)
return -1;
int fd = mkstemp(path);
if (fd == -1) {
const int err = errno;
free(path);
errno = err;
} else {
*name = path;
}
if (output_file == NULL || output_file[0] == '\0') {
return fd;
}
int create(const char *directory, const char *output_file) {
if (directory == NULL || directory[0] == '\0' ||
output_file == NULL || output_file[0] == '\0') {
errno = EINVAL;
return -1;
}
int rc = -1;
char *resolved = NULL;
char template[] = "/tmp/snapshot_XXXXXX";
char *resolved = NULL, *parent = NULL, *destination = NULL;
char *temporary = NULL, *sibling = NULL, *output = NULL;
FILE *stream = NULL;
int fd = -1;
FILE *tmp = NULL;
resolved = resolve_path(directory);
if (resolved == NULL)
goto cleanup;
output = strdup(output_file);
if (output == NULL)
goto cleanup;
char *base = strrchr(output, '/');
if (base != NULL) {
*base++ = '\0';
parent = resolve_path(output[0] ? output : "/");
} else {
base = output;
parent = resolve_path(".");
}
if (parent == NULL)
goto cleanup;
if (*base == '\0') {
errno = EINVAL;
goto cleanup;
}
destination = strconcat(parent, 2, "/", base);
if (destination == NULL)
goto cleanup;
fd = mkstemp(template);
/* Never replace a device, directory, FIFO, or symlink with a snapshot. In
particular, do not follow a destination symlink and truncate its target. */
struct stat st;
if (lstat(destination, &st) == 0) {
if (!S_ISREG(st.st_mode)) {
errno = EINVAL;
goto cleanup;
}
} else if (errno != ENOENT) {
goto cleanup;
}
const char *tmpdir = getenv("TMPDIR");
fd = temporary_file(tmpdir != NULL && *tmpdir != '\0' ? tmpdir : parent,
&temporary);
if (fd == -1)
goto cleanup;
tmp = fdopen(fd, "w+");
if (tmp == NULL) {
close(fd);
stream = fdopen(fd, "w");
if (stream == NULL)
goto cleanup;
fd = -1; /* stream now owns the descriptor */
if (fputs("FSNAP|1\n", stream) == EOF)
goto cleanup;
struct CreateContext ctx = {stream, temporary, destination};
int status = walk(resolved, write_record, &ctx);
if (status == -1)
goto cleanup;
if (fflush(stream) == EOF || fsync(fileno(stream)) == -1)
goto cleanup;
int close_status = fclose(stream);
stream = NULL;
if (close_status != 0)
goto cleanup;
if (rename(temporary, destination) == -1) {
if (errno != EXDEV)
goto cleanup;
/* TMPDIR may be on another filesystem. Copy only to a private sibling,
never to the published destination; close and sync before rename. */
fd = temporary_file(parent, &sibling);
if (fd == -1)
goto cleanup;
if (copy(temporary, sibling) == -1 || fsync(fd) == -1)
goto cleanup;
close_status = close(fd);
fd = -1;
if (close_status == -1 || rename(sibling, destination) == -1)
goto cleanup;
free(sibling);
sibling = NULL;
if (unlink(temporary) == -1)
goto cleanup;
}
if (walk(resolved, write_record, (void *)tmp) == -1)
goto cleanup;
if (fflush(tmp) == EOF)
goto cleanup;
/* FIXME: It doesn't atomic copy, using rename */
if (copy(template, output_file) == -1)
goto cleanup;
rc = 0;
free(temporary);
temporary = NULL;
rc = status;
cleanup:;
/* An error that happened before the cleanup owns errno; one raised by the
cleanup itself owns it only when nothing had failed yet. A buffered write
can fail for the first time in fclose, so that errno must survive. */
const int saved_errno = errno;
int cleanup_errno = 0;
free(resolved);
/* Only mkstemp turns the XXXXXX suffix into a real name. If it failed,
template still holds the literal and unlink would target whatever file
happens to carry that name. */
if (stream != NULL)
fclose(stream);
if (fd != -1)
unlink(template);
if (tmp != NULL && fclose(tmp) != 0)
cleanup_errno = errno;
if (rc == -1) {
errno = saved_errno;
return -1;
}
if (cleanup_errno != 0) {
errno = cleanup_errno;
return -1;
}
return 0;
close(fd);
if (temporary != NULL)
unlink(temporary);
if (sibling != NULL)
unlink(sibling);
free(temporary);
free(sibling);
free(output);
free(destination);
free(parent);
free(resolved);
errno = saved_errno;
return rc;
}

View File

@@ -1,99 +1,11 @@
#include "diff.h"
#include "types.h"
#include "utility.h"
#include "snapshot.h"
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Returns 0 on success, -1 on a system error, FSNAP_EPARSE if malformed. */
static int load_in_memory(const char *file, struct RecordObject ***records,
int *count) {
int rc = -1;
FILE *stream = NULL;
char *buf = NULL;
if ((stream = fopen(file, "r")) == NULL)
goto cleanup;
*count = count_lines(file);
if (*count < 0)
goto cleanup;
/* An empty snapshot is a valid one: create() produces it for an empty
directory and list() accepts it. It simply carries no records, so every
record in the other snapshot is an addition or a deletion. calloc(0, ..)
may legitimately return NULL, hence the early return. */
if (*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 (getline(&buf, &size, stream) != -1 && i < *count) {
struct RecordObject *objp = RecordObjectNew();
if (objp == NULL) {
errno = ENOMEM;
goto cleanup;
}
enum Fields err = NONE;
errno = 0;
int ret = RecordObjectUnpack(objp, buf, &err);
if (ret == -1) {
/* A failed allocation inside the parser is not a malformed record and
must not be reported as one; errno tells them apart. */
if (errno != EINVAL) {
RecordObjectRelease(objp);
goto cleanup;
}
/* Same diagnostic shape as list(): identify the snapshot, the line and
the offending field. A malformed record is not a system error, so it
gets its own status and main() leaves errno alone. */
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(objp);
rc = FSNAP_EPARSE;
goto cleanup;
}
(*records)[i] = objp;
i++;
}
if (ferror(stream))
goto cleanup;
rc = 0;
cleanup:;
const int saved_errno = errno;
if (stream != NULL)
fclose(stream);
free(buf);
errno = saved_errno;
return rc;
}
static void dealloc(struct RecordObject **records, int size) {
for (int j = 0; j < size; j++) {
RecordObjectRelease(records[j]);
records[j] = NULL;
}
free(records);
}
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;
@@ -105,12 +17,11 @@ int diff(const char *file1, const char *file2) {
struct RecordObject **records1 = NULL;
struct RecordObject **records2 = NULL;
int len1 = 0;
if ((rc = load_in_memory(file1, &records1, &len1)) != 0)
int len1 = 0, len2 = 0;
if ((rc = snapshot_load(file1, &records1, &len1)) != 0)
goto cleanup;
int len2 = 0;
if ((rc = load_in_memory(file2, &records2, &len2)) != 0)
if ((rc = snapshot_load(file2, &records2, &len2)) != 0)
goto cleanup;
if (records1 != NULL)
@@ -183,10 +94,12 @@ int diff(const char *file1, const char *file2) {
rc = 0;
cleanup:
cleanup:;
const int saved_errno = errno;
if (records1 != NULL)
dealloc(records1, len1);
snapshot_release(records1, len1);
if (records2 != NULL)
dealloc(records2, len2);
snapshot_release(records2, len2);
errno = saved_errno;
return rc;
}

View File

@@ -1,96 +1,14 @@
#include "list.h"
#include "types.h"
#include "utility.h"
#include "snapshot.h"
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
int list(const char *snapshot) {
FILE *snapshot_file = fopen(snapshot, "r");
if (snapshot_file == NULL) {
return -1;
}
int rc = 0;
struct RecordObject **records = NULL;
char *buf = NULL;
const int arr_size = count_lines(snapshot);
if (arr_size == 0) {
goto out;
} else if (arr_size < 0) {
rc = -1;
goto out;
}
int i = 0;
size_t size = 0;
records = calloc((size_t)arr_size, sizeof(*records));
if (records == NULL) {
errno = ENOMEM;
rc = -1;
goto out;
}
while (getline(&buf, &size, snapshot_file) != -1 && i < arr_size) {
struct RecordObject *objp = RecordObjectNew();
if (objp == NULL) {
rc = -1;
goto out;
}
enum Fields err = NONE;
errno = 0;
int ret = RecordObjectUnpack(objp, buf, &err);
if (ret == -1) {
/* A failed allocation inside the parser is not a malformed record and
must not be reported as one; errno tells them apart. */
if (errno != EINVAL) {
rc = -1;
RecordObjectRelease(objp);
goto out;
}
if (err != NONE)
fprintf(stderr, "%s:%d: invalid %s\n", snapshot, i + 1,
RecordObjectFieldName(err));
else
fprintf(stderr, "%s:%d: unparsable line\n", snapshot, i + 1);
rc = FSNAP_EPARSE;
RecordObjectRelease(objp);
break;
}
records[i] = objp;
i++;
}
if (ferror(snapshot_file)) {
rc = -1;
goto out;
}
out:;
/* An error that happened before the cleanup owns errno; one raised by the
cleanup itself owns it only when nothing had failed yet. */
int count = 0;
int rc = snapshot_load(snapshot, &records, &count);
const int saved_errno = errno;
int cleanup_errno = 0;
if (snapshot_file != NULL && fclose(snapshot_file) != 0)
cleanup_errno = errno;
free(buf);
if (records != NULL) {
for (int j = 0; j < arr_size; j++) {
RecordObjectRelease(records[j]);
records[j] = NULL;
}
free(records);
records = NULL;
}
if (rc == 0 && cleanup_errno != 0) {
errno = cleanup_errno;
return -1;
}
if (rc == -1)
errno = saved_errno;
snapshot_release(records, count);
errno = saved_errno;
return rc;
}

View File

@@ -21,11 +21,14 @@ int main(int argc, char *argv[]) {
return EXIT_FAILURE;
}
const char *directory = argv[2];
if (scan(directory) == -1) {
int ret = scan(directory);
if (ret == -1) {
const int err = errno;
fprintf(stderr, "scan failed: %s\n", strerror(err));
return EXIT_FAILURE;
}
if (ret == FSNAP_WARNINGS)
return FSNAP_WARNINGS;
} else if (strcmp(cmd, "create") == 0) {
if (argc < 4) {
fprintf(stderr,
@@ -35,11 +38,14 @@ int main(int argc, char *argv[]) {
}
const char *directory = argv[2];
const char *output_file = argv[3];
if (create(directory, output_file) == -1) {
int ret = create(directory, output_file);
if (ret == -1) {
const int err = errno;
fprintf(stderr, "create failed: %s\n", strerror(err));
return EXIT_FAILURE;
}
if (ret == FSNAP_WARNINGS)
return FSNAP_WARNINGS;
} else if (strcmp(cmd, "list") == 0) {
if (argc < 3) {
fprintf(stderr, "%s: command %s expected param [snapshot_file]\n",
@@ -87,6 +93,8 @@ int main(int argc, char *argv[]) {
const int err = errno;
fprintf(stderr, "verify failed: %s\n", strerror(err));
return EXIT_FAILURE;
} else if (ret == FSNAP_WARNINGS) {
return FSNAP_WARNINGS;
} else if (ret > 0) {
return EXIT_FAILURE;
}

View File

@@ -21,7 +21,8 @@ int scan(const char *directory) {
if (dir == NULL)
return -1;
if (walk(dir, print_file, NULL) == -1) {
int status = walk(dir, print_file, NULL);
if (status == -1) {
const int saved_errno = errno;
free(dir);
errno = saved_errno;
@@ -33,5 +34,5 @@ int scan(const char *directory) {
only here. */
if (fflush(stdout) == EOF)
return -1;
return 0;
return status;
}

118
src/snapshot.c Normal file
View File

@@ -0,0 +1,118 @@
#include "snapshot.h"
#include <errno.h>
#include <limits.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
void snapshot_release(struct RecordObject **records, int count) {
for (int i = 0; i < count; i++)
RecordObjectRelease(records[i]);
free(records);
}
int snapshot_load(const char *file, struct RecordObject ***out, int *out_count) {
*out = NULL;
*out_count = 0;
FILE *stream = fopen(file, "r");
if (stream == NULL)
return -1;
int rc = -1, count = 0;
size_t capacity = 0, size = 0, line = 0;
unsigned version = 0;
char *buf = NULL;
struct RecordObject **records = NULL;
struct stat before, after;
if (fstat(fileno(stream), &before) == -1)
goto cleanup;
ssize_t length;
while ((length = getline(&buf, &size, stream)) != -1) {
line++;
if (memchr(buf, '\0', (size_t)length) != NULL) {
fprintf(stderr, "%s:%zu: embedded NUL byte\n", file, line);
rc = FSNAP_EPARSE;
goto cleanup;
}
if (line == 1 && strncmp(buf, "FSNAP|", 6) == 0) {
if (strcmp(buf, "FSNAP|1\n") != 0 && strcmp(buf, "FSNAP|1") != 0) {
fprintf(stderr, "%s:1: unsupported snapshot version\n", file);
rc = FSNAP_EPARSE;
goto cleanup;
}
version = 1;
continue;
}
if ((size_t)count == capacity) {
size_t next = capacity == 0 ? 64 : capacity * 2;
if (next > INT_MAX)
next = INT_MAX;
if (next <= capacity || next > SIZE_MAX / sizeof(*records)) {
errno = EOVERFLOW;
goto cleanup;
}
struct RecordObject **grown = realloc(records, next * sizeof(*records));
if (grown == NULL)
goto cleanup;
records = grown;
capacity = next;
}
struct RecordObject *record = RecordObjectNew();
if (record == NULL)
goto cleanup;
enum Fields field = NONE;
if (RecordObjectUnpack(record, buf, &field, version) == -1) {
const int err = errno;
RecordObjectRelease(record);
if (err == EINVAL) {
if (field != NONE)
fprintf(stderr, "%s:%zu: invalid %s\n", file, line,
RecordObjectFieldName(field));
else
fprintf(stderr, "%s:%zu: unparsable line\n", file, line);
rc = FSNAP_EPARSE;
}
errno = err;
goto cleanup;
}
records[count++] = record;
}
if (ferror(stream) || !feof(stream))
goto cleanup;
if (fstat(fileno(stream), &after) == -1)
goto cleanup;
if (S_ISREG(before.st_mode) &&
(before.st_size != after.st_size ||
before.st_mtim.tv_sec != after.st_mtim.tv_sec ||
before.st_mtim.tv_nsec != after.st_mtim.tv_nsec ||
before.st_ctim.tv_sec != after.st_ctim.tv_sec ||
before.st_ctim.tv_nsec != after.st_ctim.tv_nsec)) {
fprintf(stderr, "%s: snapshot changed while reading\n", file);
errno = EAGAIN;
goto cleanup;
}
rc = 0;
cleanup:;
const int saved_errno = errno;
if (fclose(stream) != 0 && rc == 0) {
rc = -1;
} else {
errno = saved_errno;
}
free(buf);
if (rc == 0) {
*out = records;
*out_count = count;
} else {
const int err = errno;
snapshot_release(records, count);
errno = err;
}
return rc;
}

View File

@@ -9,11 +9,12 @@
#include <sys/stat.h>
#include <unistd.h>
#define NFIELDS 9
#define NFIELDS 12
static const char *field_names[] = {
"file type", "permissions", "uid", "gid", "size",
"time", "target", "fingerprint", "path", "none"};
"time", "target", "fingerprint", "path", "device",
"inode", "link count", "none"};
const char *RecordObjectFieldName(enum Fields f) {
/* The underlying type of an enum is the compiler's choice, so guard the
@@ -23,27 +24,24 @@ const char *RecordObjectFieldName(enum Fields f) {
/*======================= static functions ===================================*/
static int split_record(char *line, char *fields[NFIELDS], char delim) {
static int split_record(char *line, char *fields[NFIELDS], size_t count) {
char *p = line;
line[strcspn(line, "\n")] = '\0';
for (size_t n = 0; n < NFIELDS - 1; n++) {
for (size_t n = 0; n < count; n++) {
fields[n] = p;
char *sep = strchr(p, delim);
if (sep == NULL)
/* Skip escaped delimiters in both target and path. Invalid escapes are
diagnosed later by the field's unescaper. */
while (*p != '\0' && *p != '|') {
if (*p == '\\' && p[1] != '\0')
p++;
p++;
}
if (n == count - 1)
return *p == '\0' ? 0 : -1;
if (*p == '\0')
return -1;
*sep = '\0';
p = sep + 1;
*p++ = '\0';
}
/* Only the path may contain an escaped delimiter, and it is the last field,
so the separators found above are always the real ones. Validating
what is left is the unescaper's job. */
fields[NFIELDS - 1] = p;
return 0;
}
@@ -259,6 +257,8 @@ struct RecordObject {
char *path;
char *target; /* only for symlink */
uintmax_t fingerprint;
uintmax_t device, inode, links;
unsigned version;
};
struct RecordObject *RecordObjectNew(void) {
@@ -283,9 +283,11 @@ static int malformed(enum Fields *err, enum Fields field) {
return -1;
}
int RecordObjectUnpack(struct RecordObject *self, char *s, enum Fields *err) {
int RecordObjectUnpack(struct RecordObject *self, char *s, enum Fields *err,
unsigned version) {
char *fields[NFIELDS];
if (split_record(s, fields, '|') == -1) {
self->version = version;
if (split_record(s, fields, version == 1 ? 12 : 9) == -1) {
errno = EINVAL;
return -1;
}
@@ -322,11 +324,20 @@ int RecordObjectUnpack(struct RecordObject *self, char *s, enum Fields *err) {
if (parse_uintmax(fields[7], &self->fingerprint) == -1)
return malformed(err, FINGERPRINT);
if (fields[8][0] == '\0')
if (version == 1) {
if (parse_uintmax(fields[8], &self->device) == -1)
return malformed(err, DEVICE);
if (parse_uintmax(fields[9], &self->inode) == -1)
return malformed(err, INODE);
if (parse_uintmax(fields[10], &self->links) == -1 || self->links == 0)
return malformed(err, LINKS);
}
const size_t path_field = version == 1 ? 11 : 8;
if (fields[path_field][0] == '\0')
return malformed(err, PATH);
errno = 0;
char *path = unescape_path(fields[8], '|');
char *path = unescape_path(fields[path_field], '|');
if (path == NULL) {
if (errno == EINVAL)
return malformed(err, PATH);
@@ -386,6 +397,18 @@ int RecordObjectCompare(const struct RecordObject *self,
exit_code = cmp_uintmax(self->fingerprint, other->fingerprint);
if (err)
*err = FINGERPRINT;
} else if (self->version && other->version && self->device != other->device) {
exit_code = cmp_uintmax(self->device, other->device);
if (err)
*err = DEVICE;
} else if (self->version && other->version && self->inode != other->inode) {
exit_code = cmp_uintmax(self->inode, other->inode);
if (err)
*err = INODE;
} else if (self->version && other->version && self->links != other->links) {
exit_code = cmp_uintmax(self->links, other->links);
if (err)
*err = LINKS;
} else {
int retp = strcmp(or_empty(self->path), or_empty(other->path));
if (retp != 0) {
@@ -414,6 +437,10 @@ int RecordObjectWrite(struct RecordObject *self, const char *path, FILE *out) {
self->gid = (uintmax_t)st.st_gid;
self->size = (intmax_t)st.st_size;
self->time = (intmax_t)st.st_mtime;
self->device = (uintmax_t)st.st_dev;
self->inode = (uintmax_t)st.st_ino;
self->links = (uintmax_t)st.st_nlink;
self->version = 1;
s = sanitize_path(path);
if (s == NULL)
goto cleanup;
@@ -481,16 +508,22 @@ int RecordObjectWrite(struct RecordObject *self, const char *path, FILE *out) {
}
self->fingerprint = hash;
rc = fprintf(out, "%c|%04o|%ju|%ju|%jd|%jd|%s|%ju|%s\n", self->file_type,
s = sanitize_path(or_empty(self->target));
if (s == NULL)
goto cleanup;
rc = fprintf(out, "%c|%04o|%ju|%ju|%jd|%jd|%s|%ju|%ju|%ju|%ju|%s\n", self->file_type,
self->perm, self->uid, self->gid, self->size, self->time,
self->target == NULL ? "" : self->target, self->fingerprint,
s, self->fingerprint, self->device, self->inode, self->links,
self->path);
cleanup:
cleanup:;
const int saved_errno = errno;
free(s);
free(target);
if (f != NULL)
fclose(f);
errno = saved_errno;
return rc;
}
@@ -522,3 +555,16 @@ const char *RecordObjectTarget(const struct RecordObject *self) {
uintmax_t RecordObjectFingerPrint(const struct RecordObject *self) {
return self->fingerprint;
}
unsigned RecordObjectVersion(const struct RecordObject *self) {
return self->version;
}
uintmax_t RecordObjectDevice(const struct RecordObject *self) {
return self->device;
}
uintmax_t RecordObjectInode(const struct RecordObject *self) {
return self->inode;
}
uintmax_t RecordObjectLinks(const struct RecordObject *self) {
return self->links;
}

View File

@@ -94,29 +94,3 @@ cleanup:;
}
return 0;
}
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)) {
const int saved_errno = errno;
free(buf);
fclose(f);
errno = saved_errno;
return -1;
}
free(buf);
if (fclose(f) != 0)
return -1;
return count;
}

View File

@@ -1,5 +1,6 @@
#include "verify.h"
#include "status.h"
#include "snapshot.h"
#include "types.h"
#include "utility.h"
#include "walk.h"
@@ -228,105 +229,17 @@ static int verify_record(const struct RecordObject *record, int *differences) {
if ((intmax_t)st.st_mtime != RecordObjectTime(record))
return report('M', path, differences);
if (RecordObjectVersion(record)) {
if ((uintmax_t)st.st_dev != RecordObjectDevice(record) ||
(uintmax_t)st.st_ino != RecordObjectInode(record))
return report('I', path, differences);
if ((uintmax_t)st.st_nlink != RecordObjectLinks(record))
return report('H', 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') {
@@ -344,7 +257,7 @@ int verify(const char *snapshot, const char *root_fs) {
if (resolved == NULL)
goto cleanup;
rc = load_snapshot(snapshot, &records, &count);
rc = snapshot_load(snapshot, &records, &count);
if (rc != 0)
goto cleanup;
@@ -352,7 +265,8 @@ int verify(const char *snapshot, const char *root_fs) {
qsort(records, (size_t)count, sizeof(records[0]), order_by_path);
struct VerifyContext ctx = {records, count, differences};
if (walk(resolved, mark_new, &ctx) == -1) {
int walk_status = walk(resolved, mark_new, &ctx);
if (walk_status == -1) {
rc = -1;
goto cleanup;
}
@@ -372,11 +286,11 @@ int verify(const char *snapshot, const char *root_fs) {
goto cleanup;
}
rc = differences ? 1 : 0;
rc = differences ? 1 : walk_status;
cleanup:;
const int saved_errno = errno;
release_records(records, count);
snapshot_release(records, count);
free(resolved);
if (rc == -1)
errno = saved_errno;

View File

@@ -35,19 +35,16 @@ static int is_directory(const char *path, unsigned char type) {
int walk(const char *directory, WalkOp op, void *context) {
char *base = NULL;
DIR *dirp = NULL;
int status = 0;
struct Stack *stack = StackNew();
if (stack == NULL)
goto failed;
DIR *dirp = opendir(directory);
if (dirp == NULL) {
if (errno == EACCES) {
fprintf(stderr, "access denied: %s\n", directory);
goto success;
}
dirp = opendir(directory);
if (dirp == NULL)
goto failed;
}
/* The stack owns the char *paths of the subdirectories still to inspect.
At most one DIR is open at a time, so a deep tree cannot exhaust the
@@ -55,9 +52,12 @@ int walk(const char *directory, WalkOp op, void *context) {
read; NULL means the root was passed directly, so its storage is not
owned. */
for (;;) {
errno = 0;
struct dirent *direntp;
while ((direntp = readdir(dirp)) != NULL) {
for (;;) {
errno = 0;
direntp = readdir(dirp);
if (direntp == NULL)
break;
if (ignore_file(direntp->d_name))
continue;
@@ -72,18 +72,22 @@ int walk(const char *directory, WalkOp op, void *context) {
goto failed;
}
int ret = op(path, context);
if (ret == -1) {
free(path);
goto failed;
}
if (ret == FSNAP_WARNINGS)
status = FSNAP_WARNINGS;
if (type == 1) {
/* Report the directory itself, then keep it pending for descent.
The stack now owns path; do not free it here. */
if (op(path, context) == -1 || StackPush(stack, path) == -1) {
if (StackPush(stack, path) == -1) {
free(path);
goto failed;
}
} else {
if (op(path, context) == -1) {
free(path);
goto failed;
}
free(path);
}
}
@@ -91,9 +95,10 @@ int walk(const char *directory, WalkOp op, void *context) {
if (errno != 0)
goto failed;
if (closedir(dirp) == -1)
goto failed;
int close_status = closedir(dirp);
dirp = NULL;
if (close_status == -1)
goto failed;
free(base);
base = NULL;
@@ -112,6 +117,7 @@ int walk(const char *directory, WalkOp op, void *context) {
goto failed;
}
fprintf(stderr, "access denied: %s\n", base);
status = FSNAP_WARNINGS;
free(base);
base = NULL;
}
@@ -126,7 +132,7 @@ success:;
}
if (stack != NULL)
StackRelease(stack);
return 0;
return status;
failed:;
const int saved_errno = errno;

204
tests/faults.c Normal file
View File

@@ -0,0 +1,204 @@
/* Compile create.c and snapshot.c with selected libc names redirected here.
No preload, linker extensions, privileges, or second filesystem required. */
#include "create.h"
#include "diff.h"
#include "list.h"
#include "snapshot.h"
#include "verify.h"
#include <dirent.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
int test_fsync(int fd);
int test_rename(const char *from, const char *to);
int test_fclose(FILE *stream);
int test_fstat(int fd, struct stat *st);
enum Fault { NO_FAULT, SYNC, CLOSE, RENAME, EXDEV_OK, EXDEV_SYNC,
EXDEV_RENAME, GROW, SHRINK, STAT };
static enum Fault fault;
static int syncs, renames, closes, stats, failed, testno;
static const char *input = "input.fsnap";
static void reset(enum Fault value) {
fault = value;
syncs = renames = closes = stats = 0;
}
static void check(int condition, const char *description) {
printf("%s %d - %s\n", condition ? "ok" : "not ok", ++testno, description);
if (!condition)
failed++;
}
int test_fsync(int fd) {
syncs++;
if ((fault == SYNC && syncs == 1) || (fault == EXDEV_SYNC && syncs == 2)) {
errno = ENOSPC;
return -1;
}
return fsync(fd);
}
int test_rename(const char *from, const char *to) {
renames++;
if ((fault == EXDEV_OK || fault == EXDEV_SYNC || fault == EXDEV_RENAME) &&
renames == 1) {
errno = EXDEV;
return -1;
}
if (fault == RENAME || (fault == EXDEV_RENAME && renames == 2)) {
errno = EACCES;
return -1;
}
return rename(from, to);
}
int test_fclose(FILE *stream) {
closes++;
int rc = fclose(stream);
if (fault == CLOSE && closes == 1) {
errno = EIO;
return EOF;
}
return rc;
}
int test_fstat(int fd, struct stat *st) {
stats++;
if (fault == STAT) {
errno = EIO;
return -1;
}
if (stats == 2 && fault == GROW) {
FILE *out = fopen(input, "a");
if (out == NULL)
return -1;
if (fputs("X|bad\n", out) == EOF || fclose(out) != 0)
return -1;
}
if (stats == 2 && fault == SHRINK && truncate(input, 0) == -1)
return -1;
return fstat(fd, st);
}
static void write_file(const char *path, const char *text) {
FILE *stream = fopen(path, "w");
if (stream == NULL || fputs(text, stream) == EOF || fclose(stream) != 0) {
perror(path);
exit(2);
}
}
static int old_output(void) {
char buf[64];
FILE *stream = fopen("output.fsnap", "r");
if (stream == NULL)
return 0;
int same = fgets(buf, sizeof(buf), stream) != NULL && strcmp(buf, "old\n") == 0;
fclose(stream);
return same;
}
static int no_temporaries(void) {
DIR *dir = opendir(".");
if (dir == NULL)
return 0;
struct dirent *entry;
int clean = 1;
while ((entry = readdir(dir)) != NULL)
if (strncmp(entry->d_name, "snapshot_", 9) == 0)
clean = 0;
closedir(dir);
return clean;
}
int main(void) {
const char *tmpdir = getenv("TMPDIR");
if (tmpdir == NULL || *tmpdir == '\0')
tmpdir = "/tmp";
size_t size = strlen(tmpdir) + sizeof("/fsnap-faults.XXXXXX");
char *work = malloc(size);
if (work == NULL)
return 2;
snprintf(work, size, "%s/fsnap-faults.XXXXXX", tmpdir);
if (mkdtemp(work) == NULL) {
perror("fault test directory");
free(work);
return 2;
}
char *absolute = realpath(work, NULL);
free(work);
work = absolute;
if (work == NULL || chdir(work) == -1 || mkdir("tree", 0700) == -1) {
perror("fault test fixture");
free(work);
return 2;
}
/* Keep all scratch data in the fixture, regardless of the runner's TMPDIR. */
if (setenv("TMPDIR", ".", 1) == -1)
return 2;
write_file("tree/file", "contents\n");
const enum Fault create_faults[] = {SYNC, CLOSE, RENAME, EXDEV_SYNC, EXDEV_RENAME};
const char *names[] = {"flush/sync failure preserves old output",
"close failure preserves old output",
"rename failure preserves old output",
"cross-device copy sync failure preserves old output",
"cross-device final rename failure preserves old output"};
for (size_t i = 0; i < sizeof(create_faults) / sizeof(create_faults[0]); i++) {
write_file("output.fsnap", "old\n");
reset(create_faults[i]);
int rc = create("tree", "output.fsnap");
int err = errno;
reset(NO_FAULT);
check(rc == -1 && err != 0 && old_output() && no_temporaries(), names[i]);
}
reset(EXDEV_OK);
int rc = create("tree", "output.fsnap");
check(rc == 0 && renames == 2 && syncs == 2 && no_temporaries(),
"EXDEV copies to a sibling and atomically renames it");
reset(NO_FAULT);
check(list("output.fsnap") == 0, "cross-device result is a valid snapshot");
for (int command = 0; command < 4; command++) {
write_file(input, "F|0644|0|0|0|1||0|/f\n");
reset(GROW);
struct RecordObject **records = NULL;
int count = 0;
switch (command) {
case 0: rc = snapshot_load(input, &records, &count); break;
case 1: rc = list(input); break;
case 2: rc = diff(input, "output.fsnap"); break;
default: rc = verify(input, "tree"); break;
}
check(rc == -1 && errno == EAGAIN && records == NULL && count == 0,
"reader rejects growth after parsing rather than accepting a prefix");
}
const enum Fault read_faults[] = {SHRINK, CLOSE, STAT};
for (size_t i = 0; i < sizeof(read_faults) / sizeof(read_faults[0]); i++) {
write_file(input, "F|0644|0|0|0|1||0|/f\n");
reset(read_faults[i]);
struct RecordObject **records = NULL;
int count = 0;
rc = snapshot_load(input, &records, &count);
check(rc == -1 && errno != 0 && records == NULL && count == 0,
"reader cleans up on shrink, close error, or stat error");
}
reset(NO_FAULT);
unlink(input);
unlink("output.fsnap");
unlink("tree/file");
rmdir("tree");
if (chdir("/") == -1 || rmdir(work) == -1) {
perror("fault test cleanup");
failed++;
}
free(work);
printf("1..%d\n# %d fault tests passed, %d failed\n", testno, testno - failed, failed);
return failed ? 1 : 0;
}

View File

@@ -171,7 +171,7 @@ if [ "$(id -u)" = "0" ]; then
skip "unreadable directory is reported on stderr (running as root)"
else
out=$(fsnap scan noperm 2>err.txt)
is "unreadable directory does not abort the walk" "$?" "0"
is "unreadable directory returns warning status" "$?" "2"
contains "unreadable directory is reported on stderr" "$(cat err.txt)" "access denied"
fi
chmod 755 noperm/locked
@@ -184,11 +184,11 @@ is "create succeeds over a tree with every entry type" "$?" "0"
is "create over a mixed tree is silent" "$(cat err.txt)" ""
is "create writes one record per entry" \
"$(wc -l <snap.fsnap | tr -d ' ')" \
"$(($(wc -l <snap.fsnap) - 1))" \
"$(count_entries tree)"
field() { # field <path-suffix> <n>
awk -F'|' -v s="$1" -v n="$2" 'substr($9, length($9) - length(s) + 1) == s { print $n }' snap.fsnap
awk -F'|' -v s="$1" -v n="$2" 'substr($12, length($12) - length(s) + 1) == s { print $n }' snap.fsnap
}
is "regular file is recorded as F" "$(field /tree/file.txt 1)" "F"
@@ -224,7 +224,7 @@ if [ -p tree/pipe ]; then
is "FIFO keeps fingerprint 0 rather than blocking" "$(field /tree/pipe 8)" "0"
fi
is "paths are absolute" "$(field /tree/file.txt 9 | cut -c1)" "/"
is "paths are absolute" "$(field /tree/file.txt 12 | cut -c1)" "/"
# Regressions: each of these used to abort create or hang it.
for kind in link-to-dir broken-link pipe; do
@@ -239,8 +239,8 @@ done
fsnap create empty-tree empty.fsnap
is "create of an empty directory succeeds" "$?" "0"
is "create of an empty directory writes an empty snapshot" \
"$(wc -c <empty.fsnap | tr -d ' ')" "0"
is "create of an empty directory writes only the version header" \
"$(cat empty.fsnap)" "FSNAP|1"
# Snapshots living inside the tree are skipped so they do not end up in
# their own successor.
@@ -254,7 +254,7 @@ is "create fails on a missing source" "$?" "1"
fsnap create tree "" >/dev/null 2>&1
is "create rejects an empty destination" "$?" "1"
# create writes a temporary file and copies it into place; nothing may be
# create writes a temporary file and renames it into place; nothing may be
# left behind either way.
count_temps() {
find "${TMPDIR:-/tmp}" -maxdepth 1 -name 'snapshot_*' 2>/dev/null |
@@ -300,7 +300,7 @@ mkdir -p odd
fsnap create odd odd.fsnap 2>/dev/null
is "create handles unusual filenames" "$?" "0"
is "one record per unusual name" \
"$(wc -l <odd.fsnap | tr -d ' ')" \
"$(($(wc -l <odd.fsnap) - 1))" \
"$(count_entries odd)"
fsnap list odd.fsnap >/dev/null 2>&1
is "unusual filenames survive a create/list round trip" "$?" "0"
@@ -369,10 +369,10 @@ is "diff of a snapshot against itself is silent" "$out" ""
is "diff reports every record of an empty-to-full comparison as added" \
"$(fsnap diff empty.fsnap snap.fsnap | grep -c '^A ')" \
"$(wc -l <snap.fsnap | tr -d ' ')"
"$(($(wc -l <snap.fsnap) - 1))"
is "diff reports every record of a full-to-empty comparison as deleted" \
"$(fsnap diff snap.fsnap empty.fsnap | grep -c '^D ')" \
"$(wc -l <snap.fsnap | tr -d ' ')"
"$(($(wc -l <snap.fsnap) - 1))"
out=$(fsnap diff empty.fsnap empty.fsnap 2>&1)
is "diff of two empty snapshots succeeds" "$?" "0"
@@ -418,7 +418,7 @@ is "a fingerprint difference of exactly 2^32 is not lost" \
# diff sorts by path, so readdir order must not leak into the result.
fsnap diff snap.fsnap snap.fsnap >/dev/null 2>&1
is "diff is insensitive to record order" "$?" "0"
sort -r snap.fsnap >reversed.fsnap
{ head -n 1 snap.fsnap; tail -n +2 snap.fsnap | sort -r; } >reversed.fsnap
out=$(fsnap diff snap.fsnap reversed.fsnap 2>&1)
is "diff of a reordered snapshot reports no changes" "$out" ""
@@ -556,6 +556,165 @@ before=$(cksum <stale.fsnap)
fsnap create /nonexistent-directory stale.fsnap >/dev/null 2>&1
is "a failed create leaves the destination untouched" "$(cksum <stale.fsnap)" "$before"
# --------------------------------------------------------------------------
# Checklist regressions: versioning, links, warnings, atomic publication,
# temporary directories, and reading through EOF without a counting pass.
# --------------------------------------------------------------------------
is "new snapshots declare format version 1" "$(head -n 1 snap.fsnap)" "FSNAP|1"
is "hard links share a device ID" "$(field /tree/file.txt 9)" "$(field /tree/hardlink.txt 9)"
is "hard links share an inode" "$(field /tree/file.txt 10)" "$(field /tree/hardlink.txt 10)"
is "hard links record their link count" "$(field /tree/file.txt 11)" "2"
isnt "independent files have different inodes" "$(field /tree/file.txt 10)" "$(field /tree/empty-file 10)"
for n in 9 10 11; do
printf 'FSNAP|1\nF|0644|0|0|0|1||0|1|2|1|/f\n' >links-old.fsnap
awk -F'|' -v OFS='|' -v n="$n" 'NR == 2 { $n = $n + 1 } { print }' links-old.fsnap >links-new.fsnap
is "diff compares identity/link field $n" "$(fsnap diff links-old.fsnap links-new.fsnap)" "$(printf 'M\t/f')"
done
verify_fixture
ln vtree/file.txt outside-hardlink
out=$(fsnap verify vsnap.fsnap vtree 2>&1)
contains "verify detects a changed hard-link count" "$out" "$(printf 'H\t%s/vtree/file.txt' "$WORK")"
rm outside-hardlink
cp -p vtree/file.txt replacement
mv replacement vtree/file.txt
out=$(fsnap verify vsnap.fsnap vtree 2>&1)
contains "verify detects a replaced inode with identical size and mtime" "$out" "$(printf 'I\t%s/vtree/file.txt' "$WORK")"
# Legacy records are still accepted, and missing new metadata does not create
# spurious differences when comparing an old-format snapshot to a new one.
awk -F'|' 'NR > 1 { print $1 "|" $2 "|" $3 "|" $4 "|" $5 "|" $6 "|" $7 "|" $8 "|" $12 }' snap.fsnap >legacy.fsnap
fsnap list legacy.fsnap >/dev/null 2>&1
is "list accepts legacy headerless records" "$?" "0"
out=$(fsnap diff legacy.fsnap snap.fsnap 2>&1)
is "legacy and versioned records compare without invented metadata changes" "$out" ""
for cmd in list diff verify; do
printf 'FSNAP|99\n' >version.fsnap
case $cmd in
list) out=$(fsnap list version.fsnap 2>&1) ;;
diff) out=$(fsnap diff version.fsnap snap.fsnap 2>&1) ;;
verify) out=$(fsnap verify version.fsnap tree 2>&1) ;;
esac
is "$cmd rejects an unsupported format version" "$?" "1"
contains "$cmd explains an unsupported format version" "$out" "unsupported snapshot version"
done
for spec in 'device:8:-1' 'inode:9:184467440737095516160' 'link count:10:0'; do
name=${spec%%:*}; rest=${spec#*:}; index=${rest%%:*}; value=${rest#*:}
printf 'FSNAP|1\nF|0644|0|0|0|1||0|1|2|1|/f\n' |
awk -F'|' -v OFS='|' -v n="$index" -v v="$value" 'NR == 2 { $(n+1) = v } { print }' >version.fsnap
out=$(fsnap list version.fsnap 2>&1)
is "invalid $name is rejected in version 1" "$?" "1"
contains "invalid $name names the field and physical line" "$out" "version.fsnap:2: invalid $name"
done
printf 'FSNAP|1\nF|0644|0|0|0|1||0|/legacy\n' >version.fsnap
fsnap list version.fsnap >/dev/null 2>&1
is "a versioned snapshot cannot contain a legacy record" "$?" "1"
printf 'F|0644|0|0|0|1||0|/f\000hidden\n' >nul.fsnap
fsnap list nul.fsnap >/dev/null 2>&1
is "embedded NUL cannot hide trailing input" "$?" "1"
mkdir link-targets
ln -s 'with|pipe' link-targets/pipe
ln -s 'with\backslash' link-targets/backslash
ln -s "$(printf 'with\nnewline')" link-targets/newline
ln -s 'trailing\' link-targets/trailing
ln -s 'literal\n' link-targets/literal
fsnap create link-targets targets.fsnap >/dev/null 2>&1
is "create accepts escaped symlink targets" "$?" "0"
fsnap list targets.fsnap >/dev/null 2>&1
is "escaped targets survive create/list" "$?" "0"
out=$(fsnap verify targets.fsnap link-targets 2>&1)
is "escaped targets verify successfully" "$?" "0"
is "escaped targets retain their exact bytes" "$out" ""
mkdir partial
mkdir partial/locked
: >partial/good
chmod 000 partial/locked
if [ "$(id -u)" = 0 ]; then
for name in 'create warning' 'verify warning' 'root scan failure' 'root create failure' 'old output preservation'; do
skip "$name for unreadable directories (running as root)"
done
else
fsnap create partial partial.fsnap >out.txt 2>err.txt
is "create publishes a partial snapshot with status 2" "$?" "2"
fsnap verify partial.fsnap partial >out.txt 2>err.txt
is "verify cannot declare an incomplete traversal fully successful" "$?" "2"
fsnap scan partial/locked >/dev/null 2>&1
is "scan fails outright on an unreadable root" "$?" "1"
before=$(cksum <partial.fsnap)
fsnap create partial/locked partial.fsnap >/dev/null 2>&1
is "create fails outright on an unreadable root" "$?" "1"
is "an unreadable root preserves the old output" "$(cksum <partial.fsnap)" "$before"
fi
chmod 755 partial/locked
: >partial/unreadable
chmod 000 partial/unreadable
if [ "$(id -u)" = 0 ]; then
skip "unreadable regular file produces a partial snapshot (running as root)"
skip "unreadable regular file is reported (running as root)"
skip "unreadable regular file is omitted, not given a false checksum (running as root)"
skip "readable sibling survives (running as root)"
else
fsnap create partial partial.fsnap >out.txt 2>err.txt
is "unreadable regular file produces a partial snapshot" "$?" "2"
contains "unreadable regular file is reported" "$(cat err.txt)" "entry skipped"
is "unreadable file is omitted, not given a false checksum" "$(grep -c '/unreadable$' partial.fsnap)" "0"
is "a readable sibling is still recorded" "$(grep -c '/good$' partial.fsnap)" "1"
fi
chmod 600 partial/unreadable
printf 'old snapshot\n' >atomic.fsnap
ln atomic.fsnap held-old
fsnap create tree atomic.fsnap >/dev/null 2>&1
is "atomic replacement succeeds" "$?" "0"
is "atomic replacement does not truncate the old inode" "$(cat held-old)" "old snapshot"
ln -s held-old output-link
fsnap create tree output-link >/dev/null 2>&1
is "a symlink destination is rejected" "$?" "1"
is "a symlink destination cannot overwrite its referent" "$(cat held-old)" "old snapshot"
fsnap create tree tree/no-extension >/dev/null 2>&1
is "an output without a snapshot suffix can live in the tree" "$?" "0"
is "output and temporary files do not snapshot themselves" "$(grep -c 'no-extension\|snapshot_' tree/no-extension)" "0"
rm tree/no-extension
mkdir tmp-work
TMPDIR="$WORK/tmp-work" fsnap create tree tmpdir.fsnap >/dev/null 2>&1
is "create honours a valid TMPDIR" "$?" "0"
is "TMPDIR is cleaned after publication" "$(count_entries tmp-work)" "0"
TMPDIR=tmp-work fsnap create tree relative.fsnap >/dev/null 2>&1
is "a relative TMPDIR works" "$?" "0"
before=$(cksum <tmpdir.fsnap)
TMPDIR="$WORK/nonexistent" fsnap create tree tmpdir.fsnap >/dev/null 2>&1
is "an invalid TMPDIR fails instead of silently using /tmp" "$?" "1"
is "an invalid TMPDIR preserves the destination" "$(cksum <tmpdir.fsnap)" "$before"
TMPDIR="$WORK/tree" fsnap create tree inside-tmp.fsnap >/dev/null 2>&1
is "TMPDIR may be inside the scanned tree" "$?" "0"
is "a work file inside the tree is excluded" "$(grep -c 'snapshot_' inside-tmp.fsnap)" "0"
# A single FIFO writer supplies more than two allocation blocks, followed by a
# bad record. All three readers must reach it; no second open/count is needed.
for cmd in list diff verify; do
mkfifo input.fifo
(
i=0
while [ "$i" -lt 150 ]; do
printf 'F|0644|0|0|0|1||0|/entry-%d\n' "$i"
i=$((i + 1))
done
printf 'X|bad\n'
) >input.fifo &
writer=$!
case $cmd in
list) out=$(fsnap list input.fifo 2>&1) ;;
diff) out=$(fsnap diff input.fifo snap.fsnap 2>&1) ;;
verify) out=$(fsnap verify input.fifo tree 2>&1) ;;
esac
is "$cmd reads a stream through its last record" "$?" "1"
contains "$cmd does not ignore records past an allocation boundary" "$out" "input.fifo:151:"
wait "$writer"
rm input.fifo
done
# --------------------------------------------------------------------------
# Argument handling
# --------------------------------------------------------------------------