Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

More issues caught by linter #79

Open
wants to merge 17 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions appservice/appservice.go
Original file line number Diff line number Diff line change
Expand Up @@ -191,11 +191,12 @@ func (as *AppService) makeIntent(userID id.UserID) *IntentAPI {

localpart, homeserver, err := userID.Parse()
if err != nil || len(localpart) == 0 || homeserver != as.HomeserverDomain {
if err != nil {
switch {
case err != nil:
as.Log.Fatalfln("Failed to parse user ID %s: %v", userID, err)
} else if len(localpart) == 0 {
case len(localpart) == 0:
as.Log.Fatalfln("Failed to make intent for %s: localpart is empty", userID)
} else if homeserver != as.HomeserverDomain {
case homeserver != as.HomeserverDomain:
as.Log.Fatalfln("Failed to make intent for %s: homeserver isn't %s", userID, as.HomeserverDomain)
}
return nil
Expand Down
9 changes: 5 additions & 4 deletions appservice/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -182,13 +182,14 @@ func (as *AppService) handleDeviceLists(dl *mautrix.DeviceLists) {

func (as *AppService) handleEvents(evts []*event.Event, defaultTypeClass event.TypeClass) {
for _, evt := range evts {
if len(evt.ToUserID) > 0 {
switch {
case len(evt.ToUserID) > 0:
evt.Type.Class = event.ToDeviceEventType
} else if defaultTypeClass != event.UnknownEventType {
case defaultTypeClass != event.UnknownEventType:
evt.Type.Class = defaultTypeClass
} else if evt.StateKey != nil {
case evt.StateKey != nil:
evt.Type.Class = event.StateEventType
} else {
default:
evt.Type.Class = event.MessageEventType
}
err := evt.Content.ParseRaw(evt.Type)
Expand Down
4 changes: 1 addition & 3 deletions appservice/sqlstatestore/statestore.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import (
"embed"
"encoding/json"
"errors"
"sync"

"maunium.net/go/mautrix/appservice"
"maunium.net/go/mautrix/event"
Expand All @@ -34,8 +33,7 @@ type SQLStateStore struct {
*dbutil.Database
*appservice.TypingStateStore

Typing map[id.RoomID]map[id.UserID]int64
typingLock sync.RWMutex
Typing map[id.RoomID]map[id.UserID]int64
}

var _ appservice.StateStore = (*SQLStateStore)(nil)
Expand Down
42 changes: 23 additions & 19 deletions appservice/websocket.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ func (wsc *WebsocketCommand) MakeResponse(ok bool, data interface{}) *WebsocketR
var prefixMessage string
for unwrappedErr != nil {
errorData, jsonErr = json.Marshal(unwrappedErr)
if errorData != nil && len(errorData) > 2 && jsonErr == nil {
if len(errorData) > 2 && jsonErr == nil {
prefixMessage = strings.Replace(err.Error(), unwrappedErr.Error(), "", 1)
prefixMessage = strings.TrimRight(prefixMessage, ": ")
break
Expand Down Expand Up @@ -216,24 +216,24 @@ func (as *AppService) RequestWebsocket(ctx context.Context, cmd *WebsocketReques
}
select {
case resp := <-respChan:
if resp.Command == "__websocket_closed" {
switch {
case resp.Command == "__websocket_closed":
return ErrWebsocketClosed
} else if resp.Command == "error" {
case resp.Command == "error":
var respErr ErrorResponse
err = json.Unmarshal(resp.Data, &respErr)
if err != nil {
return fmt.Errorf("failed to parse error JSON: %w", err)
}
return &respErr
} else if response != nil {
case response != nil:
err = json.Unmarshal(resp.Data, &response)
if err != nil {
return fmt.Errorf("failed to parse response JSON: %w", err)
}
return nil
} else {
return nil
}
return nil
case <-ctx.Done():
return ctx.Err()
}
Expand All @@ -260,7 +260,8 @@ func (as *AppService) consumeWebsocket(stopFunc func(error), ws *websocket.Conn)
stopFunc(parseCloseError(err))
return
}
if msg.Command == "" || msg.Command == "transaction" {
switch {
case msg.Command == "", msg.Command == "transaction":
if msg.TxnID == "" || !as.txnIDC.IsProcessed(msg.TxnID) {
as.handleTransaction(msg.TxnID, &msg.Transaction)
} else {
Expand All @@ -272,9 +273,9 @@ func (as *AppService) consumeWebsocket(stopFunc func(error), ws *websocket.Conn)
as.Log.Warnfln("Failed to send response to %s %d: %v", msg.Command, msg.ReqID, err)
}
}()
} else if msg.Command == "connect" {
case msg.Command == "connect":
as.Log.Debugln("Websocket connect confirmation received")
} else if msg.Command == "response" || msg.Command == "error" {
case msg.Command == "response", msg.Command == "error":
as.websocketRequestsLock.RLock()
respChan, ok := as.websocketRequests[msg.ReqID]
if ok {
Expand All @@ -287,7 +288,7 @@ func (as *AppService) consumeWebsocket(stopFunc func(error), ws *websocket.Conn)
as.Log.Warnfln("Dropping response to %d: unknown request ID", msg.ReqID)
}
as.websocketRequestsLock.RUnlock()
} else {
default:
as.websocketHandlersLock.RLock()
handler, ok := as.websocketHandlers[msg.Command]
as.websocketHandlersLock.RUnlock()
Expand All @@ -297,11 +298,12 @@ func (as *AppService) consumeWebsocket(stopFunc func(error), ws *websocket.Conn)
go func() {
okResp, data := handler(msg.WebsocketCommand)
err = as.SendWebsocket(msg.MakeResponse(okResp, data))
if err != nil {
switch {
case err != nil:
as.Log.Warnfln("Failed to send response to %s %d: %v", msg.Command, msg.ReqID, err)
} else if okResp {
case okResp:
as.Log.Debugfln("Sent success response to %s %d", msg.Command, msg.ReqID)
} else {
default:
as.Log.Debugfln("Sent error response to %s %d", msg.Command, msg.ReqID)
}
}()
Expand All @@ -327,12 +329,14 @@ func (as *AppService) StartWebsocket(baseURL string, onConnect func()) error {
"X-Mautrix-Process-ID": []string{as.ProcessID},
"X-Mautrix-Websocket-Version": []string{"3"},
})
if resp != nil && resp.StatusCode >= 400 {
var errResp Error
err = json.NewDecoder(resp.Body).Decode(&errResp)
if err != nil {
return fmt.Errorf("websocket request returned HTTP %d with non-JSON body", resp.StatusCode)
} else {
if resp != nil {
defer resp.Body.Close()
if resp.StatusCode >= 400 {
var errResp Error
err = json.NewDecoder(resp.Body).Decode(&errResp)
if err != nil {
return fmt.Errorf("websocket request returned HTTP %d with non-JSON body", resp.StatusCode)
}
return fmt.Errorf("websocket request returned %s (HTTP %d): %s", errResp.ErrorCode, resp.StatusCode, errResp.Message)
}
} else if err != nil {
Expand Down
8 changes: 4 additions & 4 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -588,7 +588,7 @@ func (cli *Client) FullSyncRequest(req ReqSync) (resp *RespSync, err error) {
}
start := time.Now()
_, err = cli.MakeFullRequest(fullReq)
duration := time.Now().Sub(start)
duration := time.Since(start)
timeout := time.Duration(req.Timeout) * time.Millisecond
buffer := 10 * time.Second
if req.Since == "" {
Expand Down Expand Up @@ -657,7 +657,7 @@ func (cli *Client) RegisterGuest(req *ReqRegister) (*RespRegister, *RespUserInte
// }
// token := res.AccessToken
func (cli *Client) RegisterDummy(req *ReqRegister) (*RespRegister, error) {
res, uia, err := cli.Register(req)
_, uia, err := cli.Register(req)
if err != nil && uia == nil {
return nil, err
} else if uia == nil {
Expand All @@ -666,7 +666,7 @@ func (cli *Client) RegisterDummy(req *ReqRegister) (*RespRegister, error) {
return nil, errors.New("server does not support m.login.dummy")
}
req.Auth = BaseAuthData{Type: AuthTypeDummy, Session: uia.Session}
res, _, err = cli.Register(req)
res, _, err := cli.Register(req)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -1094,7 +1094,7 @@ func parseRoomStateArray(_ *http.Request, res *http.Response, responseJSON inter
var evt *event.Event
err = dec.Decode(&evt)
if err != nil {
return nil, fmt.Errorf("failed to parse state array item #%d: %v", i, err)
return nil, fmt.Errorf("failed to parse state array item #%d: %w", i, err)
}
_ = evt.Content.ParseRaw(evt.Type)
subMap, ok := response[evt.Type]
Expand Down
7 changes: 4 additions & 3 deletions crypto/canonicaljson/json.go
Original file line number Diff line number Diff line change
Expand Up @@ -164,14 +164,15 @@ func CompactJSON(input, output []byte) []byte {
if c == '\\' {
escape := input[i]
i++
if escape == 'u' {
switch escape {
case 'u':
// If this is a unicode escape then we need to handle it specially
output, i = compactUnicodeEscape(input, output, i)
} else if escape == '/' {
case '/':
// JSON does not require escaping '/', but allows encoders to escape it as a special case.
// Since the escape isn't required we remove it.
output = append(output, escape)
} else {
default:
// All other permitted escapes are single charater escapes that are already in their shortest form.
output = append(output, '\\', escape)
}
Expand Down
4 changes: 2 additions & 2 deletions crypto/utils/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ func GenA256CTRIV() (iv [AESCTRIVLength]byte) {
func DeriveKeysSHA256(key []byte, name string) ([AESCTRKeyLength]byte, [HMACKeyLength]byte) {
var zeroBytes [32]byte

derivedHkdf := hkdf.New(sha256.New, key[:], zeroBytes[:], []byte(name))
derivedHkdf := hkdf.New(sha256.New, key, zeroBytes[:], []byte(name))

var aesKey [AESCTRKeyLength]byte
var hmacKey [HMACKeyLength]byte
Expand Down Expand Up @@ -104,7 +104,7 @@ func DecodeBase58RecoveryKey(recoveryKey string) []byte {
// EncodeBase58RecoveryKey recovers the secret storage from a recovery key.
func EncodeBase58RecoveryKey(key []byte) string {
var inputBytes [35]byte
copy(inputBytes[2:34], key[:])
copy(inputBytes[2:34], key)
inputBytes[0] = 0x8B
inputBytes[1] = 1

Expand Down
6 changes: 3 additions & 3 deletions crypto/utils/utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ func TestPBKDF(t *testing.T) {
}
key := PBKDF2SHA512([]byte("Hello world"), salt, 1000, 256)
expected := "ffk9YdbVE1cgqOWgDaec0lH+rJzO+MuCcxpIn3Z6D0E="
keyB64 := base64.StdEncoding.EncodeToString([]byte(key))
keyB64 := base64.StdEncoding.EncodeToString(key)
if keyB64 != expected {
t.Errorf("Expected base64 of generated key to be `%v`, got `%v`", expected, keyB64)
}
Expand All @@ -52,7 +52,7 @@ func TestDecodeSSSSKey(t *testing.T) {
decoded := DecodeBase58RecoveryKey(recoveryKey)

expected := "QCFDrXZYLEFnwf4NikVm62rYGJS2mNBEmAWLC3CgNPw="
decodedB64 := base64.StdEncoding.EncodeToString(decoded[:])
decodedB64 := base64.StdEncoding.EncodeToString(decoded)
if expected != decodedB64 {
t.Errorf("Expected decoded recovery key b64 to be `%v`, got `%v`", expected, decodedB64)
}
Expand All @@ -66,7 +66,7 @@ func TestKeyDerivationAndHMAC(t *testing.T) {
recoveryKey := "EsUG Ddi6 e1Cm F4um g38u JN72 d37v Q2ry qCf2 rKgL E2MQ ZQz6"
decoded := DecodeBase58RecoveryKey(recoveryKey)

aesKey, hmacKey := DeriveKeysSHA256(decoded[:], "m.cross_signing.master")
aesKey, hmacKey := DeriveKeysSHA256(decoded, "m.cross_signing.master")

ciphertextBytes, err := base64.StdEncoding.DecodeString("Fx16KlJ9vkd3Dd6CafIq5spaH5QmK5BALMzbtFbQznG2j1VARKK+klc4/Qo=")
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion event/message.go
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ func (sfi *serializableFileInfo) CopyFrom(fileInfo *FileInfo) *serializableFileI

}
if fileInfo.Duration > 0 {
sfi.Duration = json.Number(strconv.Itoa(int(fileInfo.Duration)))
sfi.Duration = json.Number(strconv.Itoa(fileInfo.Duration))
}
return sfi
}
Expand Down
13 changes: 7 additions & 6 deletions format/htmlparser.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ func (parser *HTMLParser) listToString(node *html.Node, stripLinebreak bool, ctx
indentLength = Digits(longestIndex)
}
indent := strings.Repeat(" ", indentLength+2)
var children []string
children := make([]string, 0, len(taggedChildren))
for _, child := range taggedChildren {
if child.tag != "li" {
continue
Expand Down Expand Up @@ -164,11 +164,12 @@ func (parser *HTMLParser) spanToString(node *html.Node, stripLinebreak bool, ctx
if node.Data == "span" {
reason, isSpoiler := parser.maybeGetAttribute(node, "data-mx-spoiler")
if isSpoiler {
if parser.SpoilerConverter != nil {
switch {
case parser.SpoilerConverter != nil:
str = parser.SpoilerConverter(str, reason, ctx)
} else if len(reason) > 0 {
case len(reason) > 0:
str = fmt.Sprintf("||%s|%s||", reason, str)
} else {
default:
str = fmt.Sprintf("||%s||", str)
}
}
Expand Down Expand Up @@ -270,7 +271,7 @@ func (parser *HTMLParser) singleNodeToString(node *html.Node, stripLinebreak boo
switch node.Type {
case html.TextNode:
if stripLinebreak {
node.Data = strings.Replace(node.Data, "\n", "", -1)
node.Data = strings.ReplaceAll(node.Data, "\n", "")
}
if parser.TextConverter != nil {
node.Data = parser.TextConverter(node.Data, ctx)
Expand Down Expand Up @@ -330,7 +331,7 @@ func (parser *HTMLParser) nodeToString(node *html.Node, stripLinebreak bool, ctx
// Parse converts Matrix HTML into text using the settings in this parser.
func (parser *HTMLParser) Parse(htmlData string, ctx Context) string {
if parser.TabsToSpaces >= 0 {
htmlData = strings.Replace(htmlData, "\t", strings.Repeat(" ", parser.TabsToSpaces), -1)
htmlData = strings.ReplaceAll(htmlData, "\t", strings.Repeat(" ", parser.TabsToSpaces))
}
node, _ := html.Parse(strings.NewReader(htmlData))
return parser.nodeToTagAwareString(node, true, ctx)
Expand Down
17 changes: 8 additions & 9 deletions format/markdown.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,20 +67,19 @@ func HTMLToContent(html string) event.MessageEventContent {

func RenderMarkdown(text string, allowMarkdown, allowHTML bool) event.MessageEventContent {
var htmlBody string

if allowMarkdown {
switch {
case allowMarkdown:
rndr := withHTML
if !allowHTML {
rndr = noHTML
}
return RenderMarkdownCustom(text, rndr)
} else if allowHTML {
htmlBody = strings.Replace(text, "\n", "<br>", -1)
case allowHTML:
htmlBody = strings.ReplaceAll(text, "\n", "<br>")
return HTMLToContent(htmlBody)
} else {
return event.MessageEventContent{
MsgType: event.MsgText,
Body: text,
}
}
return event.MessageEventContent{
MsgType: event.MsgText,
Body: text,
}
}
8 changes: 3 additions & 5 deletions format/mdext/nohtml.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,9 @@ func (ehr *escapingHTMLRenderer) renderHTMLBlock(w util.BufWriter, source []byte
line := n.Lines().At(i)
html.DefaultWriter.RawWrite(w, line.Value(source))
}
} else {
if n.HasClosure() {
closure := n.ClosureLine
html.DefaultWriter.RawWrite(w, closure.Value(source))
}
} else if n.HasClosure() {
closure := n.ClosureLine
html.DefaultWriter.RawWrite(w, closure.Value(source))
}
return ast.WalkContinue, nil
}
3 changes: 1 addition & 2 deletions id/matrixuri.go
Original file line number Diff line number Diff line change
Expand Up @@ -150,9 +150,8 @@ func ParseMatrixURIOrMatrixToURL(uri string) (*MatrixURI, error) {
return ProcessMatrixURI(parsed)
} else if strings.HasSuffix(parsed.Hostname(), "matrix.to") {
return ProcessMatrixToURL(parsed)
} else {
return nil, ErrNotMatrixToOrMatrixURI
}
return nil, ErrNotMatrixToOrMatrixURI
}

// ParseMatrixURI implements the matrix: URI parsing algorithm.
Expand Down
7 changes: 4 additions & 3 deletions id/userid.go
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,8 @@ func DecodeUserLocalpart(str string) (string, error) {
return "", fmt.Errorf("Byte pos %d: Invalid byte", i)
}

if b == '_' { // next byte is a-z and should be upper-case or is another _ and should be a literal _
switch b {
case '_': // next byte is a-z and should be upper-case or is another _ and should be a literal _
if i+1 >= len(strBytes) {
return "", fmt.Errorf("Byte pos %d: expected _[a-z_] encoding but ran out of string", i)
}
Expand All @@ -202,7 +203,7 @@ func DecodeUserLocalpart(str string) (string, error) {
outputBuffer.WriteByte(strBytes[i+1] - 0x20) // ASCII shift a-z to A-Z
}
i++ // skip next byte since we just handled it
} else if b == '=' { // next 2 bytes are hex and should be buffered ready to be read as utf8
case '=': // next 2 bytes are hex and should be buffered ready to be read as utf8
if i+2 >= len(strBytes) {
return "", fmt.Errorf("Byte pos: %d: expected quote-printable encoding but ran out of string", i)
}
Expand All @@ -213,7 +214,7 @@ func DecodeUserLocalpart(str string) (string, error) {
}
outputBuffer.WriteByte(dst[0])
i += 2 // skip next 2 bytes since we just handled it
} else { // pass through
default: // pass through
outputBuffer.WriteByte(b)
}
}
Expand Down
Loading