forked from fclairamb/ftpserverlib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
transfer_pasv.go
225 lines (179 loc) · 5.78 KB
/
transfer_pasv.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
package ftpserver // nolint
import (
"crypto/tls"
"errors"
"fmt"
"math/rand"
"net"
"strings"
"time"
"github.com/fclairamb/ftpserverlib/log"
)
// Active/Passive transfer connection handler
type transferHandler interface {
// Get the connection to transfer data on
Open() (net.Conn, error)
// Close the connection (and any associated resource)
Close() error
// Set info about the transfer to return in STAT response
SetInfo(string)
// Info about the transfer to return in STAT response
GetInfo() string
}
// Passive connection
type passiveTransferHandler struct {
listener net.Listener // TCP or SSL Listener
tcpListener *net.TCPListener // TCP Listener (only keeping it to define a deadline during the accept)
Port int // TCP Port we are listening on
connection net.Conn // TCP Connection established
settings *Settings // Settings
info string // transfer info
logger log.Logger // Logger
}
func (c *clientHandler) getCurrentIP() ([]string, error) {
// Provide our external IP address so the ftp client can connect back to us
ip := c.server.settings.PublicHost
// If we don't have an IP address, we can take the one that was used for the current connection
if ip == "" {
// Defer to the user-provided resolver.
if c.server.settings.PublicIPResolver != nil {
var err error
ip, err = c.server.settings.PublicIPResolver(c)
if err != nil {
return nil, fmt.Errorf("couldn't fetch public IP: %w", err)
}
} else {
ip = strings.Split(c.conn.LocalAddr().String(), ":")[0]
}
}
return strings.Split(ip, "."), nil
}
// ErrNoAvailableListeningPort is returned when no port could be found to accept incoming connection
var ErrNoAvailableListeningPort = errors.New("could not find any port to listen to")
func (c *clientHandler) findListenerWithinPortRange(portRange *PortRange) (*net.TCPListener, error) {
nbAttempts := portRange.End - portRange.Start
// Making sure we trying a reasonable amount of ports before giving up
if nbAttempts < 10 {
nbAttempts = 10
} else if nbAttempts > 1000 {
nbAttempts = 1000
}
for i := 0; i < nbAttempts; i++ {
// nolint: gosec
port := portRange.Start + rand.Intn(portRange.End-portRange.Start+1)
laddr, errResolve := net.ResolveTCPAddr("tcp", fmt.Sprintf("0.0.0.0:%d", port))
if errResolve != nil {
c.logger.Error("Problem resolving local port", "err", errResolve, "port", port)
return nil, fmt.Errorf("could not resolve port %d: %w", port, errResolve)
}
tcpListener, errListen := net.ListenTCP("tcp", laddr)
if errListen == nil {
return tcpListener, errListen
}
}
c.logger.Warn(
"Could not find any free port",
"nbAttempts", nbAttempts,
"portRangeStart", portRange.Start,
"portRAngeEnd", portRange.End,
)
return nil, ErrNoAvailableListeningPort
}
func (c *clientHandler) handlePASV(param string) error {
command := c.GetLastCommand()
addr, _ := net.ResolveTCPAddr("tcp", ":0")
var tcpListener *net.TCPListener
var err error
portRange := c.server.settings.PassiveTransferPortRange
if portRange != nil {
tcpListener, err = c.findListenerWithinPortRange(portRange)
} else {
tcpListener, err = net.ListenTCP("tcp", addr)
}
if err != nil {
c.logger.Error("Could not listen for passive connection", "err", err)
c.writeMessage(StatusServiceNotAvailable, fmt.Sprintf("Could not listen for passive connection: %v", err))
return nil
}
// The listener will either be plain TCP or TLS
var listener net.Listener
if c.HasTLSForTransfers() || c.server.settings.TLSRequired == ImplicitEncryption {
if tlsConfig, err := c.server.driver.GetTLSConfig(); err == nil {
listener = tls.NewListener(tcpListener, tlsConfig)
} else {
c.writeMessage(StatusServiceNotAvailable, fmt.Sprintf("Cannot get a TLS config: %v", err))
return nil
}
} else {
listener = tcpListener
}
p := &passiveTransferHandler{
tcpListener: tcpListener,
listener: listener,
Port: tcpListener.Addr().(*net.TCPAddr).Port,
settings: c.server.settings,
logger: c.logger,
}
// We should rewrite this part
if command == "PASV" {
p1 := p.Port / 256
p2 := p.Port - (p1 * 256)
quads, err2 := c.getCurrentIP()
if err2 != nil {
c.writeMessage(StatusServiceNotAvailable, fmt.Sprintf("Could not listen for passive connection: %v", err2))
return nil
}
c.writeMessage(
StatusEnteringPASV,
fmt.Sprintf("Entering Passive Mode (%s,%s,%s,%s,%d,%d)", quads[0], quads[1], quads[2], quads[3], p1, p2))
} else {
c.writeMessage(StatusEnteringEPSV, fmt.Sprintf("Entering Extended Passive Mode (|||%d|)", p.Port))
}
c.transferMu.Lock()
c.transfer = p
c.transferMu.Unlock()
return nil
}
func (p *passiveTransferHandler) ConnectionWait(wait time.Duration) (net.Conn, error) {
if p.connection == nil {
var err error
if err = p.tcpListener.SetDeadline(time.Now().Add(wait)); err != nil {
return nil, fmt.Errorf("failed to set deadline: %w", err)
}
p.connection, err = p.listener.Accept()
if err != nil {
return nil, err
}
}
return p.connection, nil
}
func (p *passiveTransferHandler) GetInfo() string {
return p.info
}
func (p *passiveTransferHandler) SetInfo(info string) {
p.info = info
}
func (p *passiveTransferHandler) Open() (net.Conn, error) {
timeout := time.Duration(time.Second.Nanoseconds() * int64(p.settings.ConnectionTimeout))
return p.ConnectionWait(timeout)
}
// Closing only the client connection is not supported at that time
func (p *passiveTransferHandler) Close() error {
if p.tcpListener != nil {
if err := p.tcpListener.Close(); err != nil {
p.logger.Warn(
"Problem closing passive listener",
"err", err,
)
}
}
if p.connection != nil {
if err := p.connection.Close(); err != nil {
p.logger.Warn(
"Problem closing passive connection",
"err", err,
)
}
}
return nil
}