1// +build windows
2
3package winio
4
5import (
6	"io/ioutil"
7	"os"
8	"reflect"
9	"syscall"
10	"testing"
11	"unsafe"
12)
13
14var (
15	testEas = []ExtendedAttribute{
16		{Name: "foo", Value: []byte("bar")},
17		{Name: "fizz", Value: []byte("buzz")},
18	}
19
20	testEasEncoded   = []byte{16, 0, 0, 0, 0, 3, 3, 0, 102, 111, 111, 0, 98, 97, 114, 0, 0, 0, 0, 0, 0, 4, 4, 0, 102, 105, 122, 122, 0, 98, 117, 122, 122, 0, 0, 0}
21	testEasNotPadded = testEasEncoded[0 : len(testEasEncoded)-3]
22	testEasTruncated = testEasEncoded[0:20]
23)
24
25func Test_RoundTripEas(t *testing.T) {
26	b, err := EncodeExtendedAttributes(testEas)
27	if err != nil {
28		t.Fatal(err)
29	}
30	if !reflect.DeepEqual(testEasEncoded, b) {
31		t.Fatalf("encoded mismatch %v %v", testEasEncoded, b)
32	}
33	eas, err := DecodeExtendedAttributes(b)
34	if err != nil {
35		t.Fatal(err)
36	}
37	if !reflect.DeepEqual(testEas, eas) {
38		t.Fatalf("mismatch %+v %+v", testEas, eas)
39	}
40}
41
42func Test_EasDontNeedPaddingAtEnd(t *testing.T) {
43	eas, err := DecodeExtendedAttributes(testEasNotPadded)
44	if err != nil {
45		t.Fatal(err)
46	}
47	if !reflect.DeepEqual(testEas, eas) {
48		t.Fatalf("mismatch %+v %+v", testEas, eas)
49	}
50}
51
52func Test_TruncatedEasFailCorrectly(t *testing.T) {
53	_, err := DecodeExtendedAttributes(testEasTruncated)
54	if err == nil {
55		t.Fatal("expected error")
56	}
57}
58
59func Test_NilEasEncodeAndDecodeAsNil(t *testing.T) {
60	b, err := EncodeExtendedAttributes(nil)
61	if err != nil {
62		t.Fatal(err)
63	}
64	if len(b) != 0 {
65		t.Fatal("expected empty")
66	}
67	eas, err := DecodeExtendedAttributes(nil)
68	if err != nil {
69		t.Fatal(err)
70	}
71	if len(eas) != 0 {
72		t.Fatal("expected empty")
73	}
74}
75
76// Test_SetFileEa makes sure that the test buffer is actually parsable by NtSetEaFile.
77func Test_SetFileEa(t *testing.T) {
78	f, err := ioutil.TempFile("", "winio")
79	if err != nil {
80		t.Fatal(err)
81	}
82	defer os.Remove(f.Name())
83	defer f.Close()
84	ntdll := syscall.MustLoadDLL("ntdll.dll")
85	ntSetEaFile := ntdll.MustFindProc("NtSetEaFile")
86	var iosb [2]uintptr
87	r, _, _ := ntSetEaFile.Call(f.Fd(), uintptr(unsafe.Pointer(&iosb[0])), uintptr(unsafe.Pointer(&testEasEncoded[0])), uintptr(len(testEasEncoded)))
88	if r != 0 {
89		t.Fatalf("NtSetEaFile failed with %08x", r)
90	}
91}
92