service_matcher-go/mysql/mysql.go
crusader bce329e44e ing
2018-10-23 13:31:25 +09:00

141 lines
2.7 KiB
Go

package mysql
import (
"bytes"
"encoding/binary"
"io"
"strings"
osm "git.loafle.net/overflow/service_matcher-go"
)
type MySqlMatcher struct {
osm.Matchers
}
func (m *MySqlMatcher) Key(matchCtx *osm.MatchCtx) string {
v := "MYSQL"
if _v, ok := matchCtx.GetAttribute("version"); ok {
if strings.Contains(_v, "MariaDB") {
v = "MARIADB"
}
}
return v
}
func (m *MySqlMatcher) Type(matchCtx *osm.MatchCtx) string {
return "DATABASE"
}
func (m *MySqlMatcher) Vendor(matchCtx *osm.MatchCtx) string {
v := "Oracle"
if _v, ok := matchCtx.GetAttribute("version"); ok {
if strings.Contains(_v, "MariaDB") {
v = "MariaDB"
}
}
return v
}
func (m *MySqlMatcher) Version(matchCtx *osm.MatchCtx) string {
v := "UNKNOWN"
if _v, ok := matchCtx.GetAttribute("version"); ok {
v = _v
}
return v
}
func (m *MySqlMatcher) OsType(matchCtx *osm.MatchCtx) string {
return "UNKNOWN"
}
func (m *MySqlMatcher) OsVersion(matchCtx *osm.MatchCtx) string {
return "UNKNOWN"
}
func (m *MySqlMatcher) Name(matchCtx *osm.MatchCtx) string {
name := "MySQL"
if v, ok := matchCtx.GetAttribute("version"); ok {
if strings.Contains(v, "MariaDB") {
name = "MariaDB"
}
}
return name
}
func (m *MySqlMatcher) IsPrePacket() bool {
return true
}
func (m *MySqlMatcher) HasResponse(matchCtx *osm.MatchCtx, index int) bool {
return true
}
func (m *MySqlMatcher) IsError(matchCtx *osm.MatchCtx, index int, packet *osm.Packet) bool {
return false
}
type serverSettings struct {
protocol byte
version string
flags uint32
charset uint8
scrambleBuff []byte
threadID uint32
keepalive int64
}
func (m *MySqlMatcher) Match(matchCtx *osm.MatchCtx, index int, packet *osm.Packet) error {
if packet == nil || !packet.Valid() {
return osm.NoPacketReceivedError()
}
buf := bytes.NewBuffer(packet.Buffer[:3])
packetLen, _ := binary.ReadUvarint(buf)
if packetLen != uint64(packet.Len-4) {
return osm.NotMatchedError()
}
pos := 4
p := new(serverSettings)
p.protocol = packet.Buffer[pos]
if p.protocol != 9 && p.protocol != 10 {
return osm.NotMatchedError()
}
pos++
slice, err := readSlice(packet.Buffer[pos:], 0x00)
if err != nil {
return osm.NotMatchedError()
}
matchCtx.SetAttribute("version", string(slice))
pos += len(slice) + 1
p.threadID = bytesToUint32(packet.Buffer[pos : pos+4])
pos += 4
return nil
}
func readSlice(data []byte, delim byte) (slice []byte, e error) {
pos := bytes.IndexByte(data, delim)
if pos > -1 {
slice = data[:pos]
} else {
slice = data
e = io.EOF
}
return
}
func bytesToUint32(b []byte) (n uint32) {
for i := uint8(0); i < 4; i++ {
n |= uint32(b[i]) << (i * 8)
}
return
}
func NewMatcher() osm.Matcher {
m := &MySqlMatcher{}
return m
}