aboutsummaryrefslogtreecommitdiff
path: root/hotline/files.go
blob: e9f7b4fb8172d7dad2b14a83de25867d7a6a862f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
package hotline

import (
	"encoding/binary"
	"errors"
	"fmt"
	"io"
	"io/fs"
	"os"
	"path/filepath"
	"regexp"
	"strings"
)

func FileTypeFromFilename(filename string) fileType {
	fileExt := strings.ToLower(filepath.Ext(filename))
	ft, ok := fileTypes[fileExt]
	if ok {
		return ft
	}
	return defaultFileType
}

func fileTypeFromInfo(info fs.FileInfo) (ft fileType, err error) {
	if info.IsDir() {
		ft.CreatorCode = "n/a "
		ft.TypeCode = "fldr"
	} else {
		ft = FileTypeFromFilename(info.Name())
	}

	return ft, nil
}

const maxFileSize = 4294967296

func GetFileNameList(path string, ignoreList []string) (fields []Field, err error) {
	files, err := os.ReadDir(path)
	if err != nil {
		return fields, fmt.Errorf("error reading path: %s: %w", path, err)
	}

	for _, file := range files {
		var fnwi FileNameWithInfo

		if ignoreFile(file.Name(), ignoreList) {
			continue
		}

		fileCreator := make([]byte, 4)

		fileInfo, err := file.Info()
		if err != nil {
			return fields, fmt.Errorf("error getting file info: %s: %w", file.Name(), err)
		}

		// Check if path is a symlink.  If so, follow it.
		if fileInfo.Mode()&os.ModeSymlink != 0 {
			resolvedPath, err := os.Readlink(filepath.Join(path, file.Name()))
			if err != nil {
				return fields, fmt.Errorf("error following symlink: %s: %w", resolvedPath, err)
			}

			rFile, err := os.Stat(resolvedPath)
			if errors.Is(err, os.ErrNotExist) {
				continue
			}
			if err != nil {
				return fields, err
			}

			if rFile.IsDir() {
				dir, err := os.ReadDir(filepath.Join(path, file.Name()))
				if err != nil {
					return fields, err
				}

				var c uint32
				for _, f := range dir {
					if !ignoreFile(f.Name(), ignoreList) {
						c += 1
					}
				}

				binary.BigEndian.PutUint32(fnwi.FileSize[:], c)
				copy(fnwi.Type[:], "fldr")
				copy(fnwi.Creator[:], fileCreator)
			} else {
				binary.BigEndian.PutUint32(fnwi.FileSize[:], uint32(rFile.Size()))
				copy(fnwi.Type[:], FileTypeFromFilename(rFile.Name()).TypeCode)
				copy(fnwi.Creator[:], FileTypeFromFilename(rFile.Name()).CreatorCode)
			}
		} else if file.IsDir() {
			dir, err := os.ReadDir(filepath.Join(path, file.Name()))
			if err != nil {
				return fields, fmt.Errorf("readDir: %w", err)
			}

			var c uint32
			for _, f := range dir {
				if !ignoreFile(f.Name(), ignoreList) {
					c += 1
				}
			}

			binary.BigEndian.PutUint32(fnwi.FileSize[:], c)
			copy(fnwi.Type[:], "fldr")
			copy(fnwi.Creator[:], fileCreator)
		} else {
			// the Hotline protocol does not support file sizes > 4GiB due to the 4 byte field size, so skip them
			if fileInfo.Size() > maxFileSize {
				continue
			}

			hlFile, err := NewFileWrapper(&OSFileStore{}, path+"/"+file.Name(), 0)
			if err != nil {
				return nil, fmt.Errorf("NewFileWrapper: %w", err)
			}

			copy(fnwi.FileSize[:], hlFile.TotalSize())
			copy(fnwi.Type[:], hlFile.Ffo.FlatFileInformationFork.TypeSignature[:])
			copy(fnwi.Creator[:], hlFile.Ffo.FlatFileInformationFork.CreatorSignature[:])
		}

		strippedName := strings.ReplaceAll(file.Name(), ".incomplete", "")
		strippedName, err = txtEncoder.String(strippedName)
		if err != nil {
			continue
		}

		nameSize := make([]byte, 2)
		binary.BigEndian.PutUint16(nameSize, uint16(len(strippedName)))
		copy(fnwi.NameSize[:], nameSize)

		fnwi.Name = []byte(strippedName)

		b, err := io.ReadAll(&fnwi)
		if err != nil {
			return nil, fmt.Errorf("error io.ReadAll: %w", err)
		}
		fields = append(fields, NewField(FieldFileNameWithInfo, b))
	}

	return fields, nil
}

func CalcTotalSize(filePath string) ([]byte, error) {
	var totalSize uint32
	err := filepath.Walk(filePath, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}

		if info.IsDir() {
			return nil
		}

		totalSize += uint32(info.Size())

		return nil
	})
	if err != nil {
		return nil, err
	}

	bs := make([]byte, 4)
	binary.BigEndian.PutUint32(bs, totalSize)

	return bs, nil
}

// CalcItemCount recurses through a file path and counts the number of non-hidden files.
func CalcItemCount(filePath string) ([]byte, error) {
	var itemCount uint16

	// Walk the directory and count items
	err := filepath.Walk(filePath, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}

		// Skip hidden files
		if !strings.HasPrefix(info.Name(), ".") {
			itemCount++
		}

		return nil
	})
	if err != nil {
		return nil, err
	}

	bs := make([]byte, 2)
	binary.BigEndian.PutUint16(bs, itemCount-1)

	return bs, nil
}

func EncodeFilePath(filePath string) []byte {
	pathSections := strings.Split(filePath, "/")
	pathItemCount := make([]byte, 2)
	binary.BigEndian.PutUint16(pathItemCount, uint16(len(pathSections)))

	bytes := pathItemCount

	for _, section := range pathSections {
		bytes = append(bytes, []byte{0, 0}...)

		pathStr := []byte(section)
		bytes = append(bytes, byte(len(pathStr)))
		bytes = append(bytes, pathStr...)
	}

	return bytes
}

func ignoreFile(fileName string, ignoreList []string) bool {
	// skip files that match any regular expression present in the IgnoreFiles list
	matchIgnoreFilter := 0
	for _, pattern := range ignoreList {
		if match, _ := regexp.MatchString(pattern, fileName); match {
			matchIgnoreFilter += 1
		}
	}
	return matchIgnoreFilter > 0
}