tar_test.go 23.2 KB
Newer Older
1 2 3 4 5 6 7
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package tar

import (
8
	"bytes"
9 10
	"errors"
	"fmt"
11
	"internal/testenv"
12
	"io"
13
	"io/ioutil"
14
	"math"
15
	"os"
16
	"path"
17
	"path/filepath"
18
	"reflect"
19
	"strings"
20 21 22 23
	"testing"
	"time"
)

24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
type testError struct{ error }

type fileOps []interface{} // []T where T is (string | int64)

// testFile is an io.ReadWriteSeeker where the IO operations performed
// on it must match the list of operations in ops.
type testFile struct {
	ops fileOps
	pos int64
}

func (f *testFile) Read(b []byte) (int, error) {
	if len(b) == 0 {
		return 0, nil
	}
	if len(f.ops) == 0 {
		return 0, io.EOF
	}
	s, ok := f.ops[0].(string)
	if !ok {
		return 0, errors.New("unexpected Read operation")
	}

	n := copy(b, s)
	if len(s) > n {
		f.ops[0] = s[n:]
	} else {
		f.ops = f.ops[1:]
	}
	f.pos += int64(len(b))
	return n, nil
}

func (f *testFile) Write(b []byte) (int, error) {
	if len(b) == 0 {
		return 0, nil
	}
	if len(f.ops) == 0 {
		return 0, errors.New("unexpected Write operation")
	}
	s, ok := f.ops[0].(string)
	if !ok {
		return 0, errors.New("unexpected Write operation")
	}

	if !strings.HasPrefix(s, string(b)) {
		return 0, testError{fmt.Errorf("got Write(%q), want Write(%q)", b, s)}
	}
	if len(s) > len(b) {
		f.ops[0] = s[len(b):]
	} else {
		f.ops = f.ops[1:]
	}
	f.pos += int64(len(b))
	return len(b), nil
}

func (f *testFile) Seek(pos int64, whence int) (int64, error) {
	if pos == 0 && whence == io.SeekCurrent {
		return f.pos, nil
	}
	if len(f.ops) == 0 {
		return 0, errors.New("unexpected Seek operation")
	}
	s, ok := f.ops[0].(int64)
	if !ok {
		return 0, errors.New("unexpected Seek operation")
	}

	if s != pos || whence != io.SeekCurrent {
		return 0, testError{fmt.Errorf("got Seek(%d, %d), want Seek(%d, %d)", pos, whence, s, io.SeekCurrent)}
	}
	f.pos += s
	f.ops = f.ops[1:]
	return f.pos, nil
}

101
func equalSparseEntries(x, y []sparseEntry) bool {
102 103 104 105 106
	return (len(x) == 0 && len(y) == 0) || reflect.DeepEqual(x, y)
}

