service_matcher-go/matcher.go

100 lines
2.0 KiB
Go
Raw Normal View History

2018-08-13 07:48:32 +00:00
package matcher
2018-09-12 04:26:27 +00:00
import (
"fmt"
)
2018-08-13 07:48:32 +00:00
type Matcher interface {
2018-10-23 04:31:25 +00:00
Key(matchCtx *MatchCtx) string
Type(matchCtx *MatchCtx) string
Vendor(matchCtx *MatchCtx) string
Version(matchCtx *MatchCtx) string
OsType(matchCtx *MatchCtx) string
OsVersion(matchCtx *MatchCtx) string
2018-09-03 13:36:57 +00:00
Name(matchCtx *MatchCtx) string
2018-08-13 07:48:32 +00:00
2018-09-03 13:41:28 +00:00
IsPrePacket() bool
2018-09-03 13:36:57 +00:00
PacketCount(matchCtx *MatchCtx) int
Packet(matchCtx *MatchCtx, index int) *Packet
HasResponse(matchCtx *MatchCtx, index int) bool
2018-08-13 07:48:32 +00:00
2018-09-03 13:36:57 +00:00
Match(matchCtx *MatchCtx, index int, packet *Packet) error
2018-08-13 07:48:32 +00:00
}
type UDPMatcher interface {
Matcher
IsSend(port int) bool
}
type Matchers struct {
packets []*Packet
}
2018-09-03 13:36:57 +00:00
func (m *Matchers) PacketCount(matchCtx *MatchCtx) int {
2018-08-13 07:48:32 +00:00
return len(m.packets)
}
2018-09-03 13:36:57 +00:00
func (m *Matchers) Packet(matchCtx *MatchCtx, index int) *Packet {
2018-08-13 07:48:32 +00:00
return m.packets[index]
}
2018-09-03 13:36:57 +00:00
func (m *Matchers) HasResponse(matchCtx *MatchCtx, index int) bool {
2018-08-13 07:48:32 +00:00
return len(m.packets)-1 > index
}
func (m *Matchers) AddPacket(packet *Packet) {
m.packets = append(m.packets, packet)
}
2018-09-03 13:36:57 +00:00
type MatchCtx struct {
address string
port int
2018-09-03 13:52:01 +00:00
attributes map[string]string
2018-08-13 07:48:32 +00:00
}
2018-09-03 13:36:57 +00:00
func (mc *MatchCtx) Address() string {
return mc.address
}
func (mc *MatchCtx) Port() int {
return mc.port
}
2018-09-03 13:52:01 +00:00
func (mc *MatchCtx) GetAttribute(key string) (value string, ok bool) {
2018-09-03 13:36:57 +00:00
value, ok = mc.attributes[key]
return
2018-08-13 07:48:32 +00:00
}
2018-09-03 13:52:55 +00:00
func (mc *MatchCtx) GetAttributes() map[string]string {
return mc.attributes
}
2018-09-03 13:52:01 +00:00
func (mc *MatchCtx) SetAttribute(key string, value string) {
2018-09-03 13:36:57 +00:00
mc.attributes[key] = value
2018-08-13 07:48:32 +00:00
}
2018-09-03 13:36:57 +00:00
func (mc *MatchCtx) InitAttribute() {
2018-09-03 13:52:01 +00:00
mc.attributes = make(map[string]string)
2018-08-13 07:48:32 +00:00
}
2018-09-03 13:36:57 +00:00
func NewMatchCtx(address string, port int) *MatchCtx {
return &MatchCtx{
address: address,
port: port,
2018-09-03 13:52:01 +00:00
attributes: make(map[string]string),
2018-08-13 07:48:32 +00:00
}
}
const (
noPacketReceived = 1000 + iota
notMatched
)
func NoPacketReceivedError() error {
return fmt.Errorf("[%d] %s", noPacketReceived, "No packet received.")
}
func NotMatchedError() error {
return fmt.Errorf("[%d] %s", notMatched, "Not matched packet.")
}