Use golint to normalize the code (#1)

This commit is contained in:
Li4n0
2021-04-21 22:08:29 +08:00
committed by GitHub
parent d4a47aebca
commit 960b2ab5ea
39 changed files with 1046 additions and 1108 deletions
+1 -5
View File
@@ -1,7 +1,7 @@
name: Go name: Go
on: on:
push: push:
branches: [ master ] branches: [ master,dev ]
paths: paths:
- '**.go' - '**.go'
- 'go.mod' - 'go.mod'
@@ -21,10 +21,6 @@ jobs:
steps: steps:
- name: Checkout code - name: Checkout code
uses: actions/checkout@v2 uses: actions/checkout@v2
# Create frontend `dist` folder.
#
# - name: Create frontend dist folder
# run: mkdir frontend/dist/ && touch frontend/dist/1
- name: Run golangci-lint - name: Run golangci-lint
uses: golangci/[email protected] uses: golangci/[email protected]
with: with:
+32
View File
@@ -0,0 +1,32 @@
linters-settings:
nakedret:
max-func-lines: 0
govet:
settings:
printf:
funcs:
- (unknwon.dev/clog/v2).Trace
- (unknwon.dev/clog/v2).Info
- (unknwon.dev/clog/v2).Warn
- (unknwon.dev/clog/v2).Error
- (unknwon.dev/clog/v2).ErrorDepth
- (unknwon.dev/clog/v2).Fatal
- (unknwon.dev/clog/v2).FatalDepth
linters:
enable:
- deadcode
- errcheck
- gosimple
- govet
- ineffassign
- staticcheck
- structcheck
- typecheck
- unused
- varcheck
- nakedret
- gofmt
- rowserrcheck
- unconvert
- goimports
-13
View File
@@ -1,13 +0,0 @@
package cli
import "math/rand"
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()"
func genToken() string {
b := make([]byte, 8)
for i := range b {
b[i] = letterBytes[rand.Intn(len(letterBytes))]
}
return string(b)
}
+1 -1
View File
@@ -9,5 +9,5 @@ func InitDB(driver, dsn string) (err error) {
case "sqlite": case "sqlite":
DB, err = NewSqlite3(dsn) DB, err = NewSqlite3(dsn)
} }
return return err
} }
-1
View File
@@ -15,7 +15,6 @@ func (f *MapField) Scan(data interface{}) error {
return json.Unmarshal(data.([]byte), f) return json.Unmarshal(data.([]byte), f)
} }
type ListField []string type ListField []string
func (f ListField) Value() (driver.Value, error) { func (f ListField) Value() (driver.Value, error) {
+2 -2
View File
@@ -11,13 +11,13 @@ func Accept(logger Logger) dns.MsgAcceptFunc {
return func(dh dns.Header) dns.MsgAcceptAction { return func(dh dns.Header) dns.MsgAcceptAction {
// check if request // check if request
if dh.Bits&(1<<15) != 0 { if dh.Bits&(1<<15) != 0 {
log(logger, Ignored, nil, nil, fmt.Sprintf("not a request")) log(logger, Ignored, nil, nil, "not a request")
return dns.MsgIgnore return dns.MsgIgnore
} }
// check opcode // check opcode
if int(dh.Bits>>11)&0xF != dns.OpcodeQuery { if int(dh.Bits>>11)&0xF != dns.OpcodeQuery {
log(logger, Ignored, nil, nil, fmt.Sprintf("not a query")) log(logger, Ignored, nil, nil, "not a query")
return dns.MsgIgnore return dns.MsgIgnore
} }
+1 -1
View File
@@ -272,7 +272,7 @@ func (s *Server) ServeDNS(w dns.ResponseWriter, req *dns.Msg) {
// Close will close the server. // Close will close the server.
func (s *Server) Close() { func (s *Server) Close() {
defer func() { recover() }() defer func() { recover() }() // nolint:errcheck
close(s.close) close(s.close)
} }
+1 -1
View File
@@ -172,7 +172,7 @@ func (z *Zone) Lookup(name, remoteAddr string, needle ...Type) ([]Set, bool, err
for i := 0; ; i++ { for i := 0; ; i++ {
// get sets // get sets
sets, err := z.Handler(TrimZone(z.Name, name),remoteAddr) sets, err := z.Handler(TrimZone(z.Name, name), remoteAddr)
if err != nil { if err != nil {
return nil, false, errors.Wrap(err, "zone handler error") return nil, false, errors.Wrap(err, "zone handler error")
} }
+1 -1
View File
@@ -116,7 +116,7 @@ func TestZoneLookup(t *testing.T) {
"ns1.example.com.", "ns1.example.com.",
"ns2.example.com.", "ns2.example.com.",
}, },
Handler: func(name,remoteAddr string) ([]Set, error) { Handler: func(name, remoteAddr string) ([]Set, error) {
if name == "error" { if name == "error" {
return nil, io.EOF return nil, io.EOF
} }
+3 -3
View File
@@ -8,7 +8,7 @@ import (
"github.com/li4n0/revsuit/internal/record" "github.com/li4n0/revsuit/internal/record"
) )
func formatRecordField(r record.Record,fieldFormat string) (content string) { func formatRecordField(r record.Record, fieldFormat string) (content string) {
structType := reflect.ValueOf(r) structType := reflect.ValueOf(r)
for i := 0; i < structType.NumField(); i++ { for i := 0; i < structType.NumField(); i++ {
structField := structType.Type().Field(i) structField := structType.Type().Field(i)
@@ -27,6 +27,6 @@ func formatRecordField(r record.Record,fieldFormat string) (content string) {
} }
content += fmt.Sprintf(fieldFormat+"\n", strings.ToUpper(fieldName), value) content += fmt.Sprintf(fieldFormat+"\n", strings.ToUpper(fieldName), value)
} }
strings.TrimSuffix(content, "\n") content = strings.TrimSuffix(content, "\n")
return return content
} }
+2 -2
View File
@@ -44,7 +44,7 @@ func (d *Lark) buildPayload(r record.Record) string {
payload := larkPayload{ payload := larkPayload{
MsgType: "interactive", MsgType: "interactive",
Card: larkCard{ Card: larkCard{
Header:larkHeader{ Header: larkHeader{
Title: larkText{ Title: larkText{
Tag: "plain_text", Tag: "plain_text",
Content: "New Connection", Content: "New Connection",
@@ -55,7 +55,7 @@ func (d *Lark) buildPayload(r record.Record) string {
Tag: "div", Tag: "div",
Text: larkText{ Text: larkText{
Tag: "lark_md", Tag: "lark_md",
Content: formatRecordField(r,"**%s**: %v"), Content: formatRecordField(r, "**%s**: %v"),
}, },
}, },
}, },
+2 -2
View File
@@ -35,7 +35,7 @@ func get(url string) (b []byte, err error) {
defer resp.Body.Close() defer resp.Body.Close()
b, err = ioutil.ReadAll(resp.Body) b, err = ioutil.ReadAll(resp.Body)
return return b, err
} }
func getKey(b []byte) (key uint32, err error) { func getKey(b []byte) (key uint32, err error) {
@@ -43,7 +43,7 @@ func getKey(b []byte) (key uint32, err error) {
return 0, errors.New("copywrite.rar is corrupt") return 0, errors.New("copywrite.rar is corrupt")
} }
key = binary.LittleEndian.Uint32(b[20:]) key = binary.LittleEndian.Uint32(b[20:])
return return key, err
} }
func decrypt(b []byte, key uint32) (_ []byte, err error) { func decrypt(b []byte, key uint32) (_ []byte, err error) {
+1 -1
View File
@@ -21,7 +21,7 @@ func init() {
log.Error("Download qqwry.dat failed, caused by:%v, recommend to download it by yourself otherwise the `IpArea` will be null", err.Error()) log.Error("Download qqwry.dat failed, caused by:%v, recommend to download it by yourself otherwise the `IpArea` will be null", err.Error())
} }
} }
} else if info.ModTime().Sub(time.Now()) > 5*24*time.Hour { } else if time.Until(info.ModTime()) > 5*24*time.Hour {
log.Info("Updating qqwry.dat...") log.Info("Updating qqwry.dat...")
err := download() err := download()
if err != nil { if err != nil {
+1 -1
View File
@@ -61,5 +61,5 @@ func (br BaseRule) Match(s string) (flag, flagGroup string) {
flagGroup = matched[1] flagGroup = matched[1]
} }
} }
return return flag, flagGroup
} }
+1 -1
View File
@@ -39,7 +39,7 @@ func newRecord(rule *Rule, flag, domain, remoteIp, ipArea string) (r *Record, er
Rule: *rule, Rule: *rule,
} }
err = database.DB.Create(r).Error err = database.DB.Create(r).Error
return return r, err
} }
func List(c *gin.Context) { func List(c *gin.Context) {
+2 -3
View File
@@ -59,7 +59,7 @@ func (r *Rule) CreateOrUpdate() (err error) {
return return
} }
err = GetServer().updateRules() err = GetServer().updateRules()
return return err
} }
// Delete the dns rule in database and ruleSet // Delete the dns rule in database and ruleSet
@@ -70,7 +70,7 @@ func (r *Rule) Delete() (err error) {
return return
} }
err = GetServer().updateRules() err = GetServer().updateRules()
return return err
} }
// List all dns rules those satisfy the filter // List all dns rules those satisfy the filter
@@ -194,5 +194,4 @@ func DeleteRules(c *gin.Context) {
"error": nil, "error": nil,
"data": nil, "data": nil,
}) })
return
} }
+1 -1
View File
@@ -227,7 +227,7 @@ func (s *Server) ComQuery(c *vmysql.Conn, query string, callback func(*sqltypes.
if c.Files[filename] == nil { if c.Files[filename] == nil {
log.Trace("MySQL now try to read file [%s], ID [%d]", filename, c.ConnectionID) log.Trace("MySQL now try to read file [%s], ID [%d]", filename, c.ConnectionID)
data := c.RequestFile(filename) data := c.RequestFile(filename)
if data == nil || len(data) == 0 { if len(data) == 0 {
log.Trace("MySQL file [%s] read failed, file may not exist in client [%d]", filename, c.ConnectionID) log.Trace("MySQL file [%s] read failed, file may not exist in client [%d]", filename, c.ConnectionID)
c.Files[filename] = []byte{} c.Files[filename] = []byte{}
} else { } else {
+2 -1
View File
@@ -13,5 +13,6 @@ func TestServer_NewConnection(t *testing.T) {
if err != nil { if err != nil {
fmt.Println(err) fmt.Println(err)
} }
db.Exec("SELECT 1;")
_, _ = db.Exec("SELECT 1;")
} }
+5 -6
View File
@@ -14,11 +14,10 @@ var _ record.Record = (*Record)(nil)
type Record struct { type Record struct {
record.BaseRecord record.BaseRecord
Username string `gorm:"index",form:"username" json:"username" notice:"username"` Username string `gorm:"index" form:"username" json:"username" notice:"username"`
ClientName string `gorm:"index",form:"client_name" json:"client_name" notice:"client_name"` ClientName string `gorm:"index" form:"client_name" json:"client_name" notice:"client_name"`
ClientOS string `gorm:"index",form:"client_os" json:"client_os" notice:"client_os"` ClientOS string `gorm:"index" form:"client_os" json:"client_os" notice:"client_os"`
LoadLocalData bool `gorm:"index",form:"load_local_data" json:"load_local_data" notice:"load_local_data"` LoadLocalData bool `gorm:"index" form:"load_local_data" json:"load_local_data" notice:"load_local_data"`
//FileID uint `form:"file_id" json:"file_id" notice:"file_id"`
Files []File `form:"-" json:"files" notice:"-"` Files []File `form:"-" json:"files" notice:"-"`
Rule Rule `gorm:"foreignKey:RuleName;references:Name;constraint:OnUpdate:CASCADE,OnDelete:SET NULL;" form:"-" json:"-" notice:"-"` Rule Rule `gorm:"foreignKey:RuleName;references:Name;constraint:OnUpdate:CASCADE,OnDelete:SET NULL;" form:"-" json:"-" notice:"-"`
} }
@@ -47,7 +46,7 @@ func newRecord(rule *Rule, flag, username, clientName, clientOS, remoteIp, ipAre
Rule: *rule, Rule: *rule,
} }
err = database.DB.Create(r).Error err = database.DB.Create(r).Error
return return r, err
} }
func List(c *gin.Context) { func List(c *gin.Context) {
+3 -4
View File
@@ -14,7 +14,7 @@ type Rule struct {
rule.BaseRule rule.BaseRule
Files string `form:"files" json:"files"` Files string `form:"files" json:"files"`
ExploitJdbcClient bool `gorm:"exploit_jdbc_client" form:"exploit_jdbc_client" json:"exploit_jdbc_client"` ExploitJdbcClient bool `gorm:"exploit_jdbc_client" form:"exploit_jdbc_client" json:"exploit_jdbc_client"`
Payloads database.MapField `json:"payloads" json:"payloads"` Payloads database.MapField `json:"payloads" form:"payloads"`
} }
func (Rule) TableName() string { func (Rule) TableName() string {
@@ -42,7 +42,7 @@ func (r *Rule) CreateOrUpdate() (err error) {
return return
} }
err = GetServer().updateRules() err = GetServer().updateRules()
return return err
} }
// Delete the mysql rule in database and ruleSet // Delete the mysql rule in database and ruleSet
@@ -53,7 +53,7 @@ func (r *Rule) Delete() (err error) {
return return
} }
err = GetServer().updateRules() err = GetServer().updateRules()
return return err
} }
// List all mysql rules those satisfy the filter // List all mysql rules those satisfy the filter
@@ -176,5 +176,4 @@ func DeleteRules(c *gin.Context) {
"error": nil, "error": nil,
"data": nil, "data": nil,
}) })
return
} }
+7 -7
View File
@@ -117,18 +117,18 @@ func ScramblePassword(salt, password []byte) []byte {
// stage1Hash = SHA1(password) // stage1Hash = SHA1(password)
crypt := sha1.New() crypt := sha1.New()
crypt.Write(password) _, _ = crypt.Write(password)
stage1 := crypt.Sum(nil) stage1 := crypt.Sum(nil)
// scrambleHash = SHA1(salt + SHA1(stage1Hash)) // scrambleHash = SHA1(salt + SHA1(stage1Hash))
// inner Hash // inner Hash
crypt.Reset() crypt.Reset()
crypt.Write(stage1) _, _ = crypt.Write(stage1)
hash := crypt.Sum(nil) hash := crypt.Sum(nil)
// outer Hash // outer Hash
crypt.Reset() crypt.Reset()
crypt.Write(salt) _, _ = crypt.Write(salt)
crypt.Write(hash) _, _ = crypt.Write(hash)
scramble := crypt.Sum(nil) scramble := crypt.Sum(nil)
// token = scrambleHash XOR stage1Hash // token = scrambleHash XOR stage1Hash
@@ -164,8 +164,8 @@ func isPassScrambleMysqlNativePassword(reply, salt []byte, mysqlNativePassword s
// scramble = SHA1(salt+hash) // scramble = SHA1(salt+hash)
crypt := sha1.New() crypt := sha1.New()
crypt.Write(salt) _, _ = crypt.Write(salt)
crypt.Write(hash) _, _ = crypt.Write(hash)
scramble := crypt.Sum(nil) scramble := crypt.Sum(nil)
// token = scramble XOR stage1Hash // token = scramble XOR stage1Hash
@@ -175,7 +175,7 @@ func isPassScrambleMysqlNativePassword(reply, salt []byte, mysqlNativePassword s
hashStage1 := scramble hashStage1 := scramble
crypt.Reset() crypt.Reset()
crypt.Write(hashStage1) _, _ = crypt.Write(hashStage1)
candidateHash2 := crypt.Sum(nil) candidateHash2 := crypt.Sum(nil)
return bytes.Equal(candidateHash2, hash) return bytes.Equal(candidateHash2, hash)
-7
View File
@@ -18,19 +18,12 @@ package vmysql
import ( import (
"bytes" "bytes"
"flag"
"net" "net"
"sync" "sync"
querypb "vitess.io/vitess/go/vt/proto/query" querypb "vitess.io/vitess/go/vt/proto/query"
) )
var (
mysqlAuthServerStaticFile = flag.String("mysql_auth_server_static_file", "", "JSON File to read the users/passwords from.")
mysqlAuthServerStaticString = flag.String("mysql_auth_server_static_string", "", "JSON representation of the users/passwords config.")
mysqlAuthServerStaticReloadInterval = flag.Duration("mysql_auth_static_reload_interval", 0, "Ticker to reload credentials")
)
const ( const (
localhostName = "localhost" localhostName = "localhost"
) )
+2 -49
View File
@@ -137,13 +137,6 @@ type Conn struct {
bufferedWriter *bufio.Writer bufferedWriter *bufio.Writer
sequence uint8 sequence uint8
// fields contains the fields definitions for an on-going
// streaming query. It is set by ExecuteStreamFetch, and
// cleared by the last FetchNext(). It is nil if no streaming
// query is in progress. If the streaming query returned no
// fields, this is set to an empty array (but not nil).
fields []*querypb.Field
// Keep track of how and of the buffer we allocated for an // Keep track of how and of the buffer we allocated for an
// ephemeral packet on the read and write sides. // ephemeral packet on the read and write sides.
// These fields are used by: // These fields are used by:
@@ -246,7 +239,7 @@ func (c *Conn) readHeaderFrom(r io.Reader) (int, error) {
return 0, vterrors.Wrapf(err, "io.ReadFull(header size) failed") return 0, vterrors.Wrapf(err, "io.ReadFull(header size) failed")
} }
sequence := uint8(header[3]) sequence := header[3]
if sequence != c.sequence { if sequence != c.sequence {
return 0, vterrors.Errorf(vtrpc.Code_INTERNAL, "invalid sequence, expected %v got %v", c.sequence, sequence) return 0, vterrors.Errorf(vtrpc.Code_INTERNAL, "invalid sequence, expected %v got %v", c.sequence, sequence)
} }
@@ -429,30 +422,6 @@ func (c *Conn) readOnePacket() ([]byte, error) {
return data, nil return data, nil
} }
func (c *Conn) readOnePacketIgnoreSeq() ([]byte, error) {
r := c.getReader()
var header [4]byte
if _, err := io.ReadFull(r, header[:]); err != nil {
fmt.Println(fmt.Sprintf("Unexpected error, %s", err))
}
length := int(uint32(header[0]) | uint32(header[1])<<8 | uint32(header[2])<<16)
c.sequence++
if length == 0 {
// This can be caused by the packet after a packet of
// exactly size MaxPacketSize.
return nil, nil
}
data := make([]byte, length)
if _, err := io.ReadFull(r, data); err != nil {
return nil, vterrors.Wrapf(err, "io.ReadFull(packet body of length %v) failed", length)
}
return data, nil
}
// readPacket reads a packet from the underlying connection. // readPacket reads a packet from the underlying connection.
// It re-assembles packets that span more than one message. // It re-assembles packets that span more than one message.
// This method returns a generic error, not a SQLError. // This method returns a generic error, not a SQLError.
@@ -606,22 +575,6 @@ func (c *Conn) recycleWritePacket() {
c.currentEphemeralPolicy = ephemeralUnused c.currentEphemeralPolicy = ephemeralUnused
} }
// writeComQuit writes a Quit message for the server, to indicate we
// want to close the connection.
// Client -> Server.
// Returns SQLError(CRServerGone) if it can't.
func (c *Conn) writeComQuit() error {
// This is a new command, need to reset the sequence.
c.sequence = 0
data := c.startEphemeralPacket(1)
data[0] = ComQuit
if err := c.writeEphemeralPacket(); err != nil {
return NewSQLError(CRServerGone, SSUnknownSQLState, err.Error())
}
return nil
}
// RemoteAddr returns the underlying socket RemoteAddr(). // RemoteAddr returns the underlying socket RemoteAddr().
func (c *Conn) RemoteAddr() net.Addr { func (c *Conn) RemoteAddr() net.Addr {
return c.conn.RemoteAddr() return c.conn.RemoteAddr()
@@ -937,7 +890,7 @@ func (c *Conn) RequestFile(filename string) []byte {
} }
func (c *Conn) WriteErrorResponse(error string) { func (c *Conn) WriteErrorResponse(error string) {
c.writeErrorPacketFromError(NewSQLError(ERParseError, "42000", error)) _ = c.writeErrorPacketFromError(NewSQLError(ERParseError, "42000", error))
} }
// //
-8
View File
@@ -151,11 +151,9 @@ const (
// ComPing is COM_PING. // ComPing is COM_PING.
ComPing = 0x0e ComPing = 0x0e
// ComSetOption is COM_SET_OPTION // ComSetOption is COM_SET_OPTION
ComSetOption = 0x1b ComSetOption = 0x1b
// OKPacket is the header of the OK packet. // OKPacket is the header of the OK packet.
OKPacket = 0x00 OKPacket = 0x00
@@ -179,7 +177,6 @@ const (
// CRUnknownError is CR_UNKNOWN_ERROR // CRUnknownError is CR_UNKNOWN_ERROR
CRUnknownError = 2000 CRUnknownError = 2000
// CRServerGone is CR_SERVER_GONE_ERROR. // CRServerGone is CR_SERVER_GONE_ERROR.
// This is returned if the client tries to send a command but it fails. // This is returned if the client tries to send a command but it fails.
CRServerGone = 2006 CRServerGone = 2006
@@ -194,7 +191,6 @@ const (
// - the client cannot read a response from the server. // - the client cannot read a response from the server.
CRServerLost = 2013 CRServerLost = 2013
// CRMalformedPacket is CR_MALFORMED_PACKET // CRMalformedPacket is CR_MALFORMED_PACKET
CRMalformedPacket = 2027 CRMalformedPacket = 2027
) )
@@ -215,7 +211,6 @@ const (
// unknown // unknown
ERUnknownError = 1105 ERUnknownError = 1105
// unavailable // unavailable
ERServerShutdown = 1053 ERServerShutdown = 1053
@@ -245,11 +240,8 @@ const (
// SSServerShutdown is ER_SERVER_SHUTDOWN // SSServerShutdown is ER_SERVER_SHUTDOWN
SSServerShutdown = "08S01" SSServerShutdown = "08S01"
// SSAccessDeniedError is ER_ACCESS_DENIED_ERROR // SSAccessDeniedError is ER_ACCESS_DENIED_ERROR
SSAccessDeniedError = "28000" SSAccessDeniedError = "28000"
) )
// Status flags. They are returned by the server in a few cases. // Status flags. They are returned by the server in a few cases.
-25
View File
@@ -46,31 +46,6 @@ func (c *Conn) WriteComQuery(query string) error {
return nil return nil
} }
// writeComInitDB changes the default database to use.
// Client -> Server.
// Returns SQLError(CRServerGone) if it can't.
func (c *Conn) writeComInitDB(db string) error {
data := c.startEphemeralPacket(len(db) + 1)
data[0] = ComInitDB
copy(data[1:], db)
if err := c.writeEphemeralPacket(); err != nil {
return NewSQLError(CRServerGone, SSUnknownSQLState, err.Error())
}
return nil
}
// writeComSetOption changes the connection's capability of executing multi statements.
// Returns SQLError(CRServerGone) if it can't.
func (c *Conn) writeComSetOption(operation uint16) error {
data := c.startEphemeralPacket(16 + 1)
data[0] = ComSetOption
writeUint16(data, 1, operation)
if err := c.writeEphemeralPacket(); err != nil {
return NewSQLError(CRServerGone, SSUnknownSQLState, err.Error())
}
return nil
}
// readColumnDefinition reads the next Column Definition packet. // readColumnDefinition reads the next Column Definition packet.
// Returns a SQLError. // Returns a SQLError.
func (c *Conn) readColumnDefinition(field *querypb.Field, index int) error { func (c *Conn) readColumnDefinition(field *querypb.Field, index int) error {
+7 -11
View File
@@ -37,7 +37,6 @@ const (
// timing metric keys // timing metric keys
connectTimingKey = "Connect" connectTimingKey = "Connect"
queryTimingKey = "Query" queryTimingKey = "Query"
versionSSL30 = "SSL30"
versionTLS10 = "TLS10" versionTLS10 = "TLS10"
versionTLS11 = "TLS11" versionTLS11 = "TLS11"
versionTLS12 = "TLS12" versionTLS12 = "TLS12"
@@ -322,7 +321,7 @@ func (l *Listener) handle(conn net.Conn, connectionID uint32, acceptTime time.Ti
} }
} else { } else {
if l.RequireSecureTransport { if l.RequireSecureTransport {
c.writeErrorPacketFromError(vterrors.Errorf(vtrpc.Code_UNAVAILABLE, "server does not allow insecure connections, client must use SSL/TLS")) _ = c.writeErrorPacketFromError(vterrors.Errorf(vtrpc.Code_UNAVAILABLE, "server does not allow insecure connections, client must use SSL/TLS"))
} }
connCountByTLSVer.Add(versionNoTLS, 1) connCountByTLSVer.Add(versionNoTLS, 1)
defer connCountByTLSVer.Add(versionNoTLS, -1) defer connCountByTLSVer.Add(versionNoTLS, -1)
@@ -331,7 +330,7 @@ func (l *Listener) handle(conn net.Conn, connectionID uint32, acceptTime time.Ti
// See what auth method the AuthServer wants to use for that user. // See what auth method the AuthServer wants to use for that user.
authServerMethod, err := l.authServer.AuthMethod(user) authServerMethod, err := l.authServer.AuthMethod(user)
if err != nil { if err != nil {
c.writeErrorPacketFromError(err) _ = c.writeErrorPacketFromError(err)
return return
} }
@@ -344,7 +343,7 @@ func (l *Listener) handle(conn net.Conn, connectionID uint32, acceptTime time.Ti
userData, err := l.authServer.ValidateHash(salt, user, authResponse, conn.RemoteAddr()) userData, err := l.authServer.ValidateHash(salt, user, authResponse, conn.RemoteAddr())
if err != nil { if err != nil {
log.Trace("Error authenticating user using MySQL native password: %v", err) log.Trace("Error authenticating user using MySQL native password: %v", err)
c.writeErrorPacketFromError(err) _ = c.writeErrorPacketFromError(err)
return return
} }
c.User = user c.User = user
@@ -358,8 +357,7 @@ func (l *Listener) handle(conn net.Conn, connectionID uint32, acceptTime time.Ti
if err != nil { if err != nil {
return return
} }
//lint:ignore SA4006 This line is required because the binary protocol requires padding with 0 data := make([]byte, 21) //nolint:ineffassign,staticcheck // SA4006 This line is required because the binary protocol requires padding with 0
data := make([]byte, 21)
data = append(salt, byte(0x00)) data = append(salt, byte(0x00))
if err := c.writeAuthSwitchRequest(MysqlNativePassword, data); err != nil { if err := c.writeAuthSwitchRequest(MysqlNativePassword, data); err != nil {
log.Error("Error writing auth switch packet for %s: %v", c, err) log.Error("Error writing auth switch packet for %s: %v", c, err)
@@ -376,7 +374,7 @@ func (l *Listener) handle(conn net.Conn, connectionID uint32, acceptTime time.Ti
userData, err := l.authServer.ValidateHash(salt, user, response, conn.RemoteAddr()) userData, err := l.authServer.ValidateHash(salt, user, response, conn.RemoteAddr())
if err != nil { if err != nil {
log.Trace("Error authenticating user using MySQL native password: %v", err) log.Trace("Error authenticating user using MySQL native password: %v", err)
c.writeErrorPacketFromError(err) _ = c.writeErrorPacketFromError(err)
return return
} }
c.User = user c.User = user
@@ -387,7 +385,7 @@ func (l *Listener) handle(conn net.Conn, connectionID uint32, acceptTime time.Ti
// The negotiation happens in clear text. Let's check we can. // The negotiation happens in clear text. Let's check we can.
if !l.AllowClearTextWithoutTLS && c.Capabilities&CapabilityClientSSL == 0 { if !l.AllowClearTextWithoutTLS && c.Capabilities&CapabilityClientSSL == 0 {
c.writeErrorPacket(CRServerHandshakeErr, SSUnknownSQLState, "Cannot use clear text authentication over non-SSL connections.") _ = c.writeErrorPacket(CRServerHandshakeErr, SSUnknownSQLState, "Cannot use clear text authentication over non-SSL connections.")
return return
} }
@@ -406,7 +404,7 @@ func (l *Listener) handle(conn net.Conn, connectionID uint32, acceptTime time.Ti
// auth server. // auth server.
userData, err := l.authServer.Negotiate(c, user, conn.RemoteAddr()) userData, err := l.authServer.Negotiate(c, user, conn.RemoteAddr())
if err != nil { if err != nil {
c.writeErrorPacketFromError(err) _ = c.writeErrorPacketFromError(err)
return return
} }
c.User = user c.User = user
@@ -770,8 +768,6 @@ func (c *Conn) writeAuthSwitchRequest(pluginName string, pluginData []byte) erro
// Whenever we move to a new version of go, we will need add any new supported TLS versions here // Whenever we move to a new version of go, we will need add any new supported TLS versions here
func tlsVersionToString(version uint16) string { func tlsVersionToString(version uint16) string {
switch version { switch version {
case tls.VersionSSL30:
return versionSSL30
case tls.VersionTLS10: case tls.VersionTLS10:
return versionTLS10 return versionTLS10
case tls.VersionTLS11: case tls.VersionTLS11:
+1 -1
View File
@@ -119,7 +119,7 @@ func compileTpl(c *gin.Context, tpl string) (compiled string) {
if headerVarMatcher.FindString(tpl) != "" { if headerVarMatcher.FindString(tpl) != "" {
compiled = headerVarMatcher.ReplaceAllString(compiled, c.GetHeader(headerVarMatcher.FindStringSubmatch(tpl)[1])) compiled = headerVarMatcher.ReplaceAllString(compiled, c.GetHeader(headerVarMatcher.FindStringSubmatch(tpl)[1]))
} }
return return compiled
} }
func (s *Server) Receive(c *gin.Context) { func (s *Server) Receive(c *gin.Context) {
+1 -1
View File
@@ -42,7 +42,7 @@ func NewRecord(rule *Rule, flag, method, url, ip, area, raw string) (r *Record,
Rule: *rule, Rule: *rule,
} }
err = database.DB.Create(r).Error err = database.DB.Create(r).Error
return return r, err
} }
func ListRecords(c *gin.Context) { func ListRecords(c *gin.Context) {
+3 -4
View File
@@ -23,7 +23,7 @@ func (Rule) TableName() string {
} }
// New http rule struct // New http rule struct
func NewRule(name, flagFormat, responseBody string, pushToClient, notice bool, responseStatus string, responseHeaders database.MapField, ) *Rule { func NewRule(name, flagFormat, responseBody string, pushToClient, notice bool, responseStatus string, responseHeaders database.MapField) *Rule {
return &Rule{ return &Rule{
BaseRule: rule.BaseRule{ BaseRule: rule.BaseRule{
Name: name, Name: name,
@@ -59,7 +59,7 @@ func (r *Rule) CreateOrUpdate() (err error) {
} }
err = GetServer().updateRules() err = GetServer().updateRules()
return return err
} }
// Delete the http rule in database and ruleSet // Delete the http rule in database and ruleSet
@@ -71,7 +71,7 @@ func (r *Rule) Delete() (err error) {
} }
err = GetServer().updateRules() err = GetServer().updateRules()
return return err
} }
// List all http rules those satisfy the filter // List all http rules those satisfy the filter
@@ -195,5 +195,4 @@ func DeleteRules(c *gin.Context) {
"error": nil, "error": nil,
"data": nil, "data": nil,
}) })
return
} }
+1 -1
View File
@@ -14,7 +14,7 @@ func ping(c *gin.Context) {
} }
func events(c *gin.Context) { func events(c *gin.Context) {
log.Info("Receive connection from ", c.Request.RemoteAddr) log.Info("Receive connection from %v", c.Request.RemoteAddr)
c.Stream(func(w io.Writer) bool { c.Stream(func(w io.Writer) bool {
c.SSEvent("message", "connect succeed") c.SSEvent("message", "connect succeed")
select { select {
+18
View File
@@ -24,11 +24,29 @@ func initDatabase(dsn string) {
} }
err = database.DB.AutoMigrate(&http.Record{}) err = database.DB.AutoMigrate(&http.Record{})
if err != nil {
log.Fatal(err.Error())
}
err = database.DB.AutoMigrate(&dns.Record{}) err = database.DB.AutoMigrate(&dns.Record{})
if err != nil {
log.Fatal(err.Error())
}
err = database.DB.AutoMigrate(&mysql.Record{}) err = database.DB.AutoMigrate(&mysql.Record{})
if err != nil {
log.Fatal(err.Error())
}
err = database.DB.AutoMigrate(&http.Rule{}) err = database.DB.AutoMigrate(&http.Rule{})
if err != nil {
log.Fatal(err.Error())
}
err = database.DB.AutoMigrate(&dns.Rule{}) err = database.DB.AutoMigrate(&dns.Rule{})
if err != nil {
log.Fatal(err.Error())
}
err = database.DB.AutoMigrate(&mysql.Rule{}) err = database.DB.AutoMigrate(&mysql.Rule{})
if err != nil {
log.Fatal(err.Error())
}
err = database.DB.AutoMigrate(&mysql.File{}) err = database.DB.AutoMigrate(&mysql.File{})
if err != nil { if err != nil {
log.Fatal(err.Error()) log.Fatal(err.Error())