golang/go · error

ErrHeader

ErrHeader

Error message

archive/tar: invalid tar header

What it means

ErrHeader is the generic archive/tar sentinel for any malformed, truncated, or inconsistent tar header. The reader returns it from many sites: bad header checksum, unknown format flag, unparseable octal/hex numeric field, integer overflow in size/mtime, missing zero-block terminator, or a truncated stream mid-header. strconv.go also returns it for numeric parse failures. It signals the archive cannot be trusted as a tar.

Source

Thrown at src/archive/tar/common.go:34

	"internal/godebug"
	"io/fs"
	"maps"
	"math"
	"path"
	"reflect"
	"strconv"
	"strings"
	"time"
)

// BUG: Use of the Uid and Gid fields in Header could overflow on 32-bit
// architectures. If a large value is encountered when decoding, the result
// stored in Header will be the truncated version.

var tarinsecurepath = godebug.New("tarinsecurepath")

var (
	ErrHeader          = errors.New("archive/tar: invalid tar header")
	ErrWriteTooLong    = errors.New("archive/tar: write too long")
	ErrFieldTooLong    = errors.New("archive/tar: header field too long")
	ErrWriteAfterClose = errors.New("archive/tar: write after close")
	ErrInsecurePath    = errors.New("archive/tar: insecure file path")
	errMissData        = errors.New("archive/tar: sparse file references non-existent data")
	errUnrefData       = errors.New("archive/tar: sparse file contains unreferenced data")
	errWriteHole       = errors.New("archive/tar: write non-NUL byte in sparse hole")
	errSparseTooLong   = errors.New("archive/tar: sparse map too long")
)

type headerError []string

func (he headerError) Error() string {
	const prefix = "archive/tar: cannot encode header"
	var ss []string
	for _, s := range he {
		if s != "" {
			ss = append(ss, s)

View on GitHub (pinned to b6b368adc5)

Solutions

  1. Verify the file is actually a tar before reading: check magic at offset 257 ("ustar") or wrap with a sniffing reader.
  2. Re-download or re-create the archive from a trusted source; compare checksums (sha256) to detect corruption.
  3. If reading over HTTP, ensure the response is fully buffered and not truncated; check Content-Length vs actual bytes.
  4. Open the tar with binary mode only (no CRLF translation) — on Windows use os.Open, not text-mode readers.
  5. Switch to a more lenient reader or pre-validate with `tar -tvf file.tar` to localize the corruption.

Example fix

// before
tr := tar.NewReader(file)
for {
  hdr, err := tr.Next() // throws ErrHeader on corrupt archive
  ...
}

// after
buf := make([]byte, 512)
n, _ := io.ReadFull(file, buf)
file.Seek(0, io.SeekStart)
if n < 265 || string(buf[257:262]) != "ustar" {
  return fmt.Errorf("not a tar archive (bad magic)")
}
tr := tar.NewReader(file)
Defensive patterns

Strategy: try-catch

Validate before calling

buf := make([]byte, 512)
if n, _ := io.ReadFull(r, buf); n < 265 || string(buf[257:262]) != "ustar" {
  return errors.New("not a tar archive")
}
r.Seek(0, io.SeekStart)

Type guard

func isTarMagic(b []byte) bool { return len(b) >= 265 && string(b[257:262]) == "ustar" }

Try / catch

for {
  hdr, err := tr.Next()
  switch {
  case errors.Is(err, io.EOF):
    return nil
  case errors.Is(err, tar.ErrHeader):
    log.Printf("skipping corrupt entry: %v", err)
    continue
  case err != nil:
    return err
  }
  // process hdr
}

Prevention

When it happens

Trigger: Calling Reader.Next() or reader.Read() on a file that is not a tar archive (gzip header, random bytes, partial download); a tar truncated mid-header; a header whose checksum field does not match the computed value; an octal numeric field with non-octal digits or value exceeding the field width; PAX/GNU extended header that fails validation.

Common situations: Decompressing a non-tar blob with the tar reader; reading a tar over HTTP where the connection dropped; corrupted tar from a flaky network/filesystem; tar produced by a buggy or very old tool with non-standard header encoding; downloading a tarball as text mode (CRLF mangling).

Related errors


AI-assisted analysis of golang/go@b6b368adc5 (2026-08-12). Data as JSON: /api/errors/06781095c530b10d. Report an issue: GitHub.