1// +build windows
2
3package winio
4
5import (
6	"encoding/binary"
7	"errors"
8	"fmt"
9	"io"
10	"io/ioutil"
11	"os"
12	"runtime"
13	"syscall"
14	"unicode/utf16"
15)
16
17//sys backupRead(h syscall.Handle, b []byte, bytesRead *uint32, abort bool, processSecurity bool, context *uintptr) (err error) = BackupRead
18//sys backupWrite(h syscall.Handle, b []byte, bytesWritten *uint32, abort bool, processSecurity bool, context *uintptr) (err error) = BackupWrite
19
20const (
21	BackupData = uint32(iota + 1)
22	BackupEaData
23	BackupSecurity
24	BackupAlternateData
25	BackupLink
26	BackupPropertyData
27	BackupObjectId
28	BackupReparseData
29	BackupSparseBlock
30	BackupTxfsData
31)
32
33const (
34	StreamSparseAttributes = uint32(8)
35)
36
37const (
38	WRITE_DAC              = 0x40000
39	WRITE_OWNER            = 0x80000
40	ACCESS_SYSTEM_SECURITY = 0x1000000
41)
42
43// BackupHeader represents a backup stream of a file.
44type BackupHeader struct {
45	Id         uint32 // The backup stream ID
46	Attributes uint32 // Stream attributes
47	Size       int64  // The size of the stream in bytes
48	Name       string // The name of the stream (for BackupAlternateData only).
49	Offset     int64  // The offset of the stream in the file (for BackupSparseBlock only).
50}
51
52type win32StreamId struct {
53	StreamId   uint32
54	Attributes uint32
55	Size       uint64
56	NameSize   uint32
57}
58
59// BackupStreamReader reads from a stream produced by the BackupRead Win32 API and produces a series
60// of BackupHeader values.
61type BackupStreamReader struct {
62	r         io.Reader
63	bytesLeft int64
64}
65
66// NewBackupStreamReader produces a BackupStreamReader from any io.Reader.
67func NewBackupStreamReader(r io.Reader) *BackupStreamReader {
68	return &BackupStreamReader{r, 0}
69}
70
71// Next returns the next backup stream and prepares for calls to Read(). It skips the remainder of the current stream if
72// it was not completely read.
73func (r *BackupStreamReader) Next() (*BackupHeader, error) {
74	if r.bytesLeft > 0 {
75		if s, ok := r.r.(io.Seeker); ok {
76			// Make sure Seek on io.SeekCurrent sometimes succeeds
77			// before trying the actual seek.
78			if _, err := s.Seek(0, io.SeekCurrent); err == nil {
79				if _, err = s.Seek(r.bytesLeft, io.SeekCurrent); err != nil {
80					return nil, err
81				}
82				r.bytesLeft = 0
83			}
84		}
85		if _, err := io.Copy(ioutil.Discard, r); err != nil {
86			return nil, err
87		}
88	}
89	var wsi win32StreamId
90	if err := binary.Read(r.r, binary.LittleEndian, &wsi); err != nil {
91		return nil, err
92	}
93	hdr := &BackupHeader{
94		Id:         wsi.StreamId,
95		Attributes: wsi.Attributes,
96		Size:       int64(wsi.Size),
97	}
98	if wsi.NameSize != 0 {
99		name := make([]uint16, int(wsi.NameSize/2))
100		if err := binary.Read(r.r, binary.LittleEndian, name); err != nil {
101			return nil, err
102		}
103		hdr.Name = syscall.UTF16ToString(name)
104	}
105	if wsi.StreamId == BackupSparseBlock {
106		if err := binary.Read(r.r, binary.LittleEndian, &hdr.Offset); err != nil {
107			return nil, err
108		}
109		hdr.Size -= 8
110	}
111	r.bytesLeft = hdr.Size
112	return hdr, nil
113}
114
115// Read reads from the current backup stream.
116func (r *BackupStreamReader) Read(b []byte) (int, error) {
117	if r.bytesLeft == 0 {
118		return 0, io.EOF
119	}
120	if int64(len(b)) > r.bytesLeft {
121		b = b[:r.bytesLeft]
122	}
123	n, err := r.r.Read(b)
124	r.bytesLeft -= int64(n)
125	if err == io.EOF {
126		err = io.ErrUnexpectedEOF
127	} else if r.bytesLeft == 0 && err == nil {
128		err = io.EOF
129	}
130	return n, err
131}
132
133// BackupStreamWriter writes a stream compatible with the BackupWrite Win32 API.
134type BackupStreamWriter struct {
135	w         io.Writer
136	bytesLeft int64
137}
138
139// NewBackupStreamWriter produces a BackupStreamWriter on top of an io.Writer.
140func NewBackupStreamWriter(w io.Writer) *BackupStreamWriter {
141	return &BackupStreamWriter{w, 0}
142}
143
144// WriteHeader writes the next backup stream header and prepares for calls to Write().
145func (w *BackupStreamWriter) WriteHeader(hdr *BackupHeader) error {
146	if w.bytesLeft != 0 {
147		return fmt.Errorf("missing %d bytes", w.bytesLeft)
148	}
149	name := utf16.Encode([]rune(hdr.Name))
150	wsi := win32StreamId{
151		StreamId:   hdr.Id,
152		Attributes: hdr.Attributes,
153		Size:       uint64(hdr.Size),
154		NameSize:   uint32(len(name) * 2),
155	}
156	if hdr.Id == BackupSparseBlock {
157		// Include space for the int64 block offset
158		wsi.Size += 8
159	}
160	if err := binary.Write(w.w, binary.LittleEndian, &wsi); err != nil {
161		return err
162	}
163	if len(name) != 0 {
164		if err := binary.Write(w.w, binary.LittleEndian, name); err != nil {
165			return err
166		}
167	}
168	if hdr.Id == BackupSparseBlock {
169		if err := binary.Write(w.w, binary.LittleEndian, hdr.Offset); err != nil {
170			return err
171		}
172	}
173	w.bytesLeft = hdr.Size
174	return nil
175}
176
177// Write writes to the current backup stream.
178func (w *BackupStreamWriter) Write(b []byte) (int, error) {
179	if w.bytesLeft < int64(len(b)) {
180		return 0, fmt.Errorf("too many bytes by %d", int64(len(b))-w.bytesLeft)
181	}
182	n, err := w.w.Write(b)
183	w.bytesLeft -= int64(n)
184	return n, err
185}
186
187// BackupFileReader provides an io.ReadCloser interface on top of the BackupRead Win32 API.
188type BackupFileReader struct {
189	f               *os.File
190	includeSecurity bool
191	ctx             uintptr
192}
193
194// NewBackupFileReader returns a new BackupFileReader from a file handle. If includeSecurity is true,
195// Read will attempt to read the security descriptor of the file.
196func NewBackupFileReader(f *os.File, includeSecurity bool) *BackupFileReader {
197	r := &BackupFileReader{f, includeSecurity, 0}
198	return r
199}
200
201// Read reads a backup stream from the file by calling the Win32 API BackupRead().
202func (r *BackupFileReader) Read(b []byte) (int, error) {
203	var bytesRead uint32
204	err := backupRead(syscall.Handle(r.f.Fd()), b, &bytesRead, false, r.includeSecurity, &r.ctx)
205	if err != nil {
206		return 0, &os.PathError{"BackupRead", r.f.Name(), err}
207	}
208	runtime.KeepAlive(r.f)
209	if bytesRead == 0 {
210		return 0, io.EOF
211	}
212	return int(bytesRead), nil
213}
214
215// Close frees Win32 resources associated with the BackupFileReader. It does not close
216// the underlying file.
217func (r *BackupFileReader) Close() error {
218	if r.ctx != 0 {
219		backupRead(syscall.Handle(r.f.Fd()), nil, nil, true, false, &r.ctx)
220		runtime.KeepAlive(r.f)
221		r.ctx = 0
222	}
223	return nil
224}
225
226// BackupFileWriter provides an io.WriteCloser interface on top of the BackupWrite Win32 API.
227type BackupFileWriter struct {
228	f               *os.File
229	includeSecurity bool
230	ctx             uintptr
231}
232
233// NewBackupFileWriter returns a new BackupFileWriter from a file handle. If includeSecurity is true,
234// Write() will attempt to restore the security descriptor from the stream.
235func NewBackupFileWriter(f *os.File, includeSecurity bool) *BackupFileWriter {
236	w := &BackupFileWriter{f, includeSecurity, 0}
237	return w
238}
239
240// Write restores a portion of the file using the provided backup stream.
241func (w *BackupFileWriter) Write(b []byte) (int, error) {
242	var bytesWritten uint32
243	err := backupWrite(syscall.Handle(w.f.Fd()), b, &bytesWritten, false, w.includeSecurity, &w.ctx)
244	if err != nil {
245		return 0, &os.PathError{"BackupWrite", w.f.Name(), err}
246	}
247	runtime.KeepAlive(w.f)
248	if int(bytesWritten) != len(b) {
249		return int(bytesWritten), errors.New("not all bytes could be written")
250	}
251	return len(b), nil
252}
253
254// Close frees Win32 resources associated with the BackupFileWriter. It does not
255// close the underlying file.
256func (w *BackupFileWriter) Close() error {
257	if w.ctx != 0 {
258		backupWrite(syscall.Handle(w.f.Fd()), nil, nil, true, false, &w.ctx)
259		runtime.KeepAlive(w.f)
260		w.ctx = 0
261	}
262	return nil
263}
264
265// OpenForBackup opens a file or directory, potentially skipping access checks if the backup
266// or restore privileges have been acquired.
267//
268// If the file opened was a directory, it cannot be used with Readdir().
269func OpenForBackup(path string, access uint32, share uint32, createmode uint32) (*os.File, error) {
270	winPath, err := syscall.UTF16FromString(path)
271	if err != nil {
272		return nil, err
273	}
274	h, err := syscall.CreateFile(&winPath[0], access, share, nil, createmode, syscall.FILE_FLAG_BACKUP_SEMANTICS|syscall.FILE_FLAG_OPEN_REPARSE_POINT, 0)
275	if err != nil {
276		err = &os.PathError{Op: "open", Path: path, Err: err}
277		return nil, err
278	}
279	return os.NewFile(uintptr(h), path), nil
280}
281