package ftps_protocol_crawler

import (
	"git.loafle.net/overflow/overflow_probe/matcher/packet"
	"git.loafle.net/overflow/overflow_probe/model/scaninfo"
)

const (
	statusOK           = "200"
	statusNewConnectOK = "220"
)

type FTPSMatcher struct {
	sendPackets []*packet.Packet
	isFtps      bool
}

func NewFTPSMatcher() *FTPSMatcher {

	f := FTPSMatcher{}

	pbs := "PBSZ 0\r\n"
	pbsByte := make([]byte, len(pbs))
	copy(pbsByte[:], pbs)
	f.sendPackets = append(f.sendPackets, packet.NewPacket(pbsByte, len(pbs)))

	prot := "PROT P\r\n"
	protByte := make([]byte, len(prot))
	copy(protByte[:], prot)
	f.sendPackets = append(f.sendPackets, packet.NewPacket(protByte, len(prot)))

	quitStr := "QUIT\r\n"
	quitByte := make([]byte, len(quitStr))
	copy(quitByte[:], quitStr)
	f.sendPackets = append(f.sendPackets, packet.NewPacket(quitByte, len(quitStr)))

	return &f
}

func (ftp *FTPSMatcher) Match(idx int, packet *packet.Packet, info scaninfo.ServiceScanInfo) bool {
	result := false

	str := string(packet.Buffer)
	code := str[:3]

	if code == statusOK || code == statusNewConnectOK {
		result = true
	}

	return result
}

func (ftp *FTPSMatcher) PacketCount() int {
	return len(ftp.sendPackets)
}

func (ftp *FTPSMatcher) Packet(index int) *packet.Packet {
	return ftp.sendPackets[index]
}

func (ftp *FTPSMatcher) ServiceName() string {
	return "FTPS"
}

func (ftp *FTPSMatcher) IsError(index int, packet *packet.Packet, info scaninfo.ServiceScanInfo) bool {
	return false
}

func (ftp *FTPSMatcher) IsNoResponse(index int) bool {
	return false
}

func (ftp *FTPSMatcher) IsPrePacket() bool {
	return true
}
