Add SPEC.md and bring list, create and scan in line with it

SPEC.md records the design the project has been following: goals, staged
plan, and the rules for parsing, error handling and resource ownership.

Conformance fixes it made visible:

- list: accept the `?` file type that create legitimately writes; read
  records with getline so long paths are no longer truncated at a fixed
  buffer size (SPEC 13); reject numeric fields that are not bare digits
  and check ERANGE, so out-of-range values and negative uid/gid no
  longer wrap silently (SPEC 14); release the record when the path
  allocation fails (SPEC 11).
- list, create: keep the errno of the failure that actually occurred.
  An error raised before the cleanup owns errno and is restored; one
  raised by fclose owns it only when nothing had failed yet, which is
  the case a buffered write can hit for the first time at close
  (SPEC 8, SPEC 10).
- scan: propagate printf failures and check fflush(stdout), so a write
  error to a redirected stdout is no longer silently ignored (SPEC 8).
- An empty snapshot is a valid snapshot with zero records, not an
  error: create produces one for an empty directory.

README.md now documents list, points at SPEC.md where the two differ,
and drops the roadmap entry that proposed renaming list to verify --
SPEC 12 defines list as the parser and SPEC 18 reserves verify for
comparing a snapshot against the live filesystem.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01F3NNME8GifswDYLr9VpBzs
This commit is contained in:
Fabio Scotto di Santolo
2026-08-15 15:42:53 +02:00
parent ca660bc9e7
commit 691988e505
7 changed files with 1001 additions and 49 deletions

1
.gitignore vendored
View File

@@ -57,3 +57,4 @@ dkms.conf
# other files # other files
build/ build/
tags tags
*.fsnap

View File