func TestSparseEntries(t *testing.T) {
	vectors := []struct {
107
		in   []sparseEntry
108 109 110
		size int64

		wantValid    bool          // Result of validateSparseEntries
111 112
		wantAligned  []sparseEntry // Result of alignSparseEntries
		wantInverted []sparseEntry // Result of invertSparseEntries
113
	}{{
114
		in: []sparseEntry{}, size: 0,
115
		wantValid:    true,
116
		wantInverted: []sparseEntry{{0, 0}},
117
	}, {
118
		in: []sparseEntry{}, size: 5000,
119
		wantValid:    true,
120
		wantInverted: []sparseEntry{{0, 5000}},
121
	}, {
122
		in: []sparseEntry{{0, 5000}}, size: 5000,
123
		wantValid:    true,
124 125
		wantAligned:  []sparseEntry{{0, 5000}},
		wantInverted: []sparseEntry{{5000, 0}},
126
	}, {
127
		in: []sparseEntry{{1000, 4000}}, size: 5000,
128
		wantValid:    true,
129 130
		wantAligned:  []sparseEntry{{1024, 3976}},
		wantInverted: []sparseEntry{{0, 1000}, {5000, 0}},
131
	}, {
132
		in: []sparseEntry{{0, 3000}}, size: 5000,
133
		wantValid:    true,
134 135
		wantAligned:  []sparseEntry{{0, 2560}},
		wantInverted: []sparseEntry{{3000, 2000}},
136
	}, {
137
		in: []sparseEntry{{3000, 2000}}, size: 5000,
138
		wantValid:    true,
139 140
		wantAligned:  []sparseEntry{{3072, 1928}},
		wantInverted: []sparseEntry{{0, 3000}, {5000, 0}},
141
	}, {
142
		in: []sparseEntry{{2000, 2000}}, size: 5000,
143
		wantValid:    true,
144 145
		wantAligned:  []sparseEntry{{2048, 1536}},
		wantInverted: []sparseEntry{{0, 2000}, {4000, 1000}},
146
	}, {
147
		in: []sparseEntry{{0, 2000}, {8000, 2000}}, size: 10000,
148
		wantValid:    true,
149 150
		wantAligned:  []sparseEntry{{0, 1536}, {8192, 1808}},
		wantInverted: []sparseEntry{{2000, 6000}, {10000, 0}},
151
	}, {
152
		in: []sparseEntry{{0, 2000}, {2000, 2000}, {4000, 0}, {4000, 3000}, {7000, 1000}, {8000, 0}, {8000, 2000}}, size: 10000,
153
		wantValid:    true,
154 155
		wantAligned:  []sparseEntry{{0, 1536}, {2048, 1536}, {4096, 2560}, {7168, 512}, {8192, 1808}},
		wantInverted: []sparseEntry{{10000, 0}},
156
	}, {
157
		in: []sparseEntry{{0, 0}, {1000, 0}, {2000, 0}, {3000, 0}, {4000, 0}, {5000, 0}}, size: 5000,
158
		wantValid:    true,
159
		wantInverted: []sparseEntry{{0, 5000}},
160
	}, {
161
		in: []sparseEntry{{1, 0}}, size: 0,
162 163
		wantValid: false,
	}, {
164
		in: []sparseEntry{{-1, 0}}, size: 100,
165 166
		wantValid: false,
	}, {
167
		in: []sparseEntry{{0, -1}}, size: 100,
168 169
		wantValid: false,
	}, {
170
		in: []sparseEntry{{0, 0}}, size: -100,
171 172
		wantValid: false,
	}, {
173
		in: []sparseEntry{{math.MaxInt64, 3}, {6, -5}}, size: 35,
174 175
		wantValid: false,
	}, {
176
		in: []sparseEntry{{1, 3}, {6, -5}}, size: 35,
177 178
		wantValid: false,
	}, {
179
		in: []sparseEntry{{math.MaxInt64, math.MaxInt64}}, size: math.MaxInt64,
180 181
		wantValid: false,
	}, {
182
		in: []sparseEntry{{3, 3}}, size: 5,
183 184
		wantValid: false,
	}, {
185
		in: []sparseEntry{{2, 0}, {1, 0}, {0, 0}}, size: 3,
186 187
		wantValid: false,
	}, {
188
		in: []sparseEntry{{1, 3}, {2, 2}}, size: 10,
189 190 191 192 193 194 195 196 197 198 199
		wantValid: false,
	}}

	for i, v := range vectors {
		gotValid := validateSparseEntries(v.in, v.size)
		if gotValid != v.wantValid {
			t.Errorf("test %d, validateSparseEntries() = %v, want %v", i, gotValid, v.wantValid)
		}
		if !v.wantValid {
			continue
		}
200
		gotAligned := alignSparseEntries(append([]sparseEntry{}, v.in...), v.size)
201 202 203
		if !equalSparseEntries(gotAligned, v.wantAligned) {
			t.Errorf("test %d, alignSparseEntries():\ngot  %v\nwant %v", i, gotAligned, v.wantAligned)
		}
204
		gotInverted := invertSparseEntries(append([]sparseEntry{}, v.in...), v.size)
205 206 207 208 209 210
		if !equalSparseEntries(gotInverted, v.wantInverted) {
			t.Errorf("test %d, inverseSparseEntries():\ngot  %v\nwant %v", i, gotInverted, v.wantInverted)
		}
	}
}

211
func TestFileInfoHeader(t *testing.T) {
212
	fi, err := os.Stat("testdata/small.txt")
213 214 215 216 217
	if err != nil {
		t.Fatal(err)
	}
	h, err := FileInfoHeader(fi, "")
	if err != nil {
218
		t.Fatalf("FileInfoHeader: %v", err)
219 220 221 222
	}
	if g, e := h.Name, "small.txt"; g != e {
		t.Errorf("Name = %q; want %q", g, e)
	}
223
	if g, e := h.Mode, int64(fi.Mode().Perm()); g != e {
224 225 226 227 228 229 230 231
		t.Errorf("Mode = %#o; want %#o", g, e)
	}
	if g, e := h.Size, int64(5); g != e {
		t.Errorf("Size = %v; want %v", g, e)
	}
	if g, e := h.ModTime, fi.ModTime(); !g.Equal(e) {
		t.Errorf("ModTime = %v; want %v", g, e)
	}
232 233 234 235
	// FileInfoHeader should error when passing nil FileInfo
	if _, err := FileInfoHeader(nil, ""); err == nil {
		t.Fatalf("Expected error when passing nil to FileInfoHeader")
	}
236 237
}

