forked from fclairamb/ftpserverlib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client_handler.go
771 lines (615 loc) · 19 KB
/
client_handler.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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
package ftpserver
import (
"bufio"
"errors"
"fmt"
"io"
"net"
"strings"
"sync"
"time"
log "github.com/fclairamb/go-log"
)
// HASHAlgo is the enumerable that represents the supported HASH algorithms
type HASHAlgo int8
// Supported hash algorithms
const (
HASHAlgoCRC32 HASHAlgo = iota
HASHAlgoMD5
HASHAlgoSHA1
HASHAlgoSHA256
HASHAlgoSHA512
)
// TransferType is the enumerable that represents the supported transfer types
type TransferType int8
// Supported transfer type
const (
TransferTypeASCII TransferType = iota
TransferTypeBinary
)
// DataChannel is the enumerable that represents the data channel (active or passive)
type DataChannel int8
// Supported data channel types
const (
DataChannelPassive DataChannel = iota + 1
DataChannelActive
)
const (
maxCommandSize = 4096
)
var (
errNoTransferConnection = errors.New("unable to open transfer: no transfer connection")
errTLSRequired = errors.New("unable to open transfer: TLS is required")
errInvalidTLSRequirement = errors.New("invalid TLS requirement")
)
func getHashMapping() map[string]HASHAlgo {
mapping := make(map[string]HASHAlgo)
mapping["CRC32"] = HASHAlgoCRC32
mapping["MD5"] = HASHAlgoMD5
mapping["SHA-1"] = HASHAlgoSHA1
mapping["SHA-256"] = HASHAlgoSHA256
mapping["SHA-512"] = HASHAlgoSHA512
return mapping
}
func getHashName(algo HASHAlgo) string {
hashName := ""
hashMapping := getHashMapping()
for k, v := range hashMapping {
if v == algo {
hashName = k
}
}
return hashName
}
//nolint:maligned
type clientHandler struct {
id uint32 // ID of the client
server *FtpServer // Server on which the connection was accepted
driver ClientDriver // Client handling driver
conn net.Conn // TCP connection
writer *bufio.Writer // Writer on the TCP connection
reader *bufio.Reader // Reader on the TCP connection
user string // Authenticated user
path string // Current path
listPath string // Path for NLST/LIST requests
clnt string // Identified client
command string // Command received on the connection
connectedAt time.Time // Date of connection
ctxRnfr string // Rename from
ctxRest int64 // Restart point
debug bool // Show debugging info on the server side
transferTLS bool // Use TLS for transfer connection
controlTLS bool // Use TLS for control connection
selectedHashAlgo HASHAlgo // algorithm used when we receive the HASH command
logger log.Logger // Client handler logging
currentTransferType TransferType // current transfer type
transferWg sync.WaitGroup // wait group for command that open a transfer connection
transferMu sync.Mutex // this mutex will protect the transfer parameters
transfer transferHandler // Transfer connection (passive or active)s
lastDataChannel DataChannel // Last data channel mode (passive or active)
isTransferOpen bool // indicate if the transfer connection is opened
isTransferAborted bool // indicate if the transfer was aborted
tlsRequirement TLSRequirement // TLS requirement to respect
extra any // Additional application-specific data
paramsMutex sync.RWMutex // mutex to protect the parameters exposed to the library users
}
// newClientHandler initializes a client handler when someone connects
func (server *FtpServer) newClientHandler(connection net.Conn, id uint32, transferType TransferType) *clientHandler {
p := &clientHandler{
server: server,
conn: connection,
id: id,
writer: bufio.NewWriter(connection),
reader: bufio.NewReaderSize(connection, maxCommandSize),
connectedAt: time.Now().UTC(),
path: "/",
selectedHashAlgo: HASHAlgoSHA256,
currentTransferType: transferType,
logger: server.Logger.With("clientId", id),
}
return p
}
func (c *clientHandler) disconnect() {
if err := c.conn.Close(); err != nil {
c.logger.Warn(
"Problem disconnecting a client",
"err", err,
)
}
}
// Path provides the current working directory of the client
func (c *clientHandler) Path() string {
c.paramsMutex.RLock()
defer c.paramsMutex.RUnlock()
return c.path
}
// SetPath changes the current working directory
func (c *clientHandler) SetPath(value string) {
c.paramsMutex.Lock()
defer c.paramsMutex.Unlock()
c.path = value
}
// getListPath returns the path for the last LIST/NLST request
func (c *clientHandler) getListPath() string {
c.paramsMutex.RLock()
defer c.paramsMutex.RUnlock()
return c.listPath
}
// SetListPath changes the path for the last LIST/NLST request
func (c *clientHandler) SetListPath(value string) {
c.paramsMutex.Lock()
defer c.paramsMutex.Unlock()
c.listPath = value
}
// Debug defines if we will list all interaction
func (c *clientHandler) Debug() bool {
c.paramsMutex.RLock()
defer c.paramsMutex.RUnlock()
return c.debug
}
// SetDebug changes the debug flag
func (c *clientHandler) SetDebug(debug bool) {
c.paramsMutex.Lock()
defer c.paramsMutex.Unlock()
c.debug = debug
}
// ID provides the client's ID
func (c *clientHandler) ID() uint32 {
return c.id
}
// RemoteAddr returns the remote network address.
func (c *clientHandler) RemoteAddr() net.Addr {
return c.conn.RemoteAddr()
}
// LocalAddr returns the local network address.
func (c *clientHandler) LocalAddr() net.Addr {
return c.conn.LocalAddr()
}
// GetClientVersion returns the identified client, can be empty.
func (c *clientHandler) GetClientVersion() string {
c.paramsMutex.RLock()
defer c.paramsMutex.RUnlock()
return c.clnt
}
func (c *clientHandler) setClientVersion(value string) {
c.paramsMutex.Lock()
defer c.paramsMutex.Unlock()
c.clnt = value
}
// HasTLSForControl returns true if the control connection is over TLS
func (c *clientHandler) HasTLSForControl() bool {
if c.server.settings.TLSRequired == ImplicitEncryption {
return true
}
c.paramsMutex.RLock()
defer c.paramsMutex.RUnlock()
return c.controlTLS
}
func (c *clientHandler) setTLSForControl(value bool) {
c.paramsMutex.Lock()
defer c.paramsMutex.Unlock()
c.controlTLS = value
}
// HasTLSForTransfers returns true if the transfer connection is over TLS
func (c *clientHandler) HasTLSForTransfers() bool {
if c.server.settings.TLSRequired == ImplicitEncryption {
return true
}
c.paramsMutex.RLock()
defer c.paramsMutex.RUnlock()
return c.transferTLS
}
func (c *clientHandler) SetExtra(extra any) {
c.extra = extra
}
func (c *clientHandler) Extra() any {
return c.extra
}
func (c *clientHandler) setTLSForTransfer(value bool) {
c.paramsMutex.Lock()
defer c.paramsMutex.Unlock()
c.transferTLS = value
}
// SetTLSRequirement sets the TLS requirement to respect for this connection
func (c *clientHandler) SetTLSRequirement(requirement TLSRequirement) error {
if requirement < ClearOrEncrypted || requirement > MandatoryEncryption {
return errInvalidTLSRequirement
}
c.paramsMutex.Lock()
defer c.paramsMutex.Unlock()
c.tlsRequirement = requirement
return nil
}
func (c *clientHandler) isTLSRequired() bool {
if c.server.settings.TLSRequired == MandatoryEncryption {
return true
}
c.paramsMutex.RLock()
defer c.paramsMutex.RUnlock()
return c.tlsRequirement == MandatoryEncryption
}
// GetLastCommand returns the last received command
func (c *clientHandler) GetLastCommand() string {
c.paramsMutex.RLock()
defer c.paramsMutex.RUnlock()
return c.command
}
// GetLastDataChannel returns the last data channel mode
func (c *clientHandler) GetLastDataChannel() DataChannel {
c.paramsMutex.RLock()
defer c.paramsMutex.RUnlock()
return c.lastDataChannel
}
func (c *clientHandler) setLastCommand(cmd string) {
c.paramsMutex.Lock()
defer c.paramsMutex.Unlock()
c.command = cmd
}
func (c *clientHandler) setLastDataChannel(channel DataChannel) {
c.paramsMutex.Lock()
defer c.paramsMutex.Unlock()
c.lastDataChannel = channel
}
func (c *clientHandler) closeTransfer() error {
var err error
if c.transfer != nil {
err = c.transfer.Close()
c.isTransferOpen = false
c.transfer = nil
if c.debug {
c.logger.Debug("Transfer connection closed")
}
}
return err
}
// Close closes the active transfer, if any, and the control connection
func (c *clientHandler) Close() error {
c.transferMu.Lock()
defer c.transferMu.Unlock()
// set isTransferAborted to true so any transfer in progress will not try to write
// to the closed connection on transfer close
c.isTransferAborted = true
if err := c.closeTransfer(); err != nil {
c.logger.Warn(
"Problem closing a transfer on external close request",
"err", err,
)
}
// don't be tempted to send a message to the client before
// closing the connection:
//
// 1) it is racy, we need to lock writeMessage to do this
// 2) the client could wait for another response and so we break the protocol
//
// closing the connection from a different goroutine should be safe
return c.conn.Close()
}
func (c *clientHandler) end() {
c.server.driver.ClientDisconnected(c)
c.server.clientDeparture(c)
if err := c.conn.Close(); err != nil {
c.logger.Debug(
"Problem closing control connection",
"err", err,
)
}
c.transferMu.Lock()
defer c.transferMu.Unlock()
if err := c.closeTransfer(); err != nil {
c.logger.Warn(
"Problem closing a transfer",
"err", err,
)
}
}
func (c *clientHandler) isCommandAborted() (aborted bool) {
c.transferMu.Lock()
defer c.transferMu.Unlock()
aborted = c.isTransferAborted
return
}
// HandleCommands reads the stream of commands
func (c *clientHandler) HandleCommands() {
defer c.end()
if msg, err := c.server.driver.ClientConnected(c); err == nil {
c.writeMessage(StatusServiceReady, msg)
} else {
c.writeMessage(StatusSyntaxErrorNotRecognised, msg)
return
}
for {
if c.reader == nil {
if c.debug {
c.logger.Debug("Client disconnected", "clean", true)
}
return
}
// florent(2018-01-14): #58: IDLE timeout: Preparing the deadline before we read
if c.server.settings.IdleTimeout > 0 {
if err := c.conn.SetDeadline(
time.Now().Add(time.Duration(time.Second.Nanoseconds() * int64(c.server.settings.IdleTimeout)))); err != nil {
c.logger.Error("Network error", "err", err)
}
}
lineSlice, isPrefix, err := c.reader.ReadLine()
if isPrefix {
if c.debug {
c.logger.Warn("Received line too long, disconnecting client",
"size", len(lineSlice))
}
return
}
if err != nil {
c.handleCommandsStreamError(err)
return
}
line := string(lineSlice)
if c.debug {
c.logger.Debug("Received line", "line", line)
}
c.handleCommand(line)
}
}
func (c *clientHandler) handleCommandsStreamError(err error) {
// florent(2018-01-14): #58: IDLE timeout: Adding some code to deal with the deadline
switch err := err.(type) {
case net.Error:
if err.Timeout() {
// We have to extend the deadline now
if err := c.conn.SetDeadline(time.Now().Add(time.Minute)); err != nil {
c.logger.Error("Could not set read deadline", "err", err)
}
c.logger.Info("Client IDLE timeout", "err", err)
c.writeMessage(
StatusServiceNotAvailable,
fmt.Sprintf("command timeout (%d seconds): closing control connection", c.server.settings.IdleTimeout))
if err := c.writer.Flush(); err != nil {
c.logger.Error("Flush error", "err", err)
}
break
}
c.logger.Error("Network error", "err", err)
default:
if err == io.EOF {
if c.debug {
c.logger.Debug("Client disconnected", "clean", false)
}
} else {
c.logger.Error("Read error", "err", err)
}
}
}
// handleCommand takes care of executing the received line
func (c *clientHandler) handleCommand(line string) {
command, param := parseLine(line)
command = strings.ToUpper(command)
cmdDesc := commandsMap[command]
if cmdDesc == nil {
// Search among commands having a "special semantic". They
// should be sent by following the RFC-959 procedure of sending
// Telnet IP/Synch sequence (chr 242 and 255) as OOB data but
// since many ftp clients don't do it correctly we check the
// command suffix.
for _, cmd := range specialAttentionCommands {
if strings.HasSuffix(command, cmd) {
cmdDesc = commandsMap[cmd]
command = cmd
break
}
}
if cmdDesc == nil {
c.logger.Warn("Unknown command", "command", command)
c.setLastCommand(command)
c.writeMessage(StatusSyntaxErrorNotRecognised, fmt.Sprintf("Unknown command %#v", command))
return
}
}
if c.driver == nil && !cmdDesc.Open {
c.writeMessage(StatusNotLoggedIn, "Please login with USER and PASS")
return
}
// All commands are serialized except the ones that require special action.
// Special action commands are not executed in a separate goroutine so we can
// have at most one command that can open a transfer connection and one special
// action command running at the same time.
// Only server STAT is a special action command so we do an additional check here
if !cmdDesc.SpecialAction || (command == "STAT" && param != "") {
c.transferWg.Wait()
}
c.setLastCommand(command)
if cmdDesc.TransferRelated {
// these commands will be started in a separate goroutine so
// they can be aborted.
// We cannot have two concurrent transfers so also set isTransferAborted
// to false here.
// isTransferAborted could remain to true if the previous command is
// aborted and it does not open a transfer connection, see "transferFile"
// for details. For this to happen a client should send an ABOR before
// receiving the StatusFileStatusOK response. This is very unlikely
// A lock is not required here, we cannot have another concurrent ABOR
// or transfer active here
c.isTransferAborted = false
c.transferWg.Add(1)
go func(cmd, param string) {
defer c.transferWg.Done()
c.executeCommandFn(cmdDesc, cmd, param)
}(command, param)
} else {
c.executeCommandFn(cmdDesc, command, param)
}
}
func (c *clientHandler) executeCommandFn(cmdDesc *CommandDescription, command, param string) {
// Let's prepare to recover in case there's a command error
defer func() {
if r := recover(); r != nil {
c.writeMessage(StatusSyntaxErrorNotRecognised, fmt.Sprintf("Unhandled internal error: %s", r))
c.logger.Warn(
"Internal command handling error",
"err", r,
"command", command,
"param", param,
)
}
}()
if err := cmdDesc.Fn(c, param); err != nil {
c.writeMessage(StatusSyntaxErrorNotRecognised, fmt.Sprintf("Error: %s", err))
}
}
func (c *clientHandler) writeLine(line string) {
if c.debug {
c.logger.Debug("Sending answer", "line", line)
}
if _, err := c.writer.WriteString(fmt.Sprintf("%s\r\n", line)); err != nil {
c.logger.Warn(
"Answer couldn't be sent",
"line", line,
"err", err,
)
}
if err := c.writer.Flush(); err != nil {
c.logger.Warn(
"Couldn't flush line",
"err", err,
)
}
}
func (c *clientHandler) writeMessage(code int, message string) {
lines := getMessageLines(message)
for idx, line := range lines {
if idx < len(lines)-1 {
c.writeLine(fmt.Sprintf("%d-%s", code, line))
} else {
c.writeLine(fmt.Sprintf("%d %s", code, line))
}
}
}
func (c *clientHandler) GetTranferInfo() string {
if c.transfer == nil {
return ""
}
return c.transfer.GetInfo()
}
func (c *clientHandler) TransferOpen(info string) (net.Conn, error) {
c.transferMu.Lock()
defer c.transferMu.Unlock()
if c.transfer == nil {
// a transfer could be aborted before it is opened, in this case no response should be returned
if c.isTransferAborted {
c.isTransferAborted = false
return nil, errNoTransferConnection
}
c.writeMessage(StatusActionNotTaken, errNoTransferConnection.Error())
return nil, errNoTransferConnection
}
if c.isTLSRequired() && !c.HasTLSForTransfers() {
c.writeMessage(StatusServiceNotAvailable, errTLSRequired.Error())
return nil, errTLSRequired
}
conn, err := c.transfer.Open()
if err != nil {
c.logger.Warn(
"Unable to open transfer",
"error", err)
c.writeMessage(StatusCannotOpenDataConnection, err.Error())
return nil, err
}
c.isTransferOpen = true
c.transfer.SetInfo(info)
c.writeMessage(StatusFileStatusOK, "Using transfer connection")
if c.debug {
c.logger.Debug(
"Transfer connection opened",
"remoteAddr", conn.RemoteAddr().String(),
"localAddr", conn.LocalAddr().String())
}
return conn, err
}
func (c *clientHandler) TransferClose(err error) {
c.transferMu.Lock()
defer c.transferMu.Unlock()
errClose := c.closeTransfer()
if errClose != nil {
c.logger.Warn(
"Problem closing transfer connection",
"err", err,
)
}
// if the transfer was aborted we don't have to send a response
if c.isTransferAborted {
c.isTransferAborted = false
return
}
switch {
case err == nil && errClose == nil:
c.writeMessage(StatusClosingDataConn, "Closing transfer connection")
case errClose != nil:
c.writeMessage(StatusActionNotTaken, fmt.Sprintf("Issue during transfer close: %v", errClose))
case err != nil:
c.writeMessage(getErrorCode(err, StatusActionNotTaken), fmt.Sprintf("Issue during transfer: %v", err))
}
}
func (c *clientHandler) checkDataConnectionRequirement(dataConnIP net.IP, channelType DataChannel) error {
var requirement DataConnectionRequirement
switch channelType {
case DataChannelActive:
requirement = c.server.settings.ActiveConnectionsCheck
case DataChannelPassive:
requirement = c.server.settings.PasvConnectionsCheck
}
switch requirement {
case IPMatchRequired:
controlConnIP, err := getIPFromRemoteAddr(c.RemoteAddr())
if err != nil {
return err
}
if !controlConnIP.Equal(dataConnIP) {
return &ipValidationError{error: fmt.Sprintf("data connection ip address %v "+
"does not match control connection ip address %v",
dataConnIP, controlConnIP)}
}
return nil
case IPMatchDisabled:
return nil
default:
return &ipValidationError{error: fmt.Sprintf("unhandled data connection requirement: %v",
requirement)}
}
}
func getIPFromRemoteAddr(remoteAddr net.Addr) (net.IP, error) {
if remoteAddr == nil {
return nil, &ipValidationError{error: "nil remote address"}
}
ip, _, err := net.SplitHostPort(remoteAddr.String())
if err != nil {
return nil, err
}
remoteIP := net.ParseIP(ip)
if remoteIP == nil {
return nil, &ipValidationError{error: fmt.Sprintf("invalid remote IP: %v", ip)}
}
return remoteIP, nil
}
func parseLine(line string) (string, string) {
params := strings.SplitN(line, " ", 2)
if len(params) == 1 {
return params[0], ""
}
return params[0], params[1]
}
func (c *clientHandler) multilineAnswer(code int, message string) func() {
c.writeLine(fmt.Sprintf("%d-%s", code, message))
return func() {
c.writeLine(fmt.Sprintf("%d End", code))
}
}
func getMessageLines(message string) []string {
lines := make([]string, 0, 1)
sc := bufio.NewScanner(strings.NewReader(message))
for sc.Scan() {
lines = append(lines, sc.Text())
}
if len(lines) == 0 {
lines = append(lines, "")
}
return lines
}