@@ -11,18 +11,24 @@ and records the metadata of everything it finds into a plain-text snapshot file.
> listed under [Known limitations](#known-limitations) — read that section > listed under [Known limitations](#known-limitations) — read that section
> before using it on anything you care about. > before using it on anything you care about.
[SPEC.md](SPEC.md) is the design document: goals, staged plan, and the rules the
implementation is meant to follow. This README describes what the code does
today, and points at the spec where the two differ.
## What it does today ## What it does today
Two commands, and that is the whole feature set: Three commands, and that is the whole feature set:
| Command | Description | | Command | Description |
| --- | --- | | --- | --- |
| `fsnap scan <directory>` | Recursively walk `<directory>` and print every entry to stdout. | | `fsnap scan <directory>` | Recursively walk `<directory>` and print every entry to stdout. |
| `fsnap create <directory> <output_file>` | Recursively walk `<directory>` and write one metadata record per entry into `<output_file>`. | | `fsnap create <directory> <output_file>` | Recursively walk `<directory>` and write one metadata record per entry into `<output_file>`. |
| `fsnap list <snapshot_file>` | Read `<snapshot_file>` and validate every record. Reports the first malformed record on stderr; prints nothing when the snapshot is sound. |
Comparing two snapshots, verifying a snapshot against the live filesystem, and `list` is a parser and validator by design, not a pretty-printer — see
listing the contents of a snapshot are **not** implemented — see the [SPEC.md](SPEC.md) §12. The two remaining commands, `fsnap diff` (compare two
[Roadmap](#roadmap). snapshots) and `fsnap verify` (compare a snapshot against the live filesystem),
are later stages and are **not** implemented. See the [Roadmap](#roadmap).
## Building ## Building
@@ -37,6 +43,13 @@ make clean
The code targets Linux/glibc: it relies on `dirent.d_type`, `realpath(path, NULL)`, The code targets Linux/glibc: it relies on `dirent.d_type`, `realpath(path, NULL)`,
`mkstemp`, and a few `_GNU_SOURCE` extensions. There is no `install` target. `mkstemp`, and a few `_GNU_SOURCE` extensions. There is no `install` target.
[SPEC.md](SPEC.md) §19 aims wider than that — Linux *and* NetBSD, POSIX
interfaces over Linux-specific ones. The gap is `_GNU_SOURCE`, which the sources
declare per-file; the interfaces actually used behind it (`getline`, `realpath`
with a `NULL` buffer) are POSIX.1-2008 and would be reachable through
`_POSIX_C_SOURCE 200809L`. `dirent.d_type` is used as a fast path only, with an
`lstat` fallback for `DT_UNKNOWN`, as the spec requires.
## Usage ## Usage
```sh ```sh
@@ -50,10 +63,15 @@ $ head -3 snapshot.fsnap
F|0644|1000|1000|182|1785598700|/home/user/projects/example/README.md F|0644|1000|1000|182|1785598700|/home/user/projects/example/README.md
D|0755|1000|1000|80|1785598700|/home/user/projects/example/src D|0755|1000|1000|80|1785598700|/home/user/projects/example/src
F|0644|1000|1000|1319|1785598700|/home/user/projects/example/src/main.c F|0644|1000|1000|1319|1785598700|/home/user/projects/example/src/main.c
$ fsnap list snapshot.fsnap # silence means every record parsed
$ fsnap list broken.fsnap
broken.fsnap:3: invalid permissions
``` ```
Exit status is `0` on success and `1` on failure, with the reason printed to Exit status is `0` on success and `1` on failure, with the reason printed to
stderr. stderr. A malformed snapshot makes `list` exit `1` as well — there is no
distinct status for "the file was readable but its contents are not valid".
## Snapshot format ## Snapshot format
@@ -91,6 +109,18 @@ The format is ad-hoc and carries no version header. Assume it will change.
written, and the walk continues with the rest of the tree. written, and the walk continues with the rest of the tree.
- **The snapshot is written to a temporary file under `/tmp` first**, then copied - **The snapshot is written to a temporary file under `/tmp` first**, then copied
to the destination. `TMPDIR` is ignored. to the destination. `TMPDIR` is ignored.
- **`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.
- **`list` catches the malformed records the spec asks for.** All four examples
in [SPEC.md](SPEC.md) §15 — missing fields, invalid permissions, unknown type,
negative size — are rejected with the `snapshot:line: message` form the spec
prescribes.
- **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, and `list` accepts it silently with exit `0`.
## Known limitations ## Known limitations
@@ -109,7 +139,12 @@ These are actual, reproduced problems, not hypotheticals:
splits into two lines. splits into two lines.
- **No hard-link or inode information** is recorded, so hard links cannot be - **No hard-link or inode information** is recorded, so hard links cannot be
detected and identical files cannot be correlated. detected and identical files cannot be correlated.
- **No test suite.** The `tests/` directory exists but is empty. - **`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,
unusual filenames) are exercised automatically.
## Roadmap ## Roadmap
@@ -125,8 +160,14 @@ Rough order of intent, no timeline:
read. read.
- [ ] Quote or escape the path field, and add a version header to the format. - [ ] Quote or escape the path field, and add a version header to the format.
- [ ] Record inode and link count so hard links can be identified. - [ ] Record inode and link count so hard links can be identified.
- [ ] `fsnap diff` — compare a snapshot against the current state of the tree. - [ ] Report a snapshot that grew between the counting pass and the parsing pass
- [ ] `fsnap verify` / `fsnap list` — check and inspect an existing snapshot. instead of silently ignoring the extra records.
- [ ] Store the symlink target with `readlink`, per [SPEC.md](SPEC.md) §6.
- [ ] `fsnap diff <old-snapshot> <new-snapshot>` — compare two snapshots and
classify each change ([SPEC.md](SPEC.md) §17).
- [ ] `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`. - [ ] Honour `TMPDIR` instead of hardcoding `/tmp`.
- [ ] Add a test suite and wire it into the `Makefile`; build with `-O2` so the - [ ] Add a test suite and wire it into the `Makefile`; build with `-O2` so the
compiler's flow analysis is actually enabled. compiler's flow analysis is actually enabled.

856
SPEC.md Normal file
View File

@@ -0,0 +1,856 @@
# fsnap — Project Specification
## 1. Overview
`fsnap` is a small POSIX command-line utility written in C for exploring filesystem and Unix system-programming concepts.
The program recursively walks a directory tree, creates textual snapshots of filesystem metadata, reads and validates existing snapshots, compares snapshots, and verifies them against the current filesystem state.
The project is intentionally designed around low-level POSIX and C standard-library APIs rather than high-level filesystem abstractions.
---
## 2. Goals
The main goals of the project are to practice:
* filesystem traversal;
* file and directory metadata;
* file descriptors;
* standard I/O streams;
* symbolic and hard links;
* POSIX data types;
* error handling with `errno`;
* portable Unix programming;
* resource management;
* parsing textual data;
* designing reusable C interfaces.
The implementation should remain reasonably portable across POSIX systems such as Linux and NetBSD.
---
## 3. Non-Goals
The initial version does not aim to provide:
* filesystem monitoring;
* real-time change detection;
* process parallelism;
* threads;
* cryptographic integrity guarantees;
* compression;
* network synchronization;
* platform-specific filesystem features.
These may be explored later as optional extensions.
---
# 4. Commands
## 4.1 `scan`
```text
fsnap scan <directory>
```
Recursively walks the specified directory and prints every discovered filesystem entry to standard output.
### Requirements
The walker must:
* recursively enter real directories;
* ignore `.` and `..`;
* not follow symbolic links;
* process non-directory entries as leaves;
* support filesystems where `dirent.d_type` is unavailable;
* use `lstat()` as a fallback when `d_type == DT_UNKNOWN`;
* propagate traversal and callback errors to the caller.
The traversal mechanism should be independent from the operation performed on each entry.
Conceptually:
```text
walk(directory, operation, context)
```
This allows the same walker to be reused by commands such as `scan` and `create`.
---
# 5. Snapshot Creation
## 5.1 `create`
```text
fsnap create <directory> <snapshot>
```
Creates a textual snapshot representing the state of the specified directory tree.
The command must reuse the generic filesystem walker.
For every discovered entry, the program obtains metadata using `lstat()` and serializes it into the snapshot.
---
## 5.2 Snapshot Entry
Each snapshot record should contain at least:
```text
type
permissions
uid
gid
size
mtime
path
```
Example conceptual representation:
```text
F|0644|1000|1000|125|1753999812|src/main.c
D|0755|1000|1000|512|1753999700|src
L|0777|1000|1000|8|1753999600|current
```
The exact serialization format is part of the project specification and should remain stable once the parser is implemented.
---
## 5.3 File Types
Filesystem entries should be represented explicitly.
Suggested identifiers:
```text
F = regular file
D = directory
L = symbolic link
P = FIFO
S = socket
C = character device
B = block device
? = unknown or unsupported type
```
The filesystem walker itself does not necessarily need to distinguish all of these types.
For traversal purposes, the important distinction is:
```text
directory
non-directory entry
```
The snapshot writer is responsible for determining the specific entry type.
---
# 6. Symbolic Links
Symbolic links must not be followed during traversal.
`lstat()` must therefore be used when metadata about an entry is required.
A symbolic link must be represented as a symbolic link rather than as the object it references.
A later version of the snapshot format should also store the link target obtained using:
```text
readlink()
```
Broken symbolic links must still be representable in a snapshot.
---
# 7. Hard Links
Hard links are not a separate filesystem object type.
Two paths refer to the same filesystem object when both their:
```text
st_dev
st_ino
```
values match.
Future versions of the snapshot format may store:
```text
device ID
inode number
link count
```
to allow hard-link relationships to be detected.
---
# 8. Snapshot Writing
Snapshot output must use standard C I/O streams.
Relevant APIs include:
```text
fopen()
fdopen()
fprintf()
fflush()
fclose()
```
All operations capable of failing must have their return values checked.
In particular, errors from:
```text
fprintf()
fflush()
fclose()
```
must not be ignored.
A buffered write may succeed initially and fail only when the stream is flushed or closed.
---
# 9. Temporary Files
Snapshot generation may use a temporary file created using:
```text
mkstemp()
```
`mkstemp()` returns an open file descriptor.
The descriptor may then be associated with a `FILE *` stream using:
```text
fdopen()
```
Ownership rules must be respected:
```text
mkstemp succeeds + fdopen fails
-> close(fd)
fdopen succeeds
-> fclose(stream)
```
The same descriptor must never be closed twice.
Temporary files must be removed during cleanup when no longer required.
---
# 10. Error Handling
Errors should be propagated rather than silently ignored.
The program should use:
```text
0
```
for successful operations and a non-zero result for failures.
Library-style internal functions should generally return:
```text
0
```
on success and:
```text
-1
```
on failure where appropriate.
Diagnostic output should be written to:
```text
stderr
```
while normal command output should be written to:
```text
stdout
```
When cleanup operations occur after an error, the original `errno` should be preserved whenever possible.
---
# 11. Resource Management
Every acquired resource must have a clearly defined owner.
Resources include:
* dynamically allocated memory;
* directory streams;
* file descriptors;
* `FILE *` streams;
* temporary files.
Every successful:
```text
malloc()
opendir()
open()
mkstemp()
fopen()
```
must eventually have a corresponding cleanup operation.
Cleanup must also occur on error paths.
---
# 12. Snapshot Parser
## 12.1 `list`
```text
fsnap list <snapshot>
```
Reads and validates an existing snapshot.
The main purpose of this command is to implement a robust parser for the snapshot format.
The parser should transform each textual record into an internal structure representing one snapshot entry.
Conceptually:
```text
snapshot_entry
├── type
├── permissions
├── uid
├── gid
├── size
├── modification time
└── path
```
The exact C structure is intentionally left as an implementation decision.
---
# 13. Reading Snapshot Records
Records must be read without assuming an arbitrary fixed maximum line length.
The parser should therefore use dynamically sized input rather than constructs such as:
```text
char line[1024]
```
POSIX facilities such as `getline()` are appropriate.
The program must distinguish:
* successful read;
* end of file;
* I/O error;
* malformed record.
---
# 14. Numeric Parsing
Numeric fields must be validated carefully.
The parser must detect:
* empty numeric fields;
* invalid characters;
* trailing characters;
* negative values where forbidden;
* values outside the representable range;
* integer overflow and underflow.
Functions such as:
```text
strtol()
strtoul()
strtoimax()
strtoumax()
```
may be used with appropriate validation.
The parser must not assume that POSIX types such as:
```text
uid_t
gid_t
off_t
time_t
ino_t
```
are equivalent to a specific primitive C type.
---
# 15. Record Validation
The parser must reject malformed records.
Examples include:
```text
F|0644|1000
```
Missing fields.
```text
F|hello|1000|1000|12|123|file
```
Invalid permissions.
```text
X|0644|1000|1000|12|123|file
```
Unknown file type.
```text
F|0644|1000|1000|-10|123|file
```
Invalid size for a regular file.
Errors should preferably identify the offending snapshot and line number.
Example:
```text
snapshot.fsnap:17: invalid uid
```
---
# 16. Path Encoding
Unix filenames may contain almost any byte except:
```text
NUL
/
```
inside a path component.
Therefore filenames may legally contain characters used by the snapshot format, including:
```text
|
newline
backslash
```
Before the snapshot format is considered stable, it must define how such paths are encoded.
Possible strategies include:
### Escaping
For example:
```text
\ -> \\
| -> \|
newline -> \n
```
### Length-prefixed fields
Store the pathname length explicitly before its contents.
The chosen encoding must allow the parser to reconstruct the original pathname without ambiguity.
---
# 17. Snapshot Comparison
## 17.1 `diff`
Future command:
```text
fsnap diff <old-snapshot> <new-snapshot>
```
Compares two snapshots and reports changes.
Possible result categories:
```text
A = added
D = deleted
M = metadata or contents changed
P = permissions changed
L = symbolic link changed
```
The first implementation may load all snapshot records into memory and sort them by pathname.
---
# 18. Filesystem Verification
## 18.1 `verify`
Future command:
```text
fsnap verify <snapshot> <directory>
```
Compares a stored snapshot with the current filesystem.
It should eventually distinguish conditions such as:
```text
missing file
new file
type changed
size changed
permissions changed
owner changed
mtime changed
symbolic-link target changed
access error
```
Errors such as:
```text
ENOENT
EACCES
ENOTDIR
ELOOP
```
must not all be interpreted as equivalent conditions.
---
# 19. Portability
The project should prefer POSIX interfaces and avoid unnecessary Linux-specific functionality.
Code should be tested on multiple Unix-like systems where practical.
Current target environments include at least:
```text
Linux
NetBSD
```
The implementation must not rely on `dirent.d_type` always being populated.
`DT_UNKNOWN` must be handled correctly.
---
# 20. Build Requirements
The project should be compilable using a standard Makefile.
Recommended compiler configuration:
```text
-std=c11
-Wall
-Wextra
-Wpedantic
-Wconversion
```
Headers should reside under:
```text
include/
```
and compiler include paths should be configured through:
```text
-Iinclude
```
Automatic header dependency generation with:
```text
-MMD
-MP
```
is recommended.
---
# 21. Suggested Project Structure
```text
fsnap/
├── Makefile
├── README.md
├── include/
│ └── fsnap.h
├── src/
│ ├── main.c
│ ├── walk.c
│ ├── scan.c
│ ├── create.c
│ ├── parser.c
│ ├── compare.c
│ └── utility.c
└── tests/
```
The exact module layout may evolve as responsibilities become clearer.
---
# 22. Testing
The filesystem walker and snapshot writer should be tested against trees containing:
```text
regular files
empty files
directories
nested directories
symbolic links
broken symbolic links
hard links
FIFOs
character or block devices where available
unusual filenames
permission errors
```
Example test environment:
```sh
mkdir -p test/subdir
printf 'hello\n' > test/file.txt
ln test/file.txt test/hardlink.txt
ln -s file.txt test/link.txt
ln -s missing.txt test/broken-link
mkfifo test/pipe
```
The walker must never recursively follow `link.txt`, even if a symbolic link points to a directory.
---
# 23. Development Stages
The project is divided into incremental stages.
## Stage 1 — Filesystem Walker
Implement:
```text
fsnap scan
```
Goals:
* directory traversal;
* `dirent`;
* `d_type`;
* `DT_UNKNOWN`;
* `lstat()`;
* callback-based walker.
**Status: implemented.**
## Stage 2 — Snapshot Writer
Implement:
```text
fsnap create
```
Goals:
* filesystem metadata;
* `struct stat`;
* standard I/O;
* serialization;
* temporary files;
* robust cleanup.
**Status: implemented.**
## Stage 3 — Snapshot Parser
Implement:
```text
fsnap list
```
Goals:
* `getline()`;
* parsing;
* numeric conversion;
* input validation;
* dynamic memory;
* snapshot entry representation.
**Status: next development stage.**
## Stage 4 — Snapshot Comparison
Implement:
```text
fsnap diff
```
Goals:
* collections of records;
* sorting;
* comparison;
* filesystem identity and metadata semantics.
## Stage 5 — Filesystem Verification
Implement:
```text
fsnap verify
```
Goals:
* compare persisted metadata against the live filesystem;
* classify changes;
* handle filesystem errors correctly.
---
# 24. Optional Extensions
Once the basic project is complete, possible extensions include:
### Content hashing
Calculate checksums or hashes for regular files.
This introduces additional practice with:
```text
open()
read()
close()
```
and contrasts raw file I/O with standard I/O.
### Sparse-file detection
Compare logical file size with allocated blocks using fields such as:
```text
st_size
st_blocks
```
### Hard-link detection
Track:
```text
st_dev
st_ino
```
to identify multiple paths referring to the same inode.
### Snapshot format versioning
Add a header such as:
```text
FSNAP|1
```
to allow the on-disk format to evolve without making older snapshots impossible to recognize.
### Atomic snapshot replacement
Write the completed snapshot to a temporary file and atomically replace the destination where the target filesystem permits it.
### Process-based hashing
After studying Unix process management, file hashing may be distributed across worker processes.
### Signal handling
After studying Unix signals, long-running snapshot creation could respond cleanly to interruption and remove incomplete temporary files.
---
# 25. Learning Objectives
By the end of the project, the implementation should demonstrate practical understanding of concepts covered by the early chapters of *Advanced Programming in the UNIX Environment*, particularly:
* Unix filesystem semantics;
* file descriptors;
* file metadata;
* directories;
* inode-related concepts;
* symbolic links;
* standard I/O;
* buffering;
* error handling;
* POSIX types;
* portability;
* resource ownership.
The project should favor correctness, explicit error handling, and understanding of Unix behavior over minimizing the amount of code.

View File

@@ -9,9 +9,9 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include <strings.h>
#include <sys/stat.h> #include <sys/stat.h>
#include <unistd.h> #include <unistd.h>
#include <strings.h>
static char file_type(mode_t mode) { static char file_type(mode_t mode) {
if (S_ISREG(mode)) if (S_ISREG(mode))
@@ -105,11 +105,15 @@ int create(const char *directory, const char *output_file) {
goto out; goto out;
} }
out: out:;
/* A buffered write can fail for the first time here, so fclose owns errno
when nothing had failed before it. */
const int saved_errno = errno;
free(resolved); free(resolved);
unlink(template); unlink(template);
if (tmp != NULL && fclose(tmp) != 0) { if (tmp != NULL && fclose(tmp) != 0 && rc == 0)
rc = -1; return -1;
} if (rc == -1)
errno = saved_errno;
return rc; return rc;
} }

View File

@@ -1,17 +1,10 @@
#define _GNU_SOURCE
#include "list.h" #include "list.h"
#include <errno.h> #include <errno.h>
#include <inttypes.h> #include <inttypes.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include <strings.h>
#include <sys/stat.h>
#ifdef LINE_MAX
#define LINEMAX LINE_MAX
#else
#define LINEMAX 2048
#endif
#define NFIELDS 7 #define NFIELDS 7
@@ -72,6 +65,7 @@ static int parse_file_type(const char *s, char *out) {
case 'C': case 'C':
case 'B': case 'B':
case 'S': case 'S':
case '?':
*out = c; *out = c;
return 0; return 0;
default: default:
@@ -79,14 +73,31 @@ static int parse_file_type(const char *s, char *out) {
} }
} }
/* strtol and friends accept leading whitespace, a sign, and wrap negative
input around for the unsigned variants. Reject anything that is not a bare
run of decimal digits before converting. */
static int only_digits(const char *s, int base) {
const char last = (base == 8) ? '7' : '9';
if (s == NULL || *s == '\0')
return 0;
for (const char *p = s; *p != '\0'; p++) {
if (*p < '0' || *p > last)
return 0;
}
return 1;
}
static int parse_perm(const char *s, unsigned int *out) { static int parse_perm(const char *s, unsigned int *out) {
char *end = NULL; char *end = NULL;
if (s == NULL || strlen(s) != 4) if (s == NULL || strlen(s) != 4 || !only_digits(s, 8))
return -1; return -1;
errno = 0;
unsigned long v = strtoul(s, &end, 8); unsigned long v = strtoul(s, &end, 8);
if (*s == '\0' || *end != '\0' || v > 07777) if (*end != '\0' || errno == ERANGE || v > 07777)
return -1; return -1;
*out = (unsigned int)v; *out = (unsigned int)v;
@@ -96,11 +107,12 @@ static int parse_perm(const char *s, unsigned int *out) {
static int parse_uintmax(const char *s, uintmax_t *out) { static int parse_uintmax(const char *s, uintmax_t *out) {
char *end = NULL; char *end = NULL;
if (s == NULL || *s == '\0') if (!only_digits(s, 10))
return -1; return -1;
errno = 0;
uintmax_t v = strtoumax(s, &end, 10); uintmax_t v = strtoumax(s, &end, 10);
if (*end != '\0') if (*end != '\0' || errno == ERANGE)
return -1; return -1;
*out = v; *out = v;
@@ -110,11 +122,12 @@ static int parse_uintmax(const char *s, uintmax_t *out) {
static int parse_intmax_nonnegative(const char *s, intmax_t *out) { static int parse_intmax_nonnegative(const char *s, intmax_t *out) {
char *end = NULL; char *end = NULL;
if (s == NULL || *s == '\0') if (!only_digits(s, 10))
return -1; return -1;
errno = 0;
intmax_t v = strtoimax(s, &end, 10); intmax_t v = strtoimax(s, &end, 10);
if (*end != '\0' || v < 0) if (*end != '\0' || errno == ERANGE || v < 0)
return -1; return -1;
*out = v; *out = v;
@@ -179,8 +192,10 @@ struct RecordObject *unpack(char *s) {
} }
char *path = calloc(strlen(fields[6]) + 1, sizeof(char)); char *path = calloc(strlen(fields[6]) + 1, sizeof(char));
if (path == NULL) if (path == NULL) {
release(objp);
return NULL; return NULL;
}
objp->path = strcpy(path, fields[6]); objp->path = strcpy(path, fields[6]);
@@ -200,23 +215,31 @@ int release(struct RecordObject *obj) {
return 0; return 0;
} }
static size_t count_lines(const char *file) { static int count_lines(const char *file) {
FILE *f = fopen(file, "r"); FILE *f = fopen(file, "r");
if (f == NULL) { if (f == NULL) {
return 0; return -1;
} }
size_t count = 0; size_t size = 0;
char buf[LINEMAX]; int count = 0;
while (fgets(buf, sizeof(buf), f) != NULL) char *buf = NULL;
while (getline(&buf, &size, f) != -1)
count++; count++;
if (ferror(f)) { if (ferror(f)) {
/* Capture before the cleanup: free and fclose may both touch errno. */
const int saved_errno = errno;
free(buf);
fclose(f); fclose(f);
return 0; errno = saved_errno;
return -1;
} }
fclose(f); free(buf);
if (fclose(f) != 0) {
return -1;
}
return count; return count;
} }
@@ -227,16 +250,24 @@ int list(const char *snapshot) {
} }
int rc = 0; int rc = 0;
const size_t arr_size = count_lines(snapshot); struct RecordObject **records = NULL;
char *buf = NULL;
const int arr_size = count_lines(snapshot);
if (arr_size == 0) { if (arr_size == 0) {
goto out;
} else if (arr_size < 0) {
rc = -1; rc = -1;
goto out; goto out;
} }
int i = 0; int i = 0;
char buf[LINEMAX]; size_t size = 0;
struct RecordObject **records = calloc(arr_size, sizeof(*records)); records = calloc((size_t)arr_size, sizeof(*records));
while (fgets(buf, sizeof(buf), snapshot_file) != NULL) { if (records == NULL) {
rc = -1;
goto out;
}
while (getline(&buf, &size, snapshot_file) != -1 && i < arr_size) {
struct RecordObject *objp = unpack(buf); struct RecordObject *objp = unpack(buf);
if (objp == NULL) { if (objp == NULL) {
fprintf(stderr, "%s:%d: unparsable line\n", snapshot, i + 1); fprintf(stderr, "%s:%d: unparsable line\n", snapshot, i + 1);
@@ -260,17 +291,30 @@ int list(const char *snapshot) {
goto out; goto out;
} }
out: out:;
if (snapshot_file != NULL && fclose(snapshot_file) != 0) { /* An error that happened before the cleanup owns errno; one raised by the
rc = -1; cleanup itself owns it only when nothing had failed yet. */
} 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) { if (records != NULL) {
for (size_t i = 0; i < arr_size; i++) { for (int j = 0; j < arr_size; j++) {
release(records[i]); release(records[j]);
records[i] = NULL; records[j] = NULL;
} }
free(records); free(records);
records = NULL; records = NULL;
} }
if (rc == 0 && cleanup_errno != 0) {
errno = cleanup_errno;
return -1;
}
if (rc == -1)
errno = saved_errno;
return rc; return rc;
} }

View File

@@ -6,7 +6,7 @@
int main(int argc, char *argv[]) { int main(int argc, char *argv[]) {
if (argc < 2) { if (argc < 2) {
fprintf(stderr, "%s: command not found [scan|create]\n", argv[0]); fprintf(stderr, "%s: command not found [scan|create|list]\n", argv[0]);
return EXIT_FAILURE; return EXIT_FAILURE;
} }

View File

@@ -9,8 +9,7 @@
static int print_file(const char *file, void *context) { static int print_file(const char *file, void *context) {
(void)context; (void)context;
printf("[%s]\n", file); return printf("[%s]\n", file) < 0 ? -1 : 0;
return 0;
} }
/* Scan recursively directory, printing all entry */ /* Scan recursively directory, printing all entry */
@@ -25,9 +24,16 @@ int scan(const char *directory) {
return -1; return -1;
if (walk(dir, print_file, NULL) == -1) { if (walk(dir, print_file, NULL) == -1) {
const int saved_errno = errno;
free(dir); free(dir);
errno = saved_errno;
return -1; return -1;
} }
free(dir); free(dir);
/* stdout is block-buffered when redirected, so a write error can surface
only here. */
if (fflush(stdout) == EOF)
return -1;
return 0; return 0;
} }