forked from fclairamb/ftpserverlib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
321 lines (262 loc) · 9.17 KB
/
server.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
// Package ftpserver provides all the tools to build your own FTP server: The core library and the driver.
package ftpserver
import (
"crypto/tls"
"errors"
"fmt"
"net"
"os"
"syscall"
"time"
log "github.com/fclairamb/go-log"
lognoop "github.com/fclairamb/go-log/noop"
)
var (
// ErrNotListening is returned when we are performing an action that is only valid while listening
ErrNotListening = errors.New("we aren't listening")
)
// CommandDescription defines which function should be used and if it should be open to anyone or only logged in users
type CommandDescription struct {
Open bool // Open to clients without auth
TransferRelated bool // This is a command that can open a transfer connection
SpecialAction bool // Command to handle even if there is a transfer in progress
Fn func(*clientHandler, string) error // Function to handle it
}
// This is shared between FtpServer instances as there's no point in making the FTP commands behave differently
// between them.
var commandsMap = map[string]*CommandDescription{
// Authentication
"USER": {Fn: (*clientHandler).handleUSER, Open: true},
"PASS": {Fn: (*clientHandler).handlePASS, Open: true},
// TLS handling
"AUTH": {Fn: (*clientHandler).handleAUTH, Open: true},
"PROT": {Fn: (*clientHandler).handlePROT, Open: true},
"PBSZ": {Fn: (*clientHandler).handlePBSZ, Open: true},
// Misc
"CLNT": {Fn: (*clientHandler).handleCLNT, Open: true},
"FEAT": {Fn: (*clientHandler).handleFEAT, Open: true},
"SYST": {Fn: (*clientHandler).handleSYST, Open: true},
"NOOP": {Fn: (*clientHandler).handleNOOP, Open: true},
"OPTS": {Fn: (*clientHandler).handleOPTS, Open: true},
"QUIT": {Fn: (*clientHandler).handleQUIT, Open: true, SpecialAction: true},
"AVBL": {Fn: (*clientHandler).handleAVBL},
"ABOR": {Fn: (*clientHandler).handleABOR, SpecialAction: true},
// File access
"SIZE": {Fn: (*clientHandler).handleSIZE},
"STAT": {Fn: (*clientHandler).handleSTAT, SpecialAction: true},
"MDTM": {Fn: (*clientHandler).handleMDTM},
"MFMT": {Fn: (*clientHandler).handleMFMT},
"RETR": {Fn: (*clientHandler).handleRETR, TransferRelated: true},
"STOR": {Fn: (*clientHandler).handleSTOR, TransferRelated: true},
"APPE": {Fn: (*clientHandler).handleAPPE, TransferRelated: true},
"DELE": {Fn: (*clientHandler).handleDELE},
"RNFR": {Fn: (*clientHandler).handleRNFR},
"RNTO": {Fn: (*clientHandler).handleRNTO},
"ALLO": {Fn: (*clientHandler).handleALLO},
"REST": {Fn: (*clientHandler).handleREST},
"SITE": {Fn: (*clientHandler).handleSITE},
"HASH": {Fn: (*clientHandler).handleHASH},
"XCRC": {Fn: (*clientHandler).handleCRC32},
"MD5": {Fn: (*clientHandler).handleMD5},
"XMD5": {Fn: (*clientHandler).handleMD5},
"XSHA": {Fn: (*clientHandler).handleSHA1},
"XSHA1": {Fn: (*clientHandler).handleSHA1},
"XSHA256": {Fn: (*clientHandler).handleSHA256},
"XSHA512": {Fn: (*clientHandler).handleSHA512},
"COMB": {Fn: (*clientHandler).handleCOMB},
// Directory handling
"CWD": {Fn: (*clientHandler).handleCWD},
"PWD": {Fn: (*clientHandler).handlePWD},
"XCWD": {Fn: (*clientHandler).handleCWD},
"XPWD": {Fn: (*clientHandler).handlePWD},
"CDUP": {Fn: (*clientHandler).handleCDUP},
"NLST": {Fn: (*clientHandler).handleNLST, TransferRelated: true},
"LIST": {Fn: (*clientHandler).handleLIST, TransferRelated: true},
"MLSD": {Fn: (*clientHandler).handleMLSD, TransferRelated: true},
"MLST": {Fn: (*clientHandler).handleMLST},
"MKD": {Fn: (*clientHandler).handleMKD},
"RMD": {Fn: (*clientHandler).handleRMD},
"XMKD": {Fn: (*clientHandler).handleMKD},
"XRMD": {Fn: (*clientHandler).handleRMD},
// Connection handling
"TYPE": {Fn: (*clientHandler).handleTYPE},
"PASV": {Fn: (*clientHandler).handlePASV},
"EPSV": {Fn: (*clientHandler).handlePASV},
"PORT": {Fn: (*clientHandler).handlePORT},
"EPRT": {Fn: (*clientHandler).handlePORT},
}
var (
specialAttentionCommands = []string{"ABOR", "STAT", "QUIT"}
)
// FtpServer is where everything is stored
// We want to keep it as simple as possible
type FtpServer struct {
Logger log.Logger // fclairamb/go-log generic logger
settings *Settings // General settings
listener net.Listener // listener used to receive files
clientCounter uint32 // Clients counter
driver MainDriver // Driver to handle the client authentication and the file access driver selection
}
func (server *FtpServer) loadSettings() error {
s, err := server.driver.GetSettings()
if err != nil {
return err
}
if s.PublicHost != "" {
parsedIP := net.ParseIP(s.PublicHost)
if parsedIP == nil {
return &ipValidationError{error: fmt.Sprintf("invalid passive IP %#v", s.PublicHost)}
}
parsedIP = parsedIP.To4()
if parsedIP == nil {
return &ipValidationError{error: fmt.Sprintf("invalid IPv4 passive IP %#v", s.PublicHost)}
}
s.PublicHost = parsedIP.String()
}
if s.Listener == nil && s.ListenAddr == "" {
s.ListenAddr = "0.0.0.0:2121"
}
// florent(2018-01-14): #58: IDLE timeout: Default idle timeout will be set at 900 seconds
if s.IdleTimeout == 0 {
s.IdleTimeout = 900
}
if s.ConnectionTimeout == 0 {
s.ConnectionTimeout = 30
}
if s.Banner == "" {
s.Banner = "ftpserver - golang FTP server"
}
server.settings = s
return nil
}
// Listen starts the listening
// It's not a blocking call
func (server *FtpServer) Listen() error {
err := server.loadSettings()
if err != nil {
return fmt.Errorf("could not load settings: %w", err)
}
// The driver can provide its own listener implementation
if server.settings.Listener != nil {
server.listener = server.settings.Listener
} else {
// Otherwise, it's what we currently use
server.listener, err = net.Listen("tcp", server.settings.ListenAddr)
if err != nil {
server.Logger.Error("Cannot listen", "err", err)
return err
}
if server.settings.TLSRequired == ImplicitEncryption {
// implicit TLS
var tlsConfig *tls.Config
tlsConfig, err = server.driver.GetTLSConfig()
if err != nil {
server.Logger.Error("Cannot get tls config", "err", err)
return err
}
server.listener = tls.NewListener(server.listener, tlsConfig)
}
}
server.Logger.Info("Listening...", "address", server.listener.Addr())
return err
}
func temporaryError(err net.Error) bool {
if opErr, ok := err.(*net.OpError); ok {
if sysErr, ok := opErr.Err.(*os.SyscallError); ok {
if errno, ok := sysErr.Err.(syscall.Errno); ok {
if errno == syscall.ECONNABORTED ||
errno == syscall.ECONNRESET {
return true
}
}
}
}
return false
}
// Serve accepts and processes any new incoming client
func (server *FtpServer) Serve() error {
var tempDelay time.Duration // how long to sleep on accept failure
for {
connection, err := server.listener.Accept()
if err != nil {
if errOp, ok := err.(*net.OpError); ok {
// This means we just closed the connection and it's OK
if errOp.Err.Error() == "use of closed network connection" {
server.listener = nil
return nil
}
}
// see https://github.com/golang/go/blob/4aa1efed4853ea067d665a952eee77c52faac774/src/net/http/server.go#L3046
// & https://github.com/fclairamb/ftpserverlib/pull/352#pullrequestreview-1077459896
// The temporaryError method should replace net.Error.Temporary() when the go team
// will have provided us a better way to detect temporary errors.
if ne, ok := err.(net.Error); ok && ne.Temporary() { //nolint:staticcheck
if tempDelay == 0 {
tempDelay = 5 * time.Millisecond
} else {
tempDelay *= 2
}
if max := 1 * time.Second; tempDelay > max {
tempDelay = max
}
server.Logger.Warn(
"accept error", err,
"retry delay", tempDelay)
time.Sleep(tempDelay)
continue
}
server.Logger.Error("Listener accept error", "err", err)
return err
}
tempDelay = 0
server.clientArrival(connection)
}
}
// ListenAndServe simply chains the Listen and Serve method calls
func (server *FtpServer) ListenAndServe() error {
if err := server.Listen(); err != nil {
return err
}
server.Logger.Info("Starting...")
return server.Serve()
}
// NewFtpServer creates a new FtpServer instance
func NewFtpServer(driver MainDriver) *FtpServer {
return &FtpServer{
driver: driver,
Logger: lognoop.NewNoOpLogger(),
}
}
// Addr shows the listening address
func (server *FtpServer) Addr() string {
if server.listener != nil {
return server.listener.Addr().String()
}
return ""
}
// Stop closes the listener
func (server *FtpServer) Stop() error {
if server.listener == nil {
return ErrNotListening
}
err := server.listener.Close()
if err != nil {
server.Logger.Warn(
"Could not close listener",
"err", err,
)
}
return err
}
// When a client connects, the server could refuse the connection
func (server *FtpServer) clientArrival(conn net.Conn) {
server.clientCounter++
id := server.clientCounter
c := server.newClientHandler(conn, id, server.settings.DefaultTransferType)
go c.HandleCommands()
c.logger.Debug("Client connected", "clientIp", conn.RemoteAddr())
}
// clientDeparture
func (server *FtpServer) clientDeparture(c *clientHandler) {
c.logger.Debug("Client disconnected", "clientIp", c.conn.RemoteAddr())
}