238 239 240 241 242 243 244 245 246 247 248 249
func TestFileInfoHeaderDir(t *testing.T) {
	fi, err := os.Stat("testdata")
	if err != nil {
		t.Fatal(err)
	}
	h, err := FileInfoHeader(fi, "")
	if err != nil {
		t.Fatalf("FileInfoHeader: %v", err)
	}
	if g, e := h.Name, "testdata/"; g != e {
		t.Errorf("Name = %q; want %q", g, e)
	}
250
	// Ignoring c_ISGID for golang.org/issue/4867
251
	if g, e := h.Mode&^c_ISGID, int64(fi.Mode().Perm()); g != e {
252 253 254 255 256 257 258 259 260 261
		t.Errorf("Mode = %#o; want %#o", g, e)
	}
	if g, e := h.Size, int64(0); g != e {
		t.Errorf("Size = %v; want %v", g, e)
	}
	if g, e := h.ModTime, fi.ModTime(); !g.Equal(e) {
		t.Errorf("ModTime = %v; want %v", g, e)
	}
}

262
func TestFileInfoHeaderSymlink(t *testing.T) {
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
	testenv.MustHaveSymlink(t)

	tmpdir, err := ioutil.TempDir("", "TestFileInfoHeaderSymlink")
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(tmpdir)

	link := filepath.Join(tmpdir, "link")
	target := tmpdir
	err = os.Symlink(target, link)
	if err != nil {
		t.Fatal(err)
	}
	fi, err := os.Lstat(link)
	if err != nil {
		t.Fatal(err)
	}

	h, err := FileInfoHeader(fi, target)
283 284 285
	if err != nil {
		t.Fatal(err)
	}
286
	if g, e := h.Name, fi.Name(); g != e {
287 288
		t.Errorf("Name = %q; want %q", g, e)
	}
289
	if g, e := h.Linkname, target; g != e {
290 291
		t.Errorf("Linkname = %q; want %q", g, e)
	}
292 293 294
	if g, e := h.Typeflag, byte(TypeSymlink); g != e {
		t.Errorf("Typeflag = %v; want %v", g, e)
	}
295 296
}

297 298 299 300 301 302
func TestRoundTrip(t *testing.T) {
	data := []byte("some file contents")

	var b bytes.Buffer
	tw := NewWriter(&b)
	hdr := &Header{
303 304 305 306 307 308
		Name:       "file.txt",
		Uid:        1 << 21, // Too big for 8 octal digits
		Size:       int64(len(data)),
		ModTime:    time.Now().Round(time.Second),
		PAXRecords: map[string]string{"uid": "2097152"},
		Format:     FormatPAX,
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
	}
	if err := tw.WriteHeader(hdr); err != nil {
		t.Fatalf("tw.WriteHeader: %v", err)
	}
	if _, err := tw.Write(data); err != nil {
		t.Fatalf("tw.Write: %v", err)
	}
	if err := tw.Close(); err != nil {
		t.Fatalf("tw.Close: %v", err)
	}

	// Read it back.
	tr := NewReader(&b)
	rHdr, err := tr.Next()
	if err != nil {
		t.Fatalf("tr.Next: %v", err)
	}
	if !reflect.DeepEqual(rHdr, hdr) {
		t.Errorf("Header mismatch.\n got %+v\nwant %+v", rHdr, hdr)
	}
	rData, err := ioutil.ReadAll(tr)
	if err != nil {
		t.Fatalf("Read: %v", err)
	}
	if !bytes.Equal(rData, data) {
		t.Errorf("Data mismatch.\n got %q\nwant %q", rData, data)
	}
}
337 338 339 340 341 342 343

type headerRoundTripTest struct {
	h  *Header
	fm os.FileMode
}

