run go fmt

This commit is contained in:
wanyaoqi 2018-12-03 21:58:54 +08:00
parent 10cf59920e
commit 07ef6cbf3f
17 changed files with 307 additions and 315 deletions

View File

@ -191,28 +191,28 @@ func (p *StreamPool) connections() []*connection {
return conns
}
//FlushOlderThan finds any streams waiting for packets older than the given
//time, and pushes through the data they have (IE: tells them to stop waiting
//and skip the data they're waiting for).
//
//Each Stream maintains a list of zero or more sets of bytes it has received
//out-of-order. For example, if it has processed up through sequence number
//10, it might have bytes [15-20), [20-25), [30,50) in its list. Each set of
//bytes also has the timestamp it was originally viewed. A flush call will
//look at the smallest subsequent set of bytes, in this case [15-20), and if
//its timestamp is older than the passed-in time, it will push it and all
//contiguous byte-sets out to the Stream's Reassembled function. In this case,
//it will push [15-20), but also [20-25), since that's contiguous. It will
//only push [30-50) if its timestamp is also older than the passed-in time,
//otherwise it will wait until the next FlushOlderThan to see if bytes [25-30)
//come in.
//
//If it pushes all bytes (or there were no sets of bytes to begin with) AND the
//connection has not received any bytes since the passed-in time, the
//connection will be closed.
//
//Returns the number of connections flushed, and of those, the number closed
//because of the flush.
//FlushOlderThan finds any streams waiting for packets older than the given
//time, and pushes through the data they have (IE: tells them to stop waiting
//and skip the data they're waiting for).
//
//Each Stream maintains a list of zero or more sets of bytes it has received
//out-of-order. For example, if it has processed up through sequence number
//10, it might have bytes [15-20), [20-25), [30,50) in its list. Each set of
//bytes also has the timestamp it was originally viewed. A flush call will
//look at the smallest subsequent set of bytes, in this case [15-20), and if
//its timestamp is older than the passed-in time, it will push it and all
//contiguous byte-sets out to the Stream's Reassembled function. In this case,
//it will push [15-20), but also [20-25), since that's contiguous. It will
//only push [30-50) if its timestamp is also older than the passed-in time,
//otherwise it will wait until the next FlushOlderThan to see if bytes [25-30)
//come in.
//
//If it pushes all bytes (or there were no sets of bytes to begin with) AND the
//connection has not received any bytes since the passed-in time, the
//connection will be closed.
//
//Returns the number of connections flushed, and of those, the number closed
//because of the flush.
func (a *Assembler) FlushOlderThan(t time.Time) (flushed, closed int) {
conns := a.connPool.connections()
closes := 0

View File

@ -1,11 +1,11 @@
package core
import (
"os"
"strings"
"fmt"
"net"
"os"
"strconv"
"strings"
)
const InternalCmdPrefix = "--"
@ -18,14 +18,14 @@ const (
)
type Cmd struct {
Device string
Device string
plugHandle *Plug
}
func NewCmd(p *Plug) *Cmd {
return &Cmd{
plugHandle:p,
plugHandle: p,
}
}
@ -55,27 +55,27 @@ func (cm *Cmd) parseInternalCmd() {
cmd := strings.Trim(arg, InternalCmdPrefix)
switch cmd {
case InternalCmdHelp:
cm.printHelpMessage()
break
case InternalCmdEnv:
fmt.Println("External plug-in path : "+cm.plugHandle.dir)
break
case InternalCmdList:
cm.plugHandle.PrintList()
break
case InternalCmdVer:
fmt.Println(cxt.Version)
break
case InternalDevice:
cm.printDevice()
break
case InternalCmdHelp:
cm.printHelpMessage()
break
case InternalCmdEnv:
fmt.Println("External plug-in path : " + cm.plugHandle.dir)
break
case InternalCmdList:
cm.plugHandle.PrintList()
break
case InternalCmdVer:
fmt.Println(cxt.Version)
break
case InternalDevice:
cm.printDevice()
break
}
os.Exit(1)
}
//usage
func (cm *Cmd) printHelpMessage() {
func (cm *Cmd) printHelpMessage() {
fmt.Println("==================================================================================")
fmt.Println("[Usage]")
@ -104,21 +104,21 @@ func (cm *Cmd) printHelpMessage() {
func (cm *Cmd) printPlugList() {
l := len(cm.plugHandle.InternalPlugList)
l += len(cm.plugHandle.ExternalPlugList)
fmt.Println("# Number of plug-ins : "+strconv.Itoa(l))
fmt.Println("# Number of plug-ins : " + strconv.Itoa(l))
}
//print device
func (cm *Cmd) printDevice() {
ifaces, err:= net.Interfaces()
ifaces, err := net.Interfaces()
if err != nil {
panic(err)
}
for _, iface := range ifaces {
addrs, _ := iface.Addrs()
for _,a:=range addrs {
for _, a := range addrs {
if ipnet, ok := a.(*net.IPNet); ok {
if ip4 := ipnet.IP.To4(); ip4 != nil {
fmt.Println("[device] : "+iface.Name+" : "+iface.HardwareAddr.String()+" "+ip4.String())
fmt.Println("[device] : " + iface.Name + " : " + iface.HardwareAddr.String() + " " + ip4.String())
}
}
}
@ -126,7 +126,7 @@ func (cm *Cmd) printDevice() {
}
//Parameters needed for plug-ins
func (cm *Cmd) parsePlugCmd() {
func (cm *Cmd) parsePlugCmd() {
if len(os.Args) < 3 {
fmt.Println("not found [Plug-in name]")
@ -134,12 +134,8 @@ func (cm *Cmd) parsePlugCmd() {
os.Exit(1)
}
cm.Device = os.Args[1]
plugName := os.Args[2]
plugParams:= os.Args[3:]
cm.Device = os.Args[1]
plugName := os.Args[2]
plugParams := os.Args[3:]
cm.plugHandle.SetOption(plugName, plugParams)
}

View File

@ -1,6 +1,6 @@
package core
type Core struct{
type Core struct {
Version string
}
@ -13,7 +13,7 @@ func New() Core {
return cxt
}
func (c *Core) Run() {
func (c *Core) Run() {
//new plugin
plug := NewPlug()
@ -24,4 +24,4 @@ func (c *Core) Run() {
//dispatch
NewDispatch(plug, cmd).Capture()
}
}

View File

@ -12,15 +12,15 @@ import (
)
type Dispatch struct {
device string
device string
payload []byte
Plug *Plug
Plug *Plug
}
func NewDispatch(plug *Plug, cmd *Cmd) *Dispatch {
return &Dispatch {
Plug: plug,
device:cmd.Device,
return &Dispatch{
Plug: plug,
device: cmd.Device,
}
}
@ -41,16 +41,16 @@ func (d *Dispatch) Capture() {
}
//capture
src := gopacket.NewPacketSource(handle, handle.LinkType())
src := gopacket.NewPacketSource(handle, handle.LinkType())
packets := src.Packets()
//set up assembly
streamFactory := &ProtocolStreamFactory{
dispatch:d,
dispatch: d,
}
streamPool := NewStreamPool(streamFactory)
assembler := NewAssembler(streamPool)
ticker := time.Tick(time.Minute)
assembler := NewAssembler(streamPool)
ticker := time.Tick(time.Minute)
//loop until ctrl+z
for {
@ -85,7 +85,7 @@ type ProtocolStream struct {
func (m *ProtocolStreamFactory) New(net, transport gopacket.Flow) tcpassembly.Stream {
//init stream struct
stm := &ProtocolStream {
stm := &ProtocolStream{
net: net,
transport: transport,
r: tcpreader.NewReaderStream(),
@ -98,4 +98,4 @@ func (m *ProtocolStreamFactory) New(net, transport gopacket.Flow) tcpassembly.St
go m.dispatch.Plug.ResolveStream(net, transport, &(stm.r))
return &(stm.r)
}
}

View File

@ -1,24 +1,23 @@
package core
import (
"io/ioutil"
"plugin"
"github.com/google/gopacket"
"io"
mysql "github.com/40t/go-sniffer/plugSrc/mysql/build"
redis "github.com/40t/go-sniffer/plugSrc/redis/build"
"fmt"
hp "github.com/40t/go-sniffer/plugSrc/http/build"
mongodb "github.com/40t/go-sniffer/plugSrc/mongodb/build"
"path/filepath"
"fmt"
mysql "github.com/40t/go-sniffer/plugSrc/mysql/build"
redis "github.com/40t/go-sniffer/plugSrc/redis/build"
"github.com/google/gopacket"
"io"
"io/ioutil"
"path"
"path/filepath"
"plugin"
)
type Plug struct {
dir string
dir string
ResolveStream func(net gopacket.Flow, transport gopacket.Flow, r io.Reader)
BPF string
BPF string
InternalPlugList map[string]PlugInterface
ExternalPlugList map[string]ExternalPlug
@ -48,7 +47,7 @@ func NewPlug() *Plug {
var p Plug
p.dir, _ = filepath.Abs( "./plug/")
p.dir, _ = filepath.Abs("./plug/")
p.LoadInternalPlugList()
p.LoadExternalPlugList()
@ -60,16 +59,16 @@ func (p *Plug) LoadInternalPlugList() {
list := make(map[string]PlugInterface)
//Mysql
list["mysql"] = mysql.NewInstance()
list["mysql"] = mysql.NewInstance()
//Mongodb
list["mongodb"] = mongodb.NewInstance()
list["mongodb"] = mongodb.NewInstance()
//Redis
list["redis"] = redis.NewInstance()
list["redis"] = redis.NewInstance()
//Http
list["http"] = hp.NewInstance()
list["http"] = hp.NewInstance()
p.InternalPlugList = list
}
@ -87,7 +86,7 @@ func (p *Plug) LoadExternalPlugList() {
continue
}
plug, err := plugin.Open(p.dir+"/"+fi.Name())
plug, err := plugin.Open(p.dir + "/" + fi.Name())
if err != nil {
panic(err)
}
@ -113,12 +112,12 @@ func (p *Plug) LoadExternalPlugList() {
}
version := versionFunc.(func() string)()
p.ExternalPlugList[fi.Name()] = ExternalPlug {
ResolvePacket:ResolvePacketFunc.(func(net gopacket.Flow, transport gopacket.Flow, r io.Reader)),
SetFlag:setFlagFunc.(func([]string)),
BPFFilter:BPFFilterFunc.(func() string),
Version:version,
Name:fi.Name(),
p.ExternalPlugList[fi.Name()] = ExternalPlug{
ResolvePacket: ResolvePacketFunc.(func(net gopacket.Flow, transport gopacket.Flow, r io.Reader)),
SetFlag: setFlagFunc.(func([]string)),
BPFFilter: BPFFilterFunc.(func() string),
Version: version,
Name: fi.Name(),
}
}
}
@ -131,7 +130,7 @@ func (p *Plug) PrintList() {
//Print Internal Plug
for inPlugName, _ := range p.InternalPlugList {
fmt.Println("internal plug : "+inPlugName)
fmt.Println("internal plug : " + inPlugName)
}
//split
@ -139,7 +138,7 @@ func (p *Plug) PrintList() {
//print External Plug
for exPlugName, _ := range p.ExternalPlugList {
fmt.Println("external plug : "+exPlugName)
fmt.Println("external plug : " + exPlugName)
}
}
@ -150,13 +149,13 @@ func (p *Plug) SetOption(plugName string, plugParams []string) {
p.ResolveStream = internalPlug.ResolveStream
internalPlug.SetFlag(plugParams)
p.BPF = internalPlug.BPFFilter()
p.BPF = internalPlug.BPFFilter()
return
}
//Load External Plug
plug, err := plugin.Open("./plug/"+ plugName)
plug, err := plugin.Open("./plug/" + plugName)
if err != nil {
panic(err)
}
@ -174,5 +173,5 @@ func (p *Plug) SetOption(plugName string, plugParams []string) {
}
p.ResolveStream = resolvePacket.(func(net gopacket.Flow, transport gopacket.Flow, r io.Reader))
setFlag.(func([]string))(plugParams)
p.BPF = BPFFilter.(func()string)()
}
p.BPF = BPFFilter.(func() string)()
}

View File

@ -7,4 +7,4 @@ import (
func main() {
core := core.New()
core.Run()
}
}

View File

@ -1,28 +1,28 @@
package build
import (
"bufio"
"fmt"
"github.com/google/gopacket"
"io"
"log"
"strconv"
"fmt"
"os"
"bufio"
"net/http"
"os"
"strconv"
)
const (
Port = 80
Version = "0.1"
Port = 80
Version = "0.1"
)
const (
CmdPort = "-p"
CmdPort = "-p"
)
type H struct {
port int
version string
port int
version string
}
var hp *H
@ -30,8 +30,8 @@ var hp *H
func NewInstance() *H {
if hp == nil {
hp = &H{
port :Port,
version:Version,
port: Port,
version: Version,
}
}
return hp
@ -66,31 +66,31 @@ func (m *H) ResolveStream(net, transport gopacket.Flow, buf io.Reader) {
}
func (m *H) BPFFilter() string {
return "tcp and port "+strconv.Itoa(m.port);
return "tcp and port " + strconv.Itoa(m.port)
}
func (m *H) Version() string {
return Version
}
func (m *H) SetFlag(flg []string) {
func (m *H) SetFlag(flg []string) {
c := len(flg)
if c == 0 {
return
}
if c >> 1 == 0 {
if c>>1 == 0 {
fmt.Println("ERR : Http Number of parameters")
os.Exit(1)
}
for i:=0;i<c;i=i+2 {
for i := 0; i < c; i = i + 2 {
key := flg[i]
val := flg[i+1]
switch key {
case CmdPort:
port, err := strconv.Atoi(val);
port, err := strconv.Atoi(val)
m.port = port
if err != nil {
panic("ERR : port")
@ -103,4 +103,4 @@ func (m *H) SetFlag(flg []string) {
panic("ERR : mysql's params")
}
}
}
}

View File

@ -279,7 +279,7 @@ var nullBytes = []byte("null")
func (id *ObjectId) UnmarshalJSON(data []byte) error {
if len(data) > 0 && (data[0] == '{' || data[0] == 'O') {
var v struct {
Id json.RawMessage `json:"$oid"`
Id json.RawMessage `json:"$oid"`
Func struct {
Id json.RawMessage
} `json:"$oidFunc"`

View File

@ -1,17 +1,17 @@
package build
const (
OP_REPLY = 1 //Reply to a client request. responseTo is set.
OP_UPDATE = 2001 //Update document.
OP_INSERT = 2002 //Insert new document.
RESERVED = 2003 //Formerly used for OP_GET_BY_OID.
OP_REPLY = 1 //Reply to a client request. responseTo is set.
OP_UPDATE = 2001 //Update document.
OP_INSERT = 2002 //Insert new document.
RESERVED = 2003 //Formerly used for OP_GET_BY_OID.
OP_QUERY = 2004 //Query a collection.
OP_GET_MORE = 2005 //Get more data from a query. See Cursors.
OP_DELETE = 2006 //Delete documents.
OP_KILL_CURSORS = 2007 //Notify database that the client has finished with the cursor.
OP_QUERY = 2004 //Query a collection.
OP_GET_MORE = 2005 //Get more data from a query. See Cursors.
OP_DELETE = 2006 //Delete documents.
OP_KILL_CURSORS = 2007 //Notify database that the client has finished with the cursor.
OP_COMMAND = 2010 //Cluster internal protocol representing a command request.
OP_COMMANDREPLY = 2011 //Cluster internal protocol representing a reply to an OP_COMMAND.
OP_MSG = 2013 //Send a message using the format introduced in MongoDB 3.6.
)
OP_COMMAND = 2010 //Cluster internal protocol representing a command request.
OP_COMMANDREPLY = 2011 //Cluster internal protocol representing a reply to an OP_COMMAND.
OP_MSG = 2013 //Send a message using the format introduced in MongoDB 3.6.
)

View File

@ -10,7 +10,7 @@ import (
)
const (
Port = 27017
Port = 27017
Version = "0.1"
CmdPort = "-p"
)
@ -26,15 +26,14 @@ type stream struct {
}
type packet struct {
isClientFlow bool //client->server
isClientFlow bool //client->server
messageLength int
requestID int
responseTo int
opCode int //request type
opCode int //request type
payload io.Reader
payload io.Reader
}
var mongodbInstance *Mongodb
@ -42,29 +41,29 @@ var mongodbInstance *Mongodb
func NewInstance() *Mongodb {
if mongodbInstance == nil {
mongodbInstance = &Mongodb{
port :Port,
version:Version,
source: make(map[string]*stream),
port: Port,
version: Version,
source: make(map[string]*stream),
}
}
return mongodbInstance
}
func (m *Mongodb) SetFlag(flg []string) {
func (m *Mongodb) SetFlag(flg []string) {
c := len(flg)
if c == 0 {
return
}
if c >> 1 != 1 {
if c>>1 != 1 {
panic("ERR : Mongodb Number of parameters")
}
for i:=0;i<c;i=i+2 {
for i := 0; i < c; i = i + 2 {
key := flg[i]
val := flg[i+1]
switch key {
case CmdPort:
p, err := strconv.Atoi(val);
p, err := strconv.Atoi(val)
if err != nil {
panic("ERR : port")
}
@ -80,7 +79,7 @@ func (m *Mongodb) SetFlag(flg []string) {
}
func (m *Mongodb) BPFFilter() string {
return "tcp and port "+strconv.Itoa(m.port);
return "tcp and port " + strconv.Itoa(m.port)
}
func (m *Mongodb) Version() string {
@ -95,8 +94,8 @@ func (m *Mongodb) ResolveStream(net, transport gopacket.Flow, buf io.Reader) {
//resolve packet
if _, ok := m.source[uuid]; !ok {
var newStream = stream {
packets:make(chan *packet, 100),
var newStream = stream{
packets: make(chan *packet, 100),
}
m.source[uuid] = &newStream
@ -135,7 +134,7 @@ func (m *Mongodb) newPacket(net, transport gopacket.Flow, r io.Reader) *packet {
//set flow direction
if transport.Src().String() == strconv.Itoa(m.port) {
packet.isClientFlow = false
}else{
} else {
packet.isClientFlow = true
}
@ -145,7 +144,7 @@ func (m *Mongodb) newPacket(net, transport gopacket.Flow, r io.Reader) *packet {
func (stm *stream) resolve() {
for {
select {
case packet := <- stm.packets:
case packet := <-stm.packets:
if packet.isClientFlow {
stm.resolveClientPacket(packet)
} else {
@ -165,11 +164,11 @@ func (stm *stream) resolveClientPacket(pk *packet) {
switch pk.opCode {
case OP_UPDATE:
zero := ReadInt32(pk.payload)
zero := ReadInt32(pk.payload)
fullCollectionName := ReadString(pk.payload)
flags := ReadInt32(pk.payload)
selector := ReadBson2Json(pk.payload)
update := ReadBson2Json(pk.payload)
flags := ReadInt32(pk.payload)
selector := ReadBson2Json(pk.payload)
update := ReadBson2Json(pk.payload)
_ = zero
_ = flags
@ -180,9 +179,9 @@ func (stm *stream) resolveClientPacket(pk *packet) {
)
case OP_INSERT:
flags := ReadInt32(pk.payload)
flags := ReadInt32(pk.payload)
fullCollectionName := ReadString(pk.payload)
command := ReadBson2Json(pk.payload)
command := ReadBson2Json(pk.payload)
_ = flags
msg = fmt.Sprintf(" [Insert] [coll:%s] %v",
@ -191,16 +190,16 @@ func (stm *stream) resolveClientPacket(pk *packet) {
)
case OP_QUERY:
flags := ReadInt32(pk.payload)
flags := ReadInt32(pk.payload)
fullCollectionName := ReadString(pk.payload)
numberToSkip := ReadInt32(pk.payload)
numberToReturn := ReadInt32(pk.payload)
numberToSkip := ReadInt32(pk.payload)
numberToReturn := ReadInt32(pk.payload)
_ = flags
_ = numberToSkip
_ = numberToReturn
command := ReadBson2Json(pk.payload)
selector := ReadBson2Json(pk.payload)
command := ReadBson2Json(pk.payload)
selector := ReadBson2Json(pk.payload)
msg = fmt.Sprintf(" [Query] [coll:%s] %v %v",
fullCollectionName,
@ -209,11 +208,11 @@ func (stm *stream) resolveClientPacket(pk *packet) {
)
case OP_COMMAND:
database := ReadString(pk.payload)
commandName := ReadString(pk.payload)
metaData := ReadBson2Json(pk.payload)
commandArgs := ReadBson2Json(pk.payload)
inputDocs := ReadBson2Json(pk.payload)
database := ReadString(pk.payload)
commandName := ReadString(pk.payload)
metaData := ReadBson2Json(pk.payload)
commandArgs := ReadBson2Json(pk.payload)
inputDocs := ReadBson2Json(pk.payload)
msg = fmt.Sprintf(" [Commend] [DB:%s] [Cmd:%s] %v %v %v",
database,
@ -224,10 +223,10 @@ func (stm *stream) resolveClientPacket(pk *packet) {
)
case OP_GET_MORE:
zero := ReadInt32(pk.payload)
zero := ReadInt32(pk.payload)
fullCollectionName := ReadString(pk.payload)
numberToReturn := ReadInt32(pk.payload)
cursorId := ReadInt64(pk.payload)
numberToReturn := ReadInt32(pk.payload)
cursorId := ReadInt64(pk.payload)
_ = zero
msg = fmt.Sprintf(" [Query more] [coll:%s] [num of reply:%v] [cursor:%v]",
@ -237,10 +236,10 @@ func (stm *stream) resolveClientPacket(pk *packet) {
)
case OP_DELETE:
zero := ReadInt32(pk.payload)
zero := ReadInt32(pk.payload)
fullCollectionName := ReadString(pk.payload)
flags := ReadInt32(pk.payload)
selector := ReadBson2Json(pk.payload)
flags := ReadInt32(pk.payload)
selector := ReadBson2Json(pk.payload)
_ = zero
_ = flags
@ -266,7 +265,7 @@ func readStream(r io.Reader) (*packet, error) {
//header
header := make([]byte, 16)
if _, err := io.ReadFull(r, header); err != nil {
return nil,err
return nil, err
}
// message length

View File

@ -773,7 +773,7 @@ func (d *decodeState) isNull(off int) bool {
// name consumes a const or function from d.data[d.off-1:], decoding into the value v.
// the first byte of the function name has been read already.
func (d *decodeState) name(v reflect.Value) {
if d.isNull(d.off-1) {
if d.isNull(d.off - 1) {
d.literal(v)
return
}
@ -1076,9 +1076,9 @@ func (d *decodeState) storeKeyed(v reflect.Value) bool {
}
var (
trueBytes = []byte("true")
trueBytes = []byte("true")
falseBytes = []byte("false")
nullBytes = []byte("null")
nullBytes = []byte("null")
)
func (d *decodeState) storeValue(v reflect.Value, from interface{}) {

View File

@ -4,9 +4,9 @@ import (
"encoding/binary"
"encoding/json"
"fmt"
"time"
"io"
"github.com/40t/go-sniffer/plugSrc/mongodb/build/bson"
"io"
"time"
)
func GetNowStr(isClient bool) string {
@ -15,7 +15,7 @@ func GetNowStr(isClient bool) string {
msg += time.Now().Format(layout)
if isClient {
msg += "| cli -> ser |"
}else{
} else {
msg += "| ser -> cli |"
}
return msg
@ -54,7 +54,7 @@ func ReadString(r io.Reader) string {
return string(result)
}
func ReadBson2Json(r io.Reader) (string) {
func ReadBson2Json(r io.Reader) string {
//read len
docLen := ReadInt32(r)
@ -83,4 +83,3 @@ func ReadBson2Json(r io.Reader) (string) {
}
return string(jsonStr)
}

View File

@ -1,67 +1,67 @@
package build
const (
ComQueryRequestPacket string = "【Query】"
OkPacket string = "【Ok】"
ErrorPacket string = "【Err】"
PreparePacket string = "【Pretreatment】"
ComQueryRequestPacket string = "【Query】"
OkPacket string = "【Ok】"
ErrorPacket string = "【Err】"
PreparePacket string = "【Pretreatment】"
SendClientHandshakePacket string = "【User Auth】"
SendServerHandshakePacket string = "【Login】"
)
const (
COM_SLEEP byte = 0
COM_QUIT = 1
COM_INIT_DB = 2
COM_QUERY = 3
COM_FIELD_LIST = 4
COM_CREATE_DB = 5
COM_DROP_DB = 6
COM_REFRESH = 7
COM_SHUTDOWN = 8
COM_STATISTICS = 9
COM_PROCESS_INFO = 10
COM_CONNECT = 11
COM_PROCESS_KILL = 12
COM_DEBUG = 13
COM_PING = 14
COM_TIME = 15
COM_DELAYED_INSERT = 16
COM_CHANGE_USER = 17
COM_BINLOG_DUMP = 18
COM_TABLE_DUMP = 19
COM_CONNECT_OUT = 20
COM_REGISTER_SLAVE = 21
COM_STMT_PREPARE = 22
COM_STMT_EXECUTE = 23
COM_STMT_SEND_LONG_DATA = 24
COM_STMT_CLOSE = 25
COM_STMT_RESET = 26
COM_SET_OPTION = 27
COM_STMT_FETCH = 28
COM_DAEMON = 29
COM_BINLOG_DUMP_GTID = 30
COM_RESET_CONNECTION = 31
COM_SLEEP byte = 0
COM_QUIT = 1
COM_INIT_DB = 2
COM_QUERY = 3
COM_FIELD_LIST = 4
COM_CREATE_DB = 5
COM_DROP_DB = 6
COM_REFRESH = 7
COM_SHUTDOWN = 8
COM_STATISTICS = 9
COM_PROCESS_INFO = 10
COM_CONNECT = 11
COM_PROCESS_KILL = 12
COM_DEBUG = 13
COM_PING = 14
COM_TIME = 15
COM_DELAYED_INSERT = 16
COM_CHANGE_USER = 17
COM_BINLOG_DUMP = 18
COM_TABLE_DUMP = 19
COM_CONNECT_OUT = 20
COM_REGISTER_SLAVE = 21
COM_STMT_PREPARE = 22
COM_STMT_EXECUTE = 23
COM_STMT_SEND_LONG_DATA = 24
COM_STMT_CLOSE = 25
COM_STMT_RESET = 26
COM_SET_OPTION = 27
COM_STMT_FETCH = 28
COM_DAEMON = 29
COM_BINLOG_DUMP_GTID = 30
COM_RESET_CONNECTION = 31
)
const (
MYSQL_TYPE_DECIMAL byte = 0
MYSQL_TYPE_TINY = 1
MYSQL_TYPE_SHORT = 2
MYSQL_TYPE_LONG = 3
MYSQL_TYPE_FLOAT = 4
MYSQL_TYPE_DOUBLE = 5
MYSQL_TYPE_NULL = 6
MYSQL_TYPE_TIMESTAMP = 7
MYSQL_TYPE_LONGLONG = 8
MYSQL_TYPE_INT24 = 9
MYSQL_TYPE_DATE = 10
MYSQL_TYPE_TIME = 11
MYSQL_TYPE_DATETIME = 12
MYSQL_TYPE_YEAR = 13
MYSQL_TYPE_NEWDATE = 14
MYSQL_TYPE_VARCHAR = 15
MYSQL_TYPE_BIT = 16
MYSQL_TYPE_DECIMAL byte = 0
MYSQL_TYPE_TINY = 1
MYSQL_TYPE_SHORT = 2
MYSQL_TYPE_LONG = 3
MYSQL_TYPE_FLOAT = 4
MYSQL_TYPE_DOUBLE = 5
MYSQL_TYPE_NULL = 6
MYSQL_TYPE_TIMESTAMP = 7
MYSQL_TYPE_LONGLONG = 8
MYSQL_TYPE_INT24 = 9
MYSQL_TYPE_DATE = 10
MYSQL_TYPE_TIME = 11
MYSQL_TYPE_DATETIME = 12
MYSQL_TYPE_YEAR = 13
MYSQL_TYPE_NEWDATE = 14
MYSQL_TYPE_VARCHAR = 15
MYSQL_TYPE_BIT = 16
)
const (

View File

@ -1,30 +1,30 @@
package build
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"github.com/google/gopacket"
"io"
"bytes"
"errors"
"log"
"os"
"strconv"
"strings"
"sync"
"time"
"fmt"
"encoding/binary"
"strings"
"os"
)
const (
Port = 3306
Version = "0.1"
CmdPort = "-p"
Port = 3306
Version = "0.1"
CmdPort = "-p"
)
type Mysql struct {
port int
version string
source map[string]*stream
port int
version string
source map[string]*stream
}
type stream struct {
@ -34,20 +34,21 @@ type stream struct {
type packet struct {
isClientFlow bool
seq int
length int
payload []byte
seq int
length int
payload []byte
}
var mysql *Mysql
var once sync.Once
func NewInstance() *Mysql {
once.Do(func() {
mysql = &Mysql{
port :Port,
version:Version,
source: make(map[string]*stream),
port: Port,
version: Version,
source: make(map[string]*stream),
}
})
@ -63,8 +64,8 @@ func (m *Mysql) ResolveStream(net, transport gopacket.Flow, buf io.Reader) {
if _, ok := m.source[uuid]; !ok {
var newStream = stream{
packets:make(chan *packet, 100),
stmtMap:make(map[uint32]*Stmt),
packets: make(chan *packet, 100),
stmtMap: make(map[uint32]*Stmt),
}
m.source[uuid] = &newStream
@ -86,31 +87,31 @@ func (m *Mysql) ResolveStream(net, transport gopacket.Flow, buf io.Reader) {
}
func (m *Mysql) BPFFilter() string {
return "tcp and port "+strconv.Itoa(m.port);
return "tcp and port " + strconv.Itoa(m.port)
}
func (m *Mysql) Version() string {
return Version
}
func (m *Mysql) SetFlag(flg []string) {
func (m *Mysql) SetFlag(flg []string) {
c := len(flg)
if c == 0 {
return
}
if c >> 1 == 0 {
if c>>1 == 0 {
fmt.Println("ERR : Mysql Number of parameters")
os.Exit(1)
}
for i:=0;i<c;i=i+2 {
for i := 0; i < c; i = i + 2 {
key := flg[i]
val := flg[i+1]
switch key {
case CmdPort:
port, err := strconv.Atoi(val);
port, err := strconv.Atoi(val)
m.port = port
if err != nil {
panic("ERR : port")
@ -145,13 +146,13 @@ func (m *Mysql) newPacket(net, transport gopacket.Flow, r io.Reader) *packet {
//generate new packet
var pk = packet{
seq: int(seq),
length:payload.Len(),
payload:payload.Bytes(),
seq: int(seq),
length: payload.Len(),
payload: payload.Bytes(),
}
if transport.Src().String() == strconv.Itoa(Port) {
pk.isClientFlow = false
}else{
} else {
pk.isClientFlow = true
}
@ -187,7 +188,7 @@ func (m *Mysql) resolvePacketTo(r io.Reader, w io.Writer) (uint8, error) {
func (stm *stream) resolve() {
for {
select {
case packet := <- stm.packets:
case packet := <-stm.packets:
if packet.isClientFlow {
stm.resolveClientPacket(packet.payload, packet.seq)
} else {
@ -197,10 +198,10 @@ func (stm *stream) resolve() {
}
}
func (stm *stream) findStmtPacket (srv chan *packet, seq int) *packet {
func (stm *stream) findStmtPacket(srv chan *packet, seq int) *packet {
for {
select {
case packet, ok := <- stm.packets:
case packet, ok := <-stm.packets:
if !ok {
return nil
}
@ -218,23 +219,23 @@ func (stm *stream) resolveServerPacket(payload []byte, seq int) {
var msg = ""
switch payload[0] {
case 0xff:
errorCode := int(binary.LittleEndian.Uint16(payload[1:3]))
errorMsg,_ := ReadStringFromByte(payload[4:])
case 0xff:
errorCode := int(binary.LittleEndian.Uint16(payload[1:3]))
errorMsg, _ := ReadStringFromByte(payload[4:])
msg = GetNowStr(false)+"%s Err code:%s,Err msg:%s"
msg = fmt.Sprintf(msg, ErrorPacket, strconv.Itoa(errorCode), strings.TrimSpace(errorMsg))
msg = GetNowStr(false) + "%s Err code:%s,Err msg:%s"
msg = fmt.Sprintf(msg, ErrorPacket, strconv.Itoa(errorCode), strings.TrimSpace(errorMsg))
case 0x00:
var pos = 1
l,_ := LengthBinary(payload[pos:])
affectedRows := int(l)
case 0x00:
var pos = 1
l, _ := LengthBinary(payload[pos:])
affectedRows := int(l)
msg += GetNowStr(false)+"%s Effect Row:%s"
msg = fmt.Sprintf(msg, OkPacket, strconv.Itoa(affectedRows))
msg += GetNowStr(false) + "%s Effect Row:%s"
msg = fmt.Sprintf(msg, OkPacket, strconv.Itoa(affectedRows))
default:
return
default:
return
}
fmt.Println(msg)
@ -274,14 +275,14 @@ func (stm *stream) resolveClientPacket(payload []byte, seq int) {
stm.stmtMap[stmtID] = stmt
stmt.FieldCount = binary.LittleEndian.Uint16(serverPacket.payload[5:7])
stmt.ParamCount = binary.LittleEndian.Uint16(serverPacket.payload[7:9])
stmt.Args = make([]interface{}, stmt.ParamCount)
stmt.Args = make([]interface{}, stmt.ParamCount)
msg = PreparePacket+stmt.Query
msg = PreparePacket + stmt.Query
case COM_STMT_SEND_LONG_DATA:
stmtID := binary.LittleEndian.Uint32(payload[1:5])
paramId := binary.LittleEndian.Uint16(payload[5:7])
stmt, _ := stm.stmtMap[stmtID]
stmtID := binary.LittleEndian.Uint32(payload[1:5])
paramId := binary.LittleEndian.Uint16(payload[5:7])
stmt, _ := stm.stmtMap[stmtID]
if stmt.Args[paramId] == nil {
stmt.Args[paramId] = payload[7:]
@ -295,7 +296,7 @@ func (stm *stream) resolveClientPacket(payload []byte, seq int) {
case COM_STMT_RESET:
stmtID := binary.LittleEndian.Uint32(payload[1:5])
stmt, _:= stm.stmtMap[stmtID]
stmt, _ := stm.stmtMap[stmtID]
stmt.Args = make([]interface{}, stmt.ParamCount)
return
case COM_STMT_EXECUTE:
@ -324,7 +325,7 @@ func (stm *stream) resolveClientPacket(payload []byte, seq int) {
pos++
var pTypes []byte
var pTypes []byte
var pValues []byte
//if flag == 1
@ -348,4 +349,3 @@ func (stm *stream) resolveClientPacket(payload []byte, seq int) {
fmt.Println(GetNowStr(true) + msg)
}

View File

@ -3,10 +3,10 @@ package build
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"math"
"strings"
"errors"
)
type Stmt struct {

View File

@ -12,13 +12,13 @@ func GetNowStr(isClient bool) string {
msg += time.Now().Format("2006-01-02 15:04:05")
if isClient {
msg += "| cli -> ser |"
}else{
} else {
msg += "| ser -> cli |"
}
return msg
}
func ReadStringFromByte(b []byte) (string,int) {
func ReadStringFromByte(b []byte) (string, int) {
var l int
l = bytes.IndexByte(b, 0x00)
@ -35,18 +35,18 @@ func LengthBinary(b []byte) (uint32, int) {
return uint32(first), 1
}
if first == 251 {
return 0,1
return 0, 1
}
if first == 252 {
return binary.LittleEndian.Uint32(b[1:2]),1
return binary.LittleEndian.Uint32(b[1:2]), 1
}
if first == 253 {
return binary.LittleEndian.Uint32(b[1:4]),3
return binary.LittleEndian.Uint32(b[1:4]), 3
}
if first == 254 {
return binary.LittleEndian.Uint32(b[1:9]),8
return binary.LittleEndian.Uint32(b[1:9]), 8
}
return 0,0
return 0, 0
}
func LengthEncodedInt(input []byte) (num uint64, isNull bool, n int) {

View File

@ -1,33 +1,33 @@
package build
import (
"bufio"
"fmt"
"github.com/google/gopacket"
"io"
"strings"
"fmt"
"strconv"
"bufio"
"strings"
)
type Redis struct {
port int
port int
version string
cmd chan string
done chan bool
cmd chan string
done chan bool
}
const (
Port int = 6379
Port int = 6379
Version string = "0.1"
CmdPort string = "-p"
)
var redis = &Redis {
port:Port,
version:Version,
var redis = &Redis{
port: Port,
version: Version,
}
func NewInstance() *Redis{
func NewInstance() *Redis {
return redis
}
@ -63,9 +63,9 @@ func (red Redis) ResolveStream(net, transport gopacket.Flow, r io.Reader) {
l := string(line[1])
cmdCount, _ = strconv.Atoi(l)
cmd = ""
for j := 0; j < cmdCount * 2; j++ {
for j := 0; j < cmdCount*2; j++ {
c, _, _ := buf.ReadLine()
if j & 1 == 0 {
if j&1 == 0 {
continue
}
cmd += " " + string(c)
@ -75,23 +75,23 @@ func (red Redis) ResolveStream(net, transport gopacket.Flow, r io.Reader) {
}
/**
SetOption
*/
func (red *Redis) SetFlag(flg []string) {
SetOption
*/
func (red *Redis) SetFlag(flg []string) {
c := len(flg)
if c == 0 {
return
}
if c >> 1 != 1 {
if c>>1 != 1 {
panic("ERR : Redis num of params")
}
for i:=0;i<c;i=i+2 {
for i := 0; i < c; i = i + 2 {
key := flg[i]
val := flg[i+1]
switch key {
case CmdPort:
port, err := strconv.Atoi(val);
port, err := strconv.Atoi(val)
redis.port = port
if err != nil {
panic("ERR : Port error")
@ -107,16 +107,15 @@ func (red *Redis) SetFlag(flg []string) {
}
/**
BPFFilter
*/
BPFFilter
*/
func (red *Redis) BPFFilter() string {
return "tcp and port "+strconv.Itoa(redis.port)
return "tcp and port " + strconv.Itoa(redis.port)
}
/**
Version
*/
Version
*/
func (red *Redis) Version() string {
return red.version
}