service_matcher-go/ftp/ftp.go
2018-08-13 16:48:32 +09:00

97 lines
1.9 KiB
Go

package ftp
import (
"strings"
csm "git.loafle.net/commons/service_matcher-go"
)
// FTP Status codes, defined in RFC 959
const (
statusReadyServer = "120"
statusOK = "200"
statusNewConnectOK = "220"
statusSystemNameOK = "215"
statusCloseConnect = "221"
statusUnkownCMD = "202"
statusTlsUseOK = "234"
statusCloseControlConnect = "421"
statusSyntaxErr = "500"
statusParamSyntaxErr = "501"
statusNotUseCMD = "502"
statusIncorrectCMD = "503"
statusNotLoggedIn = "530"
statusTlsNotUse = "534"
statusNeedUserId = "332"
)
type FTPMatcher struct {
csm.Matchers
meta csm.Metadata
}
func (ftp *FTPMatcher) Key() string {
return "FTP"
}
func (ftp *FTPMatcher) Name() string {
return "FTP"
}
func (ftp *FTPMatcher) Meta() csm.Metadata {
return ftp.meta
}
func (ftp *FTPMatcher) IsPrePacket() bool {
return true
}
func (ftp *FTPMatcher) HasResponse(index int) bool {
return true
}
func (ftp *FTPMatcher) IsError(info csm.MatchInfo, index int, packet *csm.Packet) bool {
return false
}
func (ftp *FTPMatcher) Match(info csm.MatchInfo, index int, packet *csm.Packet) error {
if packet == nil || packet.Buffer == nil || packet.Len == 0 {
return csm.NoPacketReceivedError()
}
str := strings.Split(string(packet.Buffer), "\r\n")[0]
if len(str) < 4 {
return csm.NotMatchedError()
}
code := str[:3]
if index == 0 {
switch code {
case statusNewConnectOK, statusReadyServer:
ftp.meta["comment"] = str[4:]
return nil
}
} else if index == 1 {
switch code {
case statusCloseConnect, statusSyntaxErr:
return nil
}
}
return csm.NotMatchedError()
}
func NewMatcher() csm.Matcher {
m := &FTPMatcher{}
m.meta = csm.NewMetadata()
quitStr := "QUIT\r\n"
quitByte := make([]byte, len(quitStr))
copy(quitByte[:], quitStr)
m.AddPacket(csm.NewPacket(quitByte, len(quitStr)))
return m
}