Only unlink the temporary file when mkstemp actually created it

The cleanup path ran unlink(template) unconditionally. Until mkstemp
succeeds, template still holds the literal "/tmp/snapshot_XXXXXX", so any
earlier failure -- an unresolvable source directory, or mkstemp itself --
deleted whatever file happened to carry that name:

  $ echo victim > /tmp/snapshot_XXXXXX
  $ fsnap create /nonexistent out.fsnap
  create failed: No such file or directory
  $ test -f /tmp/snapshot_XXXXXX || echo gone
  gone

Guard it with fd != -1, which is true exactly when mkstemp turned the
suffix into a real name.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018KyCHPAxWzqa3vHKdXJkgx
This commit is contained in:
Fabio Scotto di Santolo
2026-08-26 15:17:52 +02:00
parent 3cce196045
commit c6ffc7fbb9

View File

@@ -79,6 +79,10 @@ cleanup:;
int cleanup_errno = 0; int cleanup_errno = 0;
free(resolved); 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 (fd != -1)
unlink(template); unlink(template);
if (tmp != NULL && fclose(tmp) != 0) if (tmp != NULL && fclose(tmp) != 0)
cleanup_errno = errno; cleanup_errno = errno;