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
on:
push:
branches: [ master ]
branches: [ master,dev ]
paths:
- '**.go'
- 'go.mod'
@@ -21,10 +21,6 @@ jobs:
steps:
- name: Checkout code
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
uses: golangci/[email protected]
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":
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)
}
type ListField []string
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 {
// check if request
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
}
// check opcode
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
}
+1 -1
View File
@@ -272,7 +272,7 @@ func (s *Server) ServeDNS(w dns.ResponseWriter, req *dns.Msg) {
// Close will close the server.
func (s *Server) Close() {
defer func() { recover() }()
defer func() { recover() }() // nolint:errcheck
close(s.close)
}
+2 -2
View File
@@ -27,6 +27,6 @@ func formatRecordField(r record.Record,fieldFormat string) (content string) {
}
content += fmt.Sprintf(fieldFormat+"\n", strings.ToUpper(fieldName), value)
}
strings.TrimSuffix(content, "\n")
return
content = strings.TrimSuffix(content, "\n")
return content
}
+2 -2
View File
@@ -35,7 +35,7 @@ func get(url string) (b []byte, err error) {
defer resp.Body.Close()
b, err = ioutil.ReadAll(resp.Body)
return
return b, err
}
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")
}
key = binary.LittleEndian.Uint32(b[20:])
return
return key, err
}
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())
}
}
} 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...")
err := download()
if err != nil {
+1 -1
View File
@@ -61,5 +61,5 @@ func (br BaseRule) Match(s string) (flag, flagGroup string) {
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,
}
err = database.DB.Create(r).Error
return
return r, err
}
func List(c *gin.Context) {
+2 -3
View File
@@ -59,7 +59,7 @@ func (r *Rule) CreateOrUpdate() (err error) {
return
}
err = GetServer().updateRules()
return
return err
}
// Delete the dns rule in database and ruleSet
@@ -70,7 +70,7 @@ func (r *Rule) Delete() (err error) {
return
}
err = GetServer().updateRules()
return
return err
}
// List all dns rules those satisfy the filter
@@ -194,5 +194,4 @@ func DeleteRules(c *gin.Context) {
"error": 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 {
log.Trace("MySQL now try to read file [%s], ID [%d]", filename, c.ConnectionID)
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)
c.Files[filename] = []byte{}
} else {
+2 -1
View File
@@ -13,5 +13,6 @@ func TestServer_NewConnection(t *testing.T) {
if err != nil {
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 {
record.BaseRecord
Username string `gorm:"index",form:"username" json:"username" notice:"username"`
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"`
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"`
Username string `gorm:"index" form:"username" json:"username" notice:"username"`
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"`
LoadLocalData bool `gorm:"index" form:"load_local_data" json:"load_local_data" notice:"load_local_data"`
Files []File `form:"-" json:"files" 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,
}
err = database.DB.Create(r).Error
return
return r, err
}
func List(c *gin.Context) {
+3 -4
View File
@@ -14,7 +14,7 @@ type Rule struct {
rule.BaseRule
Files string `form:"files" json:"files"`
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 {
@@ -42,7 +42,7 @@ func (r *Rule) CreateOrUpdate() (err error) {
return
}
err = GetServer().updateRules()
return
return err
}
// Delete the mysql rule in database and ruleSet
@@ -53,7 +53,7 @@ func (r *Rule) Delete() (err error) {
return
}
err = GetServer().updateRules()
return
return err
}
// List all mysql rules those satisfy the filter
@@ -176,5 +176,4 @@ func DeleteRules(c *gin.Context) {
"error": nil,
"data": nil,
})
return
}
+7 -7
View File
@@ -117,18 +117,18 @@ func ScramblePassword(salt, password []byte) []byte {
// stage1Hash = SHA1(password)
crypt := sha1.New()
crypt.Write(password)
_, _ = crypt.Write(password)
stage1 := crypt.Sum(nil)
// scrambleHash = SHA1(salt + SHA1(stage1Hash))
// inner Hash
crypt.Reset()
crypt.Write(stage1)
_, _ = crypt.Write(stage1)
hash := crypt.Sum(nil)
// outer Hash
crypt.Reset()
crypt.Write(salt)
crypt.Write(hash)
_, _ = crypt.Write(salt)
_, _ = crypt.Write(hash)
scramble := crypt.Sum(nil)
// token = scrambleHash XOR stage1Hash
@@ -164,8 +164,8 @@ func isPassScrambleMysqlNativePassword(reply, salt []byte, mysqlNativePassword s
// scramble = SHA1(salt+hash)
crypt := sha1.New()
crypt.Write(salt)
crypt.Write(hash)
_, _ = crypt.Write(salt)
_, _ = crypt.Write(hash)
scramble := crypt.Sum(nil)
// token = scramble XOR stage1Hash
@@ -175,7 +175,7 @@ func isPassScrambleMysqlNativePassword(reply, salt []byte, mysqlNativePassword s
hashStage1 := scramble
crypt.Reset()
crypt.Write(hashStage1)
_, _ = crypt.Write(hashStage1)
candidateHash2 := crypt.Sum(nil)
return bytes.Equal(candidateHash2, hash)
-7
View File
@@ -18,19 +18,12 @@ package vmysql
import (
"bytes"
"flag"
"net"
"sync"
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 (
localhostName = "localhost"
)
+2 -49
View File
@@ -137,13 +137,6 @@ type Conn struct {
bufferedWriter *bufio.Writer
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
// ephemeral packet on the read and write sides.
// 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")
}
sequence := uint8(header[3])
sequence := header[3]
if sequence != c.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
}
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.
// It re-assembles packets that span more than one message.
// This method returns a generic error, not a SQLError.
@@ -606,22 +575,6 @@ func (c *Conn) recycleWritePacket() {
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().
func (c *Conn) RemoteAddr() net.Addr {
return c.conn.RemoteAddr()
@@ -937,7 +890,7 @@ func (c *Conn) RequestFile(filename string) []byte {
}
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 = 0x0e
// ComSetOption is COM_SET_OPTION
ComSetOption = 0x1b
// OKPacket is the header of the OK packet.
OKPacket = 0x00
@@ -179,7 +177,6 @@ const (
// CRUnknownError is CR_UNKNOWN_ERROR
CRUnknownError = 2000
// CRServerGone is CR_SERVER_GONE_ERROR.
// This is returned if the client tries to send a command but it fails.
CRServerGone = 2006
@@ -194,7 +191,6 @@ const (
// - the client cannot read a response from the server.
CRServerLost = 2013
// CRMalformedPacket is CR_MALFORMED_PACKET
CRMalformedPacket = 2027
)
@@ -215,7 +211,6 @@ const (
// unknown
ERUnknownError = 1105
// unavailable
ERServerShutdown = 1053
@@ -245,11 +240,8 @@ const (
// SSServerShutdown is ER_SERVER_SHUTDOWN
SSServerShutdown = "08S01"
// SSAccessDeniedError is ER_ACCESS_DENIED_ERROR
SSAccessDeniedError = "28000"
)
// 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
}
// 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.
// Returns a SQLError.
func (c *Conn) readColumnDefinition(field *querypb.Field, index int) error {
+7 -11
View File
@@ -37,7 +37,6 @@ const (
// timing metric keys
connectTimingKey = "Connect"
queryTimingKey = "Query"
versionSSL30 = "SSL30"
versionTLS10 = "TLS10"
versionTLS11 = "TLS11"
versionTLS12 = "TLS12"
@@ -322,7 +321,7 @@ func (l *Listener) handle(conn net.Conn, connectionID uint32, acceptTime time.Ti
}
} else {
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)
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.
authServerMethod, err := l.authServer.AuthMethod(user)
if err != nil {
c.writeErrorPacketFromError(err)
_ = c.writeErrorPacketFromError(err)
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())
if err != nil {
log.Trace("Error authenticating user using MySQL native password: %v", err)
c.writeErrorPacketFromError(err)
_ = c.writeErrorPacketFromError(err)
return
}
c.User = user
@@ -358,8 +357,7 @@ func (l *Listener) handle(conn net.Conn, connectionID uint32, acceptTime time.Ti
if err != nil {
return
}
//lint:ignore SA4006 This line is required because the binary protocol requires padding with 0
data := make([]byte, 21)
data := make([]byte, 21) //nolint:ineffassign,staticcheck // SA4006 This line is required because the binary protocol requires padding with 0
data = append(salt, byte(0x00))
if err := c.writeAuthSwitchRequest(MysqlNativePassword, data); err != nil {
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())
if err != nil {
log.Trace("Error authenticating user using MySQL native password: %v", err)
c.writeErrorPacketFromError(err)
_ = c.writeErrorPacketFromError(err)
return
}
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.
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
}
@@ -406,7 +404,7 @@ func (l *Listener) handle(conn net.Conn, connectionID uint32, acceptTime time.Ti
// auth server.
userData, err := l.authServer.Negotiate(c, user, conn.RemoteAddr())
if err != nil {
c.writeErrorPacketFromError(err)
_ = c.writeErrorPacketFromError(err)
return
}
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
func tlsVersionToString(version uint16) string {
switch version {
case tls.VersionSSL30:
return versionSSL30
case tls.VersionTLS10:
return versionTLS10
case tls.VersionTLS11:
+1 -1
View File
@@ -119,7 +119,7 @@ func compileTpl(c *gin.Context, tpl string) (compiled string) {
if headerVarMatcher.FindString(tpl) != "" {
compiled = headerVarMatcher.ReplaceAllString(compiled, c.GetHeader(headerVarMatcher.FindStringSubmatch(tpl)[1]))
}
return
return compiled
}
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,
}
err = database.DB.Create(r).Error
return
return r, err
}
func ListRecords(c *gin.Context) {
+3 -4
View File
@@ -23,7 +23,7 @@ func (Rule) TableName() string {
}
// 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{
BaseRule: rule.BaseRule{
Name: name,
@@ -59,7 +59,7 @@ func (r *Rule) CreateOrUpdate() (err error) {
}
err = GetServer().updateRules()
return
return err
}
// Delete the http rule in database and ruleSet
@@ -71,7 +71,7 @@ func (r *Rule) Delete() (err error) {
}
err = GetServer().updateRules()
return
return err
}
// List all http rules those satisfy the filter
@@ -195,5 +195,4 @@ func DeleteRules(c *gin.Context) {
"error": nil,
"data": nil,
})
return
}
+1 -1
View File
@@ -14,7 +14,7 @@ func ping(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.SSEvent("message", "connect succeed")
select {
+18
View File
@@ -24,11 +24,29 @@ func initDatabase(dsn string) {
}
err = database.DB.AutoMigrate(&http.Record{})
if err != nil {
log.Fatal(err.Error())
}
err = database.DB.AutoMigrate(&dns.Record{})
if err != nil {
log.Fatal(err.Error())
}
err = database.DB.AutoMigrate(&mysql.Record{})
if err != nil {
log.Fatal(err.Error())
}
err = database.DB.AutoMigrate(&http.Rule{})
if err != nil {
log.Fatal(err.Error())
}
err = database.DB.AutoMigrate(&dns.Rule{})
if err != nil {
log.Fatal(err.Error())
}
err = database.DB.AutoMigrate(&mysql.Rule{})
if err != nil {
log.Fatal(err.Error())
}
err = database.DB.AutoMigrate(&mysql.File{})
if err != nil {
log.Fatal(err.Error())