-
Notifications
You must be signed in to change notification settings - Fork 98
/
handle_dirs.go
421 lines (333 loc) · 10.1 KB
/
handle_dirs.go
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
package ftpserver
import (
"errors"
"fmt"
"io"
"io/fs"
"os"
"path"
"strings"
"time"
"github.com/spf13/afero"
)
// thrown if listing with a filePath isn't supported (MLSD, NLST)
var errFileList = errors.New("listing a file isn't allowed")
// the order matter, put parameters with more characters first
var supportedlistArgs = []string{"-al", "-la", "-a", "-l"} //nolint:gochecknoglobals
func (c *clientHandler) absPath(p string) string {
if path.IsAbs(p) {
return path.Clean(p)
}
return path.Join(c.Path(), p)
}
// getRelativePath returns the specified path as relative to the
// current working directory. The specified path must be cleaned
func (c *clientHandler) getRelativePath(inputPath string) string {
var builder strings.Builder
base := c.Path()
for {
if base == inputPath {
return builder.String()
}
if !strings.HasSuffix(base, "/") {
base += "/"
}
if strings.HasPrefix(inputPath, base) {
builder.WriteString(strings.TrimPrefix(inputPath, base))
return builder.String()
}
if base == "/" || base == "./" {
return inputPath
}
builder.WriteString("../")
base = path.Dir(path.Clean(base))
}
}
func (c *clientHandler) handleCWD(param string) error {
pathAbsolute := c.absPath(param)
if stat, err := c.driver.Stat(pathAbsolute); err == nil {
if stat.IsDir() {
c.SetPath(pathAbsolute)
c.writeMessage(StatusFileOK, "CD worked on "+pathAbsolute)
} else {
c.writeMessage(StatusActionNotTaken, fmt.Sprintf("Can't change directory to %s: Not a Directory", pathAbsolute))
}
} else {
c.writeMessage(StatusActionNotTaken, fmt.Sprintf("CD issue: %v", err))
}
return nil
}
func (c *clientHandler) handleMKD(param string) error {
pathAbsolute := c.absPath(param)
if err := c.driver.Mkdir(pathAbsolute, 0o755); err == nil {
// handleMKD confirms to "quote-doubling"
// https://tools.ietf.org/html/rfc959 , page 63
c.writeMessage(StatusPathCreated, fmt.Sprintf(`Created dir "%s"`, quoteDoubling(pathAbsolute)))
} else {
c.writeMessage(StatusActionNotTaken, fmt.Sprintf(`Could not create "%s" : %v`, quoteDoubling(pathAbsolute), err))
}
return nil
}
func (c *clientHandler) handleMKDIR(params string) {
if params == "" {
c.writeMessage(StatusSyntaxErrorNotRecognised, "Missing path")
return
}
p := c.absPath(params)
if err := c.driver.MkdirAll(p, 0o755); err == nil {
c.writeMessage(StatusFileOK, "Created dir "+p)
} else {
c.writeMessage(StatusActionNotTaken, fmt.Sprintf("Couldn't create dir %s: %v", p, err))
}
}
func (c *clientHandler) handleRMD(param string) error {
var err error
pathAbsolute := c.absPath(param)
if rmd, ok := c.driver.(ClientDriverExtensionRemoveDir); ok {
err = rmd.RemoveDir(pathAbsolute)
} else {
err = c.driver.Remove(pathAbsolute)
}
if err == nil {
c.writeMessage(StatusFileOK, "Deleted dir "+pathAbsolute)
} else {
c.writeMessage(StatusActionNotTaken, fmt.Sprintf("Could not delete dir %s: %v", pathAbsolute, err))
}
return nil
}
func (c *clientHandler) handleRMDIR(params string) {
if params == "" {
c.writeMessage(StatusSyntaxErrorNotRecognised, "Missing path")
return
}
p := c.absPath(params)
if err := c.driver.RemoveAll(p); err == nil {
c.writeMessage(StatusFileOK, "Removed dir "+p)
} else {
c.writeMessage(StatusActionNotTaken, fmt.Sprintf("Couldn't remove dir %s: %v", p, err))
}
}
func (c *clientHandler) handleCDUP(_ string) error {
parent, _ := path.Split(c.Path())
if parent != "/" && strings.HasSuffix(parent, "/") {
parent = parent[0 : len(parent)-1]
}
if _, err := c.driver.Stat(parent); err == nil {
c.SetPath(parent)
c.writeMessage(StatusFileOK, "CDUP worked on "+parent)
} else {
c.writeMessage(StatusActionNotTaken, fmt.Sprintf("CDUP issue: %v", err))
}
return nil
}
func (c *clientHandler) handlePWD(_ string) error {
c.writeMessage(StatusPathCreated, fmt.Sprintf(`"%s" is the current directory`, quoteDoubling(c.Path())))
return nil
}
func (c *clientHandler) checkLISTArgs(args string) string {
result := args
param := strings.ToLower(args)
for _, arg := range supportedlistArgs {
if strings.HasPrefix(param, arg) {
// a check for a non-existent directory error is more appropriate here
// but we cannot assume that the driver implementation will return an
// os.IsNotExist error.
if _, err := c.driver.Stat(args); err != nil {
params := strings.SplitN(args, " ", 2)
if len(params) == 1 {
result = ""
} else {
result = params[1]
}
}
}
}
return result
}
func (c *clientHandler) handleLIST(param string) error {
info := fmt.Sprintf("LIST %v", param)
if files, _, err := c.getFileList(param, true); err == nil || errors.Is(err, io.EOF) {
if tr, errTr := c.TransferOpen(info); errTr == nil {
err = c.dirTransferLIST(tr, files)
c.TransferClose(err)
return nil
}
} else {
if !c.isCommandAborted() {
c.writeMessage(StatusFileActionNotTaken, fmt.Sprintf("Could not list: %v", err))
}
}
return nil
}
func (c *clientHandler) handleNLST(param string) error {
info := fmt.Sprintf("NLST %v", param)
if files, parentDir, err := c.getFileList(param, true); err == nil || errors.Is(err, io.EOF) {
if tr, errTrOpen := c.TransferOpen(info); errTrOpen == nil {
err = c.dirTransferNLST(tr, files, parentDir)
c.TransferClose(err)
return nil
}
} else {
if !c.isCommandAborted() {
c.writeMessage(StatusFileActionNotTaken, fmt.Sprintf("Could not list: %v", err))
}
}
return nil
}
func (c *clientHandler) dirTransferNLST(writer io.Writer, files []os.FileInfo, parentDir string) error {
if len(files) == 0 {
_, err := writer.Write([]byte(""))
if err != nil {
err = newNetworkError("couldn't send NLST data", err)
}
return err
}
for _, file := range files {
// Based on RFC 959 NLST is intended to return information that can be used
// by a program to further process the files automatically.
// So we return paths relative to the current working directory
if _, err := fmt.Fprintf(writer, "%s\r\n", path.Join(c.getRelativePath(parentDir), file.Name())); err != nil {
return newNetworkError("couldn't send NLST data", err)
}
}
return nil
}
func (c *clientHandler) handleMLSD(param string) error {
if c.server.settings.DisableMLSD && !c.isCommandAborted() {
c.writeMessage(StatusSyntaxErrorNotRecognised, "MLSD has been disabled")
return nil
}
info := fmt.Sprintf("MLSD %v", param)
if files, _, err := c.getFileList(param, false); err == nil || errors.Is(err, io.EOF) {
if tr, errTr := c.TransferOpen(info); errTr == nil {
err = c.dirTransferMLSD(tr, files)
c.TransferClose(err)
return nil
}
} else {
if !c.isCommandAborted() {
c.writeMessage(StatusActionNotTaken, fmt.Sprintf("Could not list: %v", err))
}
}
return nil
}
const (
dateFormatStatTime = "Jan _2 15:04" // LIST date formatting with hour and minute
dateFormatStatYear = "Jan _2 2006" // LIST date formatting with year
dateFormatStatOldSwitch = time.Hour * 24 * 30 * 6 // 6 months ago
dateFormatMLSD = "20060102150405" // MLSD date formatting
fakeUser = "ftp"
fakeGroup = "ftp"
)
func (c *clientHandler) fileStat(file os.FileInfo) string {
modTime := file.ModTime()
var dateFormat string
if c.connectedAt.Sub(modTime) > dateFormatStatOldSwitch {
dateFormat = dateFormatStatYear
} else {
dateFormat = dateFormatStatTime
}
return fmt.Sprintf(
"%s 1 %s %s %12d %s %s",
file.Mode(),
fakeUser,
fakeGroup,
file.Size(),
file.ModTime().Format(dateFormat),
file.Name(),
)
}
// fclairamb (2018-02-13): #64: Removed extra empty line
func (c *clientHandler) dirTransferLIST(writer io.Writer, files []os.FileInfo) error {
if len(files) == 0 {
_, err := writer.Write([]byte(""))
if err != nil {
err = newNetworkError("error writing LIST entry", err)
}
return err
}
for _, file := range files {
if _, err := fmt.Fprintf(writer, "%s\r\n", c.fileStat(file)); err != nil {
return fmt.Errorf("error writing LIST entry: %w", err)
}
}
return nil
}
// fclairamb (2018-02-13): #64: Removed extra empty line
func (c *clientHandler) dirTransferMLSD(writer io.Writer, files []os.FileInfo) error {
if len(files) == 0 {
_, err := writer.Write([]byte(""))
if err != nil {
err = newNetworkError("error writing MLSD entry", err)
}
return err
}
for _, file := range files {
if err := c.writeMLSxEntry(writer, file); err != nil {
return err
}
}
return nil
}
func (c *clientHandler) writeMLSxEntry(writer io.Writer, file os.FileInfo) error {
var listType string
if file.IsDir() {
listType = "dir"
} else {
listType = "file"
}
_, err := fmt.Fprintf(
writer,
"Type=%s;Size=%d;Modify=%s; %s\r\n",
listType,
file.Size(),
file.ModTime().UTC().Format(dateFormatMLSD),
file.Name(),
)
if err != nil {
err = fmt.Errorf("error writing MLSD entry: %w", err)
}
return err
}
func (c *clientHandler) getFileList(param string, filePathAllowed bool) ([]os.FileInfo, string, error) {
if !c.server.settings.DisableLISTArgs {
param = c.checkLISTArgs(param)
}
// directory or filePath
listPath := c.absPath(param)
c.SetListPath(listPath)
// return list of single file if directoryPath points to file and filePathAllowed
info, err := c.driver.Stat(listPath)
if err != nil {
return nil, "", newFileAccessError("couldn't stat", err)
}
if !info.IsDir() {
if filePathAllowed {
return []os.FileInfo{info}, path.Dir(c.getListPath()), nil
}
return nil, "", errFileList
}
var files []fs.FileInfo
if fileList, ok := c.driver.(ClientDriverExtensionFileList); ok {
files, err = fileList.ReadDir(listPath)
return files, c.getListPath(), err
}
directory, errOpenFile := c.driver.Open(listPath)
if errOpenFile != nil {
return nil, "", newFileAccessError("couldn't open directory", errOpenFile)
}
defer c.closeDirectory(listPath, directory)
files, err = directory.Readdir(-1)
return files, c.getListPath(), err
}
func (c *clientHandler) closeDirectory(directoryPath string, directory afero.File) {
if errClose := directory.Close(); errClose != nil {
c.logger.Error("Couldn't close directory", "err", errClose, "directory", directoryPath)
}
}
func quoteDoubling(s string) string {
if !strings.Contains(s, "\"") {
return s
}
return strings.ReplaceAll(s, "\"", `""`)
}