forked from fclairamb/ftpserverlib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathasciiconverter.go
85 lines (70 loc) · 1.52 KB
/
asciiconverter.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
package ftpserver // nolint
import (
"bufio"
"io"
)
type convertMode int
const (
convertModeToCRLF convertMode = iota
convertModeToLF
)
type asciiConverter struct {
reader *bufio.Reader
mode convertMode
remaining []byte
}
func newASCIIConverter(r io.Reader, mode convertMode) *asciiConverter {
reader := bufio.NewReaderSize(r, 4096)
return &asciiConverter{
reader: reader,
mode: mode,
remaining: nil,
}
}
func (c *asciiConverter) Read(p []byte) (n int, err error) {
var data []byte
if len(c.remaining) > 0 {
data = c.remaining
c.remaining = nil
} else {
data, _, err = c.reader.ReadLine()
if err != nil {
return
}
}
n = len(data)
if n > 0 {
maxSize := len(p) - 2
if n > maxSize {
copy(p, data[:maxSize])
c.remaining = data[maxSize:]
return maxSize, nil
}
copy(p[:n], data[:n])
}
// we can have a partial read if the line is too long
// or a trailing line without a line ending, so we check
// the last byte to decide if we need to add a line ending.
// This will also ensure that a file without line endings
// will remain unchanged.
// Please note that a binary file will likely contain
// newline chars so it will be still corrupted if the
// client transfers it in ASCII mode
err = c.reader.UnreadByte()
if err != nil {
return
}
lastByte, err := c.reader.ReadByte()
if err == nil && lastByte == '\n' {
switch c.mode {
case convertModeToCRLF:
p[n] = '\r'
p[n+1] = '\n'
n += 2
case convertModeToLF:
p[n] = '\n'
n++
}
}
return n, err
}