func TestHeaderRoundTrip(t *testing.T) {
344
	vectors := []headerRoundTripTest{{
345
		// regular file.
346 347
		h: &Header{
			Name:     "test.txt",
348
			Mode:     0644,
349 350 351
			Size:     12,
			ModTime:  time.Unix(1360600916, 0),
			Typeflag: TypeReg,
352
		},
353 354
		fm: 0644,
	}, {
355
		// symbolic link.
356 357
		h: &Header{
			Name:     "link.txt",
358
			Mode:     0777,
359 360 361
			Size:     0,
			ModTime:  time.Unix(1360600852, 0),
			Typeflag: TypeSymlink,
362
		},
363 364
		fm: 0777 | os.ModeSymlink,
	}, {
365
		// character device node.
366 367
		h: &Header{
			Name:     "dev/null",
368
			Mode:     0666,
369 370 371
			Size:     0,
			ModTime:  time.Unix(1360578951, 0),
			Typeflag: TypeChar,
372
		},
373 374
		fm: 0666 | os.ModeDevice | os.ModeCharDevice,
	}, {
375
		// block device node.
376 377
		h: &Header{
			Name:     "dev/sda",
378
			Mode:     0660,
379 380 381
			Size:     0,
			ModTime:  time.Unix(1360578954, 0),
			Typeflag: TypeBlock,
382
		},
383 384
		fm: 0660 | os.ModeDevice,
	}, {
385
		// directory.
386 387
		h: &Header{
			Name:     "dir/",
388
			Mode:     0755,
389 390 391
			Size:     0,
			ModTime:  time.Unix(1360601116, 0),
			Typeflag: TypeDir,
392
		},
393 394
		fm: 0755 | os.ModeDir,
	}, {
395
		// fifo node.
396 397
		h: &Header{
			Name:     "dev/initctl",
398
			Mode:     0600,
399 400 401
			Size:     0,
			ModTime:  time.Unix(1360578949, 0),
			Typeflag: TypeFifo,
402
		},
403 404
		fm: 0600 | os.ModeNamedPipe,
	}, {
405
		// setuid.
406 407
		h: &Header{
			Name:     "bin/su",
408
			Mode:     0755 | c_ISUID,
409 410 411
			Size:     23232,
			ModTime:  time.Unix(1355405093, 0),
			Typeflag: TypeReg,
412
		},
413 414
		fm: 0755 | os.ModeSetuid,
	}, {
415
		// setguid.
416 417
		h: &Header{
			Name:     "group.txt",
418
			Mode:     0750 | c_ISGID,
419 420 421
			Size:     0,
			ModTime:  time.Unix(1360602346, 0),
			Typeflag: TypeReg,
422
		},
423 424
		fm: 0750 | os.ModeSetgid,
	}, {
425
		// sticky.
426 427
		h: &Header{
			Name:     "sticky.txt",
428
			Mode:     0600 | c_ISVTX,
429 430 431
			Size:     7,
			ModTime:  time.Unix(1360602540, 0),
			Typeflag: TypeReg,
432
		},
433 434
		fm: 0600 | os.ModeSticky,
	}, {
435
		// hard link.
436 437
		h: &Header{
			Name:     "hard.txt",
438
			Mode:     0644,
439 440 441 442
			Size:     0,
			Linkname: "file.txt",
			ModTime:  time.Unix(1360600916, 0),
			Typeflag: TypeLink,
443
		},
444 445
		fm: 0644,
	}, {
446
		// More information.
447 448
		h: &Header{
			Name:     "info.txt",
449
			Mode:     0600,
450 451 452 453 454 455 456
			Size:     0,
			Uid:      1000,
			Gid:      1000,
			ModTime:  time.Unix(1360602540, 0),
			Uname:    "slartibartfast",
			Gname:    "users",
			Typeflag: TypeReg,
457
		},
458 459
		fm: 0600,
	}}
460

461 462
	for i, v := range vectors {
		fi := v.h.FileInfo()
463 464 465 466 467
		h2, err := FileInfoHeader(fi, "")
		if err != nil {
			t.Error(err)
			continue
		}
468
		if strings.Contains(fi.Name(), "/") {
469
			t.Errorf("FileInfo of %q contains slash: %q", v.h.Name, fi.Name())
470
		}
471
		name := path.Base(v.h.Name)
472 473 474 475
		if fi.IsDir() {
			name += "/"
		}
		if got, want := h2.Name, name; got != want {
476 477
			t.Errorf("i=%d: Name: got %v, want %v", i, got, want)
		}
478
		if got, want := h2.Size, v.h.Size; got != want {
479 480
			t.Errorf("i=%d: Size: got %v, want %v", i, got, want)
		}
481
		if got, want := h2.Uid, v.h.Uid; got != want {
482 483
			t.Errorf("i=%d: Uid: got %d, want %d", i, got, want)
		}
484
		if got, want := h2.Gid, v.h.Gid; got != want {
485 486
			t.Errorf("i=%d: Gid: got %d, want %d", i, got, want)
		}
487
		if got, want := h2.Uname, v.h.Uname; got != want {
488 489
			t.Errorf("i=%d: Uname: got %q, want %q", i, got, want)
		}
490
		if got, want := h2.Gname, v.h.Gname; got != want {
491 492
			t.Errorf("i=%d: Gname: got %q, want %q", i, got, want)
		}
493
		if got, want := h2.Linkname, v.h.Linkname; got != want {
494 495
			t.Errorf("i=%d: Linkname: got %v, want %v", i, got, want)
		}
496 497
		if got, want := h2.Typeflag, v.h.Typeflag; got != want {
			t.Logf("%#v %#v", v.h, fi.Sys())
498 499
			t.Errorf("i=%d: Typeflag: got %q, want %q", i, got, want)
		}
500
		if got, want := h2.Mode, v.h.Mode; got != want {
501 502
			t.Errorf("i=%d: Mode: got %o, want %o", i, got, want)
		}
503
		if got, want := fi.Mode(), v.fm; got != want {
504 505
			t.Errorf("i=%d: fi.Mode: got %o, want %o", i, got, want)
		}
506
		if got, want := h2.AccessTime, v.h.AccessTime; got != want {
507 508
			t.Errorf("i=%d: AccessTime: got %v, want %v", i, got, want)
		}
509
		if got, want := h2.ChangeTime, v.h.ChangeTime; got != want {
510 511
			t.Errorf("i=%d: ChangeTime: got %v, want %v", i, got, want)
		}
512
		if got, want := h2.ModTime, v.h.ModTime; got != want {
513 514
			t.Errorf("i=%d: ModTime: got %v, want %v", i, got, want)
		}
515
		if sysh, ok := fi.Sys().(*Header); !ok || sysh != v.h {
516 517 518 519
			t.Errorf("i=%d: Sys didn't return original *Header", i)
		}
	}
}
520 521 522 523 524

func TestHeaderAllowedFormats(t *testing.T) {
	vectors := []struct {
		header  *Header           // Input header
		paxHdrs map[string]string // Expected PAX headers that may be needed
525
		formats Format            // Expected formats that can encode the header
526 527
	}{{
		header:  &Header{},
528
		formats: FormatUSTAR | FormatPAX | FormatGNU,
529 530
	}, {
		header:  &Header{Size: 077777777777},
531 532 533 534 535 536 537 538 539 540
		formats: FormatUSTAR | FormatPAX | FormatGNU,
	}, {
		header:  &Header{Size: 077777777777, Format: FormatUSTAR},
		formats: FormatUSTAR,
	}, {
		header:  &Header{Size: 077777777777, Format: FormatPAX},
		formats: FormatUSTAR | FormatPAX,
	}, {
		header:  &Header{Size: 077777777777, Format: FormatGNU},
		formats: FormatGNU,
541 542 543
	}, {
		header:  &Header{Size: 077777777777 + 1},
		paxHdrs: map[string]string{paxSize: "8589934592"},
544 545 546 547 548 549 550 551 552
		formats: FormatPAX | FormatGNU,
	}, {
		header:  &Header{Size: 077777777777 + 1, Format: FormatPAX},
		paxHdrs: map[string]string{paxSize: "8589934592"},
		formats: FormatPAX,
	}, {
		header:  &Header{Size: 077777777777 + 1, Format: FormatGNU},
		paxHdrs: map[string]string{paxSize: "8589934592"},
		formats: FormatGNU,
553 554
	}, {
		header:  &Header{Mode: 07777777},
555
		formats: FormatUSTAR | FormatPAX | FormatGNU,
556 557
	}, {
		header:  &Header{Mode: 07777777 + 1},
558
		formats: FormatGNU,
559 560
	}, {
		header:  &Header{Devmajor: -123},
561
		formats: FormatGNU,
562 563
	}, {
		header:  &Header{Devmajor: 1<<56 - 1},
564
		formats: FormatGNU,
565 566
	}, {
		header:  &Header{Devmajor: 1 << 56},
567
		formats: FormatUnknown,
568 569
	}, {
		header:  &Header{Devmajor: -1 << 56},
570
		formats: FormatGNU,
571 572
	}, {
		header:  &Header{Devmajor: -1<<56 - 1},
573
		formats: FormatUnknown,
574 575
	}, {
		header:  &Header{Name: "用戶名", Devmajor: -1 << 56},
576
		formats: FormatGNU,
577 578 579
	}, {
		header:  &Header{Size: math.MaxInt64},
		paxHdrs: map[string]string{paxSize: "9223372036854775807"},
580
		formats: FormatPAX | FormatGNU,
581 582 583
	}, {
		header:  &Header{Size: math.MinInt64},
		paxHdrs: map[string]string{paxSize: "-9223372036854775808"},
584
		formats: FormatUnknown,
585 586
	}, {
		header:  &Header{Uname: "0123456789abcdef0123456789abcdef"},
587
		formats: FormatUSTAR | FormatPAX | FormatGNU,
588 589 590
	}, {
		header:  &Header{Uname: "0123456789abcdef0123456789abcdefx"},
		paxHdrs: map[string]string{paxUname: "0123456789abcdef0123456789abcdefx"},
591
		formats: FormatPAX,
592 593
	}, {
		header:  &Header{Name: "foobar"},
594
		formats: FormatUSTAR | FormatPAX | FormatGNU,
595 596
	}, {
		header:  &Header{Name: strings.Repeat("a", nameSize)},
597
		formats: FormatUSTAR | FormatPAX | FormatGNU,
598 599 600
	}, {
		header:  &Header{Name: strings.Repeat("a", nameSize+1)},
		paxHdrs: map[string]string{paxPath: strings.Repeat("a", nameSize+1)},
601
		formats: FormatPAX | FormatGNU,
602 603 604
	}, {
		header:  &Header{Linkname: "用戶名"},
		paxHdrs: map[string]string{paxLinkpath: "用戶名"},
605
		formats: FormatPAX | FormatGNU,
606 607 608
	}, {
		header:  &Header{Linkname: strings.Repeat("用戶名\x00", nameSize)},
		paxHdrs: map[string]string{paxLinkpath: strings.Repeat("用戶名\x00", nameSize)},
609
		formats: FormatUnknown,
610 611 612
	}, {
		header:  &Header{Linkname: "\x00hello"},
		paxHdrs: map[string]string{paxLinkpath: "\x00hello"},
613
		formats: FormatUnknown,
614 615
	}, {
		header:  &Header{Uid: 07777777},
616
		formats: FormatUSTAR | FormatPAX | FormatGNU,
617 618 619
	}, {
		header:  &Header{Uid: 07777777 + 1},
		paxHdrs: map[string]string{paxUid: "2097152"},
620
		formats: FormatPAX | FormatGNU,
621 622
	}, {
		header:  &Header{Xattrs: nil},
623
		formats: FormatUSTAR | FormatPAX | FormatGNU,
624 625
	}, {
		header:  &Header{Xattrs: map[string]string{"foo": "bar"}},
626
		paxHdrs: map[string]string{paxSchilyXattr + "foo": "bar"},
627
		formats: FormatPAX,
628 629
	}, {
		header:  &Header{Xattrs: map[string]string{"foo": "bar"}, Format: FormatGNU},
630
		paxHdrs: map[string]string{paxSchilyXattr + "foo": "bar"},
631
		formats: FormatUnknown,
632 633
	}, {
		header:  &Header{Xattrs: map[string]string{"用戶名": "\x00hello"}},
634
		paxHdrs: map[string]string{paxSchilyXattr + "用戶名": "\x00hello"},
635
		formats: FormatPAX,
636 637
	}, {
		header:  &Header{Xattrs: map[string]string{"foo=bar": "baz"}},
638
		formats: FormatUnknown,
639 640
	}, {
		header:  &Header{Xattrs: map[string]string{"foo": ""}},
641 642
		paxHdrs: map[string]string{paxSchilyXattr + "foo": ""},
		formats: FormatPAX,
643 644
	}, {
		header:  &Header{ModTime: time.Unix(0, 0)},
645
		formats: FormatUSTAR | FormatPAX | FormatGNU,
646 647
	}, {
		header:  &Header{ModTime: time.Unix(077777777777, 0)},
648
		formats: FormatUSTAR | FormatPAX | FormatGNU,
649 650 651
	}, {
		header:  &Header{ModTime: time.Unix(077777777777+1, 0)},
		paxHdrs: map[string]string{paxMtime: "8589934592"},
652
		formats: FormatPAX | FormatGNU,
653 654 655
	}, {
		header:  &Header{ModTime: time.Unix(math.MaxInt64, 0)},
		paxHdrs: map[string]string{paxMtime: "9223372036854775807"},
656
		formats: FormatPAX | FormatGNU,
657 658 659 660
	}, {
		header:  &Header{ModTime: time.Unix(math.MaxInt64, 0), Format: FormatUSTAR},
		paxHdrs: map[string]string{paxMtime: "9223372036854775807"},
		formats: FormatUnknown,
661 662 663
	}, {
		header:  &Header{ModTime: time.Unix(-1, 0)},
		paxHdrs: map[string]string{paxMtime: "-1"},
664
		formats: FormatPAX | FormatGNU,
665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686
	}, {
		header:  &Header{ModTime: time.Unix(1, 500)},
		paxHdrs: map[string]string{paxMtime: "1.0000005"},
		formats: FormatUSTAR | FormatPAX | FormatGNU,
	}, {
		header:  &Header{ModTime: time.Unix(1, 0)},
		formats: FormatUSTAR | FormatPAX | FormatGNU,
	}, {
		header:  &Header{ModTime: time.Unix(1, 0), Format: FormatPAX},
		formats: FormatUSTAR | FormatPAX,
	}, {
		header:  &Header{ModTime: time.Unix(1, 500), Format: FormatUSTAR},
		paxHdrs: map[string]string{paxMtime: "1.0000005"},
		formats: FormatUSTAR,
	}, {
		header:  &Header{ModTime: time.Unix(1, 500), Format: FormatPAX},
		paxHdrs: map[string]string{paxMtime: "1.0000005"},
		formats: FormatPAX,
	}, {
		header:  &Header{ModTime: time.Unix(1, 500), Format: FormatGNU},
		paxHdrs: map[string]string{paxMtime: "1.0000005"},
		formats: FormatGNU,
687 688 689
	}, {
		header:  &Header{ModTime: time.Unix(-1, 500)},
		paxHdrs: map[string]string{paxMtime: "-0.9999995"},
690
		formats: FormatPAX | FormatGNU,
691 692 693
	}, {
		header:  &Header{ModTime: time.Unix(-1, 500), Format: FormatGNU},
		paxHdrs: map[string]string{paxMtime: "-0.9999995"},
694
		formats: FormatGNU,
695 696 697
	}, {
		header:  &Header{AccessTime: time.Unix(0, 0)},
		paxHdrs: map[string]string{paxAtime: "0"},
698
		formats: FormatPAX | FormatGNU,
699 700 701 702 703 704 705 706 707 708 709 710
	}, {
		header:  &Header{AccessTime: time.Unix(0, 0), Format: FormatUSTAR},
		paxHdrs: map[string]string{paxAtime: "0"},
		formats: FormatUnknown,
	}, {
		header:  &Header{AccessTime: time.Unix(0, 0), Format: FormatPAX},
		paxHdrs: map[string]string{paxAtime: "0"},
		formats: FormatPAX,
	}, {
		header:  &Header{AccessTime: time.Unix(0, 0), Format: FormatGNU},
		paxHdrs: map[string]string{paxAtime: "0"},
		formats: FormatGNU,
711 712 713
	}, {
		header:  &Header{AccessTime: time.Unix(-123, 0)},
		paxHdrs: map[string]string{paxAtime: "-123"},
714
		formats: FormatPAX | FormatGNU,
715 716 717 718
	}, {
		header:  &Header{AccessTime: time.Unix(-123, 0), Format: FormatPAX},
		paxHdrs: map[string]string{paxAtime: "-123"},
		formats: FormatPAX,
719 720 721
	}, {
		header:  &Header{ChangeTime: time.Unix(123, 456)},
		paxHdrs: map[string]string{paxCtime: "123.000000456"},
722
		formats: FormatPAX | FormatGNU,
723
	}, {
724
		header:  &Header{ChangeTime: time.Unix(123, 456), Format: FormatUSTAR},
725 726
		paxHdrs: map[string]string{paxCtime: "123.000000456"},
		formats: FormatUnknown,
727 728 729 730 731 732 733 734
	}, {
		header:  &Header{ChangeTime: time.Unix(123, 456), Format: FormatGNU},
		paxHdrs: map[string]string{paxCtime: "123.000000456"},
		formats: FormatGNU,
	}, {
		header:  &Header{ChangeTime: time.Unix(123, 456), Format: FormatPAX},
		paxHdrs: map[string]string{paxCtime: "123.000000456"},
		formats: FormatPAX,
735 736 737 738 739 740 741 742 743
	}, {
		header:  &Header{Name: "foo/", Typeflag: TypeDir},
		formats: FormatUSTAR | FormatPAX | FormatGNU,
	}, {
		header:  &Header{Name: "foo/", Typeflag: TypeReg},
		formats: FormatUnknown,
	}, {
		header:  &Header{Name: "foo/", Typeflag: TypeSymlink},
		formats: FormatUSTAR | FormatPAX | FormatGNU,
744 745 746
	}}

	for i, v := range vectors {
747
		formats, paxHdrs, err := v.header.allowedFormats()
748
		if formats != v.formats {
749
			t.Errorf("test %d, allowedFormats(): got %v, want %v", i, formats, v.formats)
750
		}
751
		if formats&FormatPAX > 0 && !reflect.DeepEqual(paxHdrs, v.paxHdrs) && !(len(paxHdrs) == 0 && len(v.paxHdrs) == 0) {
752 753 754 755 756 757 758
			t.Errorf("test %d, allowedFormats():\ngot  %v\nwant %s", i, paxHdrs, v.paxHdrs)
		}
		if (formats != FormatUnknown) && (err != nil) {
			t.Errorf("test %d, unexpected error: %v", i, err)
		}
		if (formats == FormatUnknown) && (err == nil) {
			t.Errorf("test %d, got nil-error, want non-nil error", i)
759 760 761
		}
	}
}
762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854

func Benchmark(b *testing.B) {
	type file struct {
		hdr  *Header
		body []byte
	}

	vectors := []struct {
		label string
		files []file
	}{{
		"USTAR",
		[]file{{
			&Header{Name: "bar", Mode: 0640, Size: int64(3)},
			[]byte("foo"),
		}, {
			&Header{Name: "world", Mode: 0640, Size: int64(5)},
			[]byte("hello"),
		}},
	}, {
		"GNU",
		[]file{{
			&Header{Name: "bar", Mode: 0640, Size: int64(3), Devmajor: -1},
			[]byte("foo"),
		}, {
			&Header{Name: "world", Mode: 0640, Size: int64(5), Devmajor: -1},
			[]byte("hello"),
		}},
	}, {
		"PAX",
		[]file{{
			&Header{Name: "bar", Mode: 0640, Size: int64(3), Xattrs: map[string]string{"foo": "bar"}},
			[]byte("foo"),
		}, {
			&Header{Name: "world", Mode: 0640, Size: int64(5), Xattrs: map[string]string{"foo": "bar"}},
			[]byte("hello"),
		}},
	}}

	b.Run("Writer", func(b *testing.B) {
		for _, v := range vectors {
			b.Run(v.label, func(b *testing.B) {
				b.ReportAllocs()
				for i := 0; i < b.N; i++ {
					// Writing to ioutil.Discard because we want to
					// test purely the writer code and not bring in disk performance into this.
					tw := NewWriter(ioutil.Discard)
					for _, file := range v.files {
						if err := tw.WriteHeader(file.hdr); err != nil {
							b.Errorf("unexpected WriteHeader error: %v", err)
						}
						if _, err := tw.Write(file.body); err != nil {
							b.Errorf("unexpected Write error: %v", err)
						}
					}
					if err := tw.Close(); err != nil {
						b.Errorf("unexpected Close error: %v", err)
					}
				}
			})
		}
	})

	b.Run("Reader", func(b *testing.B) {
		for _, v := range vectors {
			var buf bytes.Buffer
			var r bytes.Reader

			// Write the archive to a byte buffer.
			tw := NewWriter(&buf)
			for _, file := range v.files {
				tw.WriteHeader(file.hdr)
				tw.Write(file.body)
			}
			tw.Close()
			b.Run(v.label, func(b *testing.B) {
				b.ReportAllocs()
				// Read from the byte buffer.
				for i := 0; i < b.N; i++ {
					r.Reset(buf.Bytes())
					tr := NewReader(&r)
					if _, err := tr.Next(); err != nil {
						b.Errorf("unexpected Next error: %v", err)
					}
					if _, err := io.Copy(ioutil.Discard, tr); err != nil {
						b.Errorf("unexpected Copy error : %v", err)
					}
				}
			})
		}
	})

}