Add errcheck linter (#238)

* Add errcheck linter

* Add config for 'fast' linters

* Fix errcheck lint stuff

* Fix errcheck lint
main
Erik Johnston 2017-09-20 10:59:19 +01:00 committed by Mark Haines
parent b91b3e729a
commit 8a36a7e89b
40 changed files with 186 additions and 98 deletions

15
linter-fast.json Normal file
View File

@ -0,0 +1,15 @@
{
"Vendor": true,
"Cyclo": 12,
"Deadline": "5m",
"Enable": [
"vetshadow",
"gotype",
"deadcode",
"gocyclo",
"ineffassign",
"gas",
"misspell",
"errcheck"
]
}

View File

@ -14,6 +14,7 @@
"ineffassign", "ineffassign",
"gas", "gas",
"misspell", "misspell",
"unparam" "unparam",
"errcheck"
] ]
} }

View File

@ -108,7 +108,7 @@ func (s *membershipStatements) selectMembershipsByLocalpart(
memberships = []authtypes.Membership{} memberships = []authtypes.Membership{}
defer rows.Close() defer rows.Close() // nolint: errcheck
for rows.Next() { for rows.Next() {
var m authtypes.Membership var m authtypes.Membership
m.Localpart = localpart m.Localpart = localpart

View File

@ -69,7 +69,10 @@ func BuildEvent(
authEvents := gomatrixserverlib.NewAuthEvents(nil) authEvents := gomatrixserverlib.NewAuthEvents(nil)
for i := range queryRes.StateEvents { for i := range queryRes.StateEvents {
authEvents.AddEvent(&queryRes.StateEvents[i]) err = authEvents.AddEvent(&queryRes.StateEvents[i])
if err != nil {
return nil, err
}
} }
refs, err := eventsNeeded.AuthEventReferences(&authEvents) refs, err := eventsNeeded.AuthEventReferences(&authEvents)

View File

@ -25,7 +25,7 @@ import (
// UnmarshalJSONRequest into the given interface pointer. Returns an error JSON response if // UnmarshalJSONRequest into the given interface pointer. Returns an error JSON response if
// there was a problem unmarshalling. Calling this function consumes the request body. // there was a problem unmarshalling. Calling this function consumes the request body.
func UnmarshalJSONRequest(req *http.Request, iface interface{}) *util.JSONResponse { func UnmarshalJSONRequest(req *http.Request, iface interface{}) *util.JSONResponse {
defer req.Body.Close() defer req.Body.Close() // nolint: errcheck
if err := json.NewDecoder(req.Body).Decode(iface); err != nil { if err := json.NewDecoder(req.Body).Decode(iface); err != nil {
// TODO: We may want to suppress the Error() return in production? It's useful when // TODO: We may want to suppress the Error() return in production? It's useful when
// debugging because an error will be produced for both invalid/malformed JSON AND // debugging because an error will be produced for both invalid/malformed JSON AND

View File

@ -52,7 +52,7 @@ func SaveAccountData(
return httputil.LogThenError(req, err) return httputil.LogThenError(req, err)
} }
defer req.Body.Close() defer req.Body.Close() // nolint: errcheck
body, err := ioutil.ReadAll(req.Body) body, err := ioutil.ReadAll(req.Body)
if err != nil { if err != nil {

View File

@ -185,7 +185,10 @@ func createRoom(req *http.Request, device *authtypes.Device,
StateKey: &e.StateKey, StateKey: &e.StateKey,
Depth: int64(depth), Depth: int64(depth),
} }
builder.SetContent(e.Content) err = builder.SetContent(e.Content)
if err != nil {
return httputil.LogThenError(req, err)
}
if i > 0 { if i > 0 {
builder.PrevEvents = []gomatrixserverlib.EventReference{builtEvents[i-1].EventReference()} builder.PrevEvents = []gomatrixserverlib.EventReference{builtEvents[i-1].EventReference()}
} }
@ -194,13 +197,16 @@ func createRoom(req *http.Request, device *authtypes.Device,
return httputil.LogThenError(req, err) return httputil.LogThenError(req, err)
} }
if err := gomatrixserverlib.Allowed(*ev, &authEvents); err != nil { if err = gomatrixserverlib.Allowed(*ev, &authEvents); err != nil {
return httputil.LogThenError(req, err) return httputil.LogThenError(req, err)
} }
// Add the event to the list of auth events // Add the event to the list of auth events
builtEvents = append(builtEvents, *ev) builtEvents = append(builtEvents, *ev)
authEvents.AddEvent(ev) err = authEvents.AddEvent(ev)
if err != nil {
return httputil.LogThenError(req, err)
}
} }
// send events to the room server // send events to the room server

View File

@ -153,21 +153,35 @@ func (r joinRoomReq) joinRoomByRemoteAlias(
return r.joinRoomUsingServers(resp.RoomID, resp.Servers) return r.joinRoomUsingServers(resp.RoomID, resp.Servers)
} }
func (r joinRoomReq) writeToBuilder(eb *gomatrixserverlib.EventBuilder, roomID string) { func (r joinRoomReq) writeToBuilder(eb *gomatrixserverlib.EventBuilder, roomID string) error {
eb.Type = "m.room.member" eb.Type = "m.room.member"
eb.SetContent(r.content)
eb.SetUnsigned(struct{}{}) err := eb.SetContent(r.content)
if err != nil {
return err
}
err = eb.SetUnsigned(struct{}{})
if err != nil {
return err
}
eb.Sender = r.userID eb.Sender = r.userID
eb.StateKey = &r.userID eb.StateKey = &r.userID
eb.RoomID = roomID eb.RoomID = roomID
eb.Redacts = "" eb.Redacts = ""
return nil
} }
func (r joinRoomReq) joinRoomUsingServers( func (r joinRoomReq) joinRoomUsingServers(
roomID string, servers []gomatrixserverlib.ServerName, roomID string, servers []gomatrixserverlib.ServerName,
) util.JSONResponse { ) util.JSONResponse {
var eb gomatrixserverlib.EventBuilder var eb gomatrixserverlib.EventBuilder
r.writeToBuilder(&eb, roomID) err := r.writeToBuilder(&eb, roomID)
if err != nil {
return httputil.LogThenError(r.req, err)
}
var queryRes api.QueryLatestEventsAndStateResponse var queryRes api.QueryLatestEventsAndStateResponse
event, err := events.BuildEvent(r.req.Context(), &eb, r.cfg, r.queryAPI, &queryRes) event, err := events.BuildEvent(r.req.Context(), &eb, r.cfg, r.queryAPI, &queryRes)
@ -235,7 +249,10 @@ func (r joinRoomReq) joinRoomUsingServer(roomID string, server gomatrixserverlib
// Set all the fields to be what they should be, this should be a no-op // Set all the fields to be what they should be, this should be a no-op
// but it's possible that the remote server returned us something "odd" // but it's possible that the remote server returned us something "odd"
r.writeToBuilder(&respMakeJoin.JoinEvent, roomID) err = r.writeToBuilder(&respMakeJoin.JoinEvent, roomID)
if err != nil {
return nil, err
}
now := time.Now() now := time.Now()
eventID := fmt.Sprintf("$%s:%s", util.RandomString(16), r.cfg.Matrix.ServerName) eventID := fmt.Sprintf("$%s:%s", util.RandomString(16), r.cfg.Matrix.ServerName)

View File

@ -60,7 +60,10 @@ func SendEvent(
Type: eventType, Type: eventType,
StateKey: stateKey, StateKey: stateKey,
} }
builder.SetContent(r) err := builder.SetContent(r)
if err != nil {
return httputil.LogThenError(req, err)
}
var queryRes api.QueryLatestEventsAndStateResponse var queryRes api.QueryLatestEventsAndStateResponse
e, err := events.BuildEvent(req.Context(), &builder, cfg, queryAPI, &queryRes) e, err := events.BuildEvent(req.Context(), &builder, cfg, queryAPI, &queryRes)

View File

@ -80,20 +80,20 @@ func main() {
b.RoomID = *roomID b.RoomID = *roomID
b.Type = "m.room.create" b.Type = "m.room.create"
b.StateKey = &emptyString b.StateKey = &emptyString
b.SetContent(map[string]string{"creator": *userID}) b.SetContent(map[string]string{"creator": *userID}) // nolint: errcheck
create := buildAndOutput() create := buildAndOutput()
// Build a m.room.member event. // Build a m.room.member event.
b.Type = "m.room.member" b.Type = "m.room.member"
b.StateKey = userID b.StateKey = userID
b.SetContent(map[string]string{"membership": "join"}) b.SetContent(map[string]string{"membership": "join"}) // nolint: errcheck
b.AuthEvents = []gomatrixserverlib.EventReference{create} b.AuthEvents = []gomatrixserverlib.EventReference{create}
member := buildAndOutput() member := buildAndOutput()
// Build a number of m.room.message events. // Build a number of m.room.message events.
b.Type = "m.room.message" b.Type = "m.room.message"
b.StateKey = nil b.StateKey = nil
b.SetContent(map[string]string{"body": "Test Message"}) b.SetContent(map[string]string{"body": "Test Message"}) // nolint: errcheck
b.AuthEvents = []gomatrixserverlib.EventReference{create, member} b.AuthEvents = []gomatrixserverlib.EventReference{create, member}
for i := 0; i < *messageCount; i++ { for i := 0; i < *messageCount; i++ {
buildAndOutput() buildAndOutput()

View File

@ -125,7 +125,8 @@ func startMediaAPI(suffix string, dynamicThumbnails bool) (*exec.Cmd, chan error
} }
func cleanUpServer(cmd *exec.Cmd, dir string) { func cleanUpServer(cmd *exec.Cmd, dir string) {
cmd.Process.Kill() // ensure server is dead, only cleaning up so don't care about errors this returns. // ensure server is dead, only cleaning up so don't care about errors this returns
cmd.Process.Kill() // nolint: errcheck
if err := os.RemoveAll(dir); err != nil { if err := os.RemoveAll(dir); err != nil {
fmt.Printf("WARNING: Failed to remove temporary directory %v: %q\n", dir, err) fmt.Printf("WARNING: Failed to remove temporary directory %v: %q\n", dir, err)
} }
@ -146,7 +147,7 @@ func main() {
// create server1 with only pre-generated thumbnails allowed // create server1 with only pre-generated thumbnails allowed
server1Cmd, server1CmdChan, _, server1ProxyCmd, _, server1ProxyAddr, server1Dir := startMediaAPI("1", false) server1Cmd, server1CmdChan, _, server1ProxyCmd, _, server1ProxyAddr, server1Dir := startMediaAPI("1", false)
defer cleanUpServer(server1Cmd, server1Dir) defer cleanUpServer(server1Cmd, server1Dir)
defer server1ProxyCmd.Process.Kill() defer server1ProxyCmd.Process.Kill() // nolint: errcheck
testDownload(server1ProxyAddr, server1ProxyAddr, "doesnotexist", 404, server1CmdChan) testDownload(server1ProxyAddr, server1ProxyAddr, "doesnotexist", 404, server1CmdChan)
// upload a JPEG file // upload a JPEG file
@ -163,7 +164,7 @@ func main() {
// create server2 with dynamic thumbnail generation // create server2 with dynamic thumbnail generation
server2Cmd, server2CmdChan, _, server2ProxyCmd, _, server2ProxyAddr, server2Dir := startMediaAPI("2", true) server2Cmd, server2CmdChan, _, server2ProxyCmd, _, server2ProxyAddr, server2Dir := startMediaAPI("2", true)
defer cleanUpServer(server2Cmd, server2Dir) defer cleanUpServer(server2Cmd, server2Dir)
defer server2ProxyCmd.Process.Kill() defer server2ProxyCmd.Process.Kill() // nolint: errcheck
testDownload(server2ProxyAddr, server2ProxyAddr, "doesnotexist", 404, server2CmdChan) testDownload(server2ProxyAddr, server2ProxyAddr, "doesnotexist", 404, server2CmdChan)
// pre-generated thumbnail that JPEG file via server2 // pre-generated thumbnail that JPEG file via server2
@ -189,7 +190,7 @@ func getMediaURI(host, endpoint, query string, components []string) string {
func testUpload(host, filePath string) { func testUpload(host, filePath string) {
fmt.Printf("==TESTING== upload %v to %v\n", filePath, host) fmt.Printf("==TESTING== upload %v to %v\n", filePath, host)
file, err := os.Open(filePath) file, err := os.Open(filePath)
defer file.Close() defer file.Close() // nolint: errcheck
if err != nil { if err != nil {
panic(err) panic(err)
} }

View File

@ -114,8 +114,8 @@ func runAndReadFromTopic(runCmd *exec.Cmd, readyURL string, doInput func(), topi
readCmd.Stderr = os.Stderr readCmd.Stderr = os.Stderr
// Kill both processes before we exit. // Kill both processes before we exit.
defer func() { runCmd.Process.Kill() }() defer func() { runCmd.Process.Kill() }() // nolint: errcheck
defer func() { readCmd.Process.Kill() }() defer func() { readCmd.Process.Kill() }() // nolint: errcheck
// Run the command, read the messages and wait for a timeout in parallel. // Run the command, read the messages and wait for a timeout in parallel.
go func() { go func() {
@ -228,7 +228,11 @@ func testRoomserver(input []string, wantOutput []string, checkQueries func(api.R
outputTopic := string(cfg.Kafka.Topics.OutputRoomEvent) outputTopic := string(cfg.Kafka.Topics.OutputRoomEvent)
exe.DeleteTopic(outputTopic) err = exe.DeleteTopic(outputTopic)
if err != nil {
panic(err)
}
if err = exe.CreateTopic(outputTopic); err != nil { if err = exe.CreateTopic(outputTopic); err != nil {
panic(err) panic(err)
} }

View File

@ -175,12 +175,21 @@ func startSyncServer() (*exec.Cmd, chan error) {
// prepareKafka creates the topics which will be written to by the tests. // prepareKafka creates the topics which will be written to by the tests.
func prepareKafka() { func prepareKafka() {
exe.DeleteTopic(inputTopic) err := exe.DeleteTopic(inputTopic)
if err := exe.CreateTopic(inputTopic); err != nil { if err != nil {
panic(err) panic(err)
} }
exe.DeleteTopic(clientTopic)
if err := exe.CreateTopic(clientTopic); err != nil { if err = exe.CreateTopic(inputTopic); err != nil {
panic(err)
}
err = exe.DeleteTopic(clientTopic)
if err != nil {
panic(err)
}
if err = exe.CreateTopic(clientTopic); err != nil {
panic(err) panic(err)
} }
} }
@ -225,7 +234,8 @@ func main() {
fmt.Println("==TESTING==", os.Args[0]) fmt.Println("==TESTING==", os.Args[0])
prepareKafka() prepareKafka()
cmd, syncServerCmdChan := startSyncServer() cmd, syncServerCmdChan := startSyncServer()
defer cmd.Process.Kill() // ensure server is dead, only cleaning up so don't care about errors this returns. // ensure server is dead, only cleaning up so don't care about errors this returns.
defer cmd.Process.Kill() // nolint: errcheck
// $ curl -XPOST -d '{}' "http://localhost:8009/_matrix/client/r0/createRoom?access_token=@alice:localhost" // $ curl -XPOST -d '{}' "http://localhost:8009/_matrix/client/r0/createRoom?access_token=@alice:localhost"
// $ curl -XPUT -d '{"msgtype":"m.text","body":"hello world"}' "http://localhost:8009/_matrix/client/r0/rooms/%21PjrbIMW2cIiaYF4t:localhost/send/m.room.message/1?access_token=@alice:localhost" // $ curl -XPUT -d '{"msgtype":"m.text","body":"hello world"}' "http://localhost:8009/_matrix/client/r0/rooms/%21PjrbIMW2cIiaYF4t:localhost/send/m.room.message/1?access_token=@alice:localhost"

View File

@ -91,7 +91,7 @@ func (c *ContinualConsumer) Start() error {
pc, err := c.Consumer.ConsumePartition(c.Topic, partition, offset) pc, err := c.Consumer.ConsumePartition(c.Topic, partition, offset)
if err != nil { if err != nil {
for _, p := range partitionConsumers { for _, p := range partitionConsumers {
p.Close() p.Close() // nolint: errcheck
} }
return err return err
} }
@ -106,7 +106,7 @@ func (c *ContinualConsumer) Start() error {
// consumePartition consumes the room events for a single partition of the kafkaesque stream. // consumePartition consumes the room events for a single partition of the kafkaesque stream.
func (c *ContinualConsumer) consumePartition(pc sarama.PartitionConsumer) { func (c *ContinualConsumer) consumePartition(pc sarama.PartitionConsumer) {
defer pc.Close() defer pc.Close() // nolint: errcheck
for message := range pc.Messages() { for message := range pc.Messages() {
msgErr := c.ProcessMessage(message) msgErr := c.ProcessMessage(message)
// Advance our position in the stream so that we will start at the right position after a restart. // Advance our position in the stream so that we will start at the right position after a restart.

View File

@ -37,7 +37,10 @@ func NewDatabase(dataSourceName string) (*Database, error) {
return nil, err return nil, err
} }
d := &Database{} d := &Database{}
d.statements.prepare(db) err = d.statements.prepare(db)
if err != nil {
return nil, err
}
return d, nil return d, nil
} }

View File

@ -83,7 +83,7 @@ func (s *serverKeyStatements) bulkSelectServerKeys(
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer rows.Close() defer rows.Close() // nolint: errcheck
results := map[gomatrixserverlib.PublicKeyRequest]gomatrixserverlib.ServerKeys{} results := map[gomatrixserverlib.PublicKeyRequest]gomatrixserverlib.ServerKeys{}
for rows.Next() { for rows.Next() {
var serverName string var serverName string

View File

@ -71,7 +71,7 @@ func (s *PartitionOffsetStatements) SelectPartitionOffsets(topic string) ([]Part
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer rows.Close() defer rows.Close() // nolint: errcheck
var results []PartitionOffset var results []PartitionOffset
for rows.Next() { for rows.Next() {
var offset PartitionOffset var offset PartitionOffset

View File

@ -30,9 +30,9 @@ type Transaction interface {
// If the transaction succeeded then it is committed, otherwise it is rolledback. // If the transaction succeeded then it is committed, otherwise it is rolledback.
func EndTransaction(txn Transaction, succeeded *bool) { func EndTransaction(txn Transaction, succeeded *bool) {
if *succeeded { if *succeeded {
txn.Commit() txn.Commit() // nolint: errcheck
} else { } else {
txn.Rollback() txn.Rollback() // nolint: errcheck
} }
} }

View File

@ -69,7 +69,7 @@ func CanonicalJSONInput(jsonData []string) []string {
} }
// Do issues a request and checks the status code and body of the response // Do issues a request and checks the status code and body of the response
func (r *Request) Do() error { func (r *Request) Do() (err error) {
client := &http.Client{ client := &http.Client{
Timeout: 5 * time.Second, Timeout: 5 * time.Second,
Transport: &http.Transport{ Transport: &http.Transport{
@ -82,7 +82,7 @@ func (r *Request) Do() error {
if err != nil { if err != nil {
return err return err
} }
defer res.Body.Close() defer (func() { err = res.Body.Close() })()
if res.StatusCode != r.WantedStatusCode { if res.StatusCode != r.WantedStatusCode {
return fmt.Errorf("incorrect status code. Expected: %d Got: %d", r.WantedStatusCode, res.StatusCode) return fmt.Errorf("incorrect status code. Expected: %d Got: %d", r.WantedStatusCode, res.StatusCode)

View File

@ -120,16 +120,21 @@ func WriteConfig(cfg *config.Dendrite, configDir string) error {
} }
// NewMatrixKey generates a new ed25519 matrix server key and writes it to a file. // NewMatrixKey generates a new ed25519 matrix server key and writes it to a file.
func NewMatrixKey(matrixKeyPath string) error { func NewMatrixKey(matrixKeyPath string) (err error) {
var data [35]byte var data [35]byte
if _, err := rand.Read(data[:]); err != nil { _, err = rand.Read(data[:])
if err != nil {
return err return err
} }
keyOut, err := os.OpenFile(matrixKeyPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) keyOut, err := os.OpenFile(matrixKeyPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil { if err != nil {
return err return err
} }
defer keyOut.Close()
defer (func() {
err = keyOut.Close()
})()
if err = pem.Encode(keyOut, &pem.Block{ if err = pem.Encode(keyOut, &pem.Block{
Type: "MATRIX PRIVATE KEY", Type: "MATRIX PRIVATE KEY",
Headers: map[string]string{ Headers: map[string]string{
@ -176,7 +181,7 @@ func NewTLSKey(tlsKeyPath, tlsCertPath string) error {
if err != nil { if err != nil {
return err return err
} }
defer certOut.Close() defer certOut.Close() // nolint: errcheck
if err = pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}); err != nil { if err = pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}); err != nil {
return err return err
} }
@ -185,7 +190,7 @@ func NewTLSKey(tlsKeyPath, tlsCertPath string) error {
if err != nil { if err != nil {
return err return err
} }
defer keyOut.Close() defer keyOut.Close() // nolint: errcheck
if err = pem.Encode(keyOut, &pem.Block{ if err = pem.Encode(keyOut, &pem.Block{
Type: "RSA PRIVATE KEY", Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(priv), Bytes: x509.MarshalPKCS1PrivateKey(priv),

View File

@ -180,7 +180,10 @@ func (t *txnReq) processEvent(e gomatrixserverlib.Event) error {
func checkAllowedByState(e gomatrixserverlib.Event, stateEvents []gomatrixserverlib.Event) error { func checkAllowedByState(e gomatrixserverlib.Event, stateEvents []gomatrixserverlib.Event) error {
authUsingState := gomatrixserverlib.NewAuthEvents(nil) authUsingState := gomatrixserverlib.NewAuthEvents(nil)
for i := range stateEvents { for i := range stateEvents {
authUsingState.AddEvent(&stateEvents[i]) err := authUsingState.AddEvent(&stateEvents[i])
if err != nil {
return err
}
} }
return gomatrixserverlib.Allowed(e, &authUsingState) return gomatrixserverlib.Allowed(e, &authUsingState)
} }

View File

@ -257,7 +257,10 @@ func buildMembershipEvent(
authEvents := gomatrixserverlib.NewAuthEvents(nil) authEvents := gomatrixserverlib.NewAuthEvents(nil)
for i := range queryRes.StateEvents { for i := range queryRes.StateEvents {
authEvents.AddEvent(&queryRes.StateEvents[i]) err = authEvents.AddEvent(&queryRes.StateEvents[i])
if err != nil {
return nil, err
}
} }
if err = fillDisplayName(builder, authEvents); err != nil { if err = fillDisplayName(builder, authEvents); err != nil {

View File

@ -105,7 +105,7 @@ func (s *joinedHostsStatements) selectJoinedHosts(
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer rows.Close() defer rows.Close() // nolint: errcheck
var result []types.JoinedHost var result []types.JoinedHost
for rows.Next() { for rows.Next() {

View File

@ -105,12 +105,14 @@ func RemoveDir(dir types.Path, logger *log.Entry) {
} }
// WriteTempFile writes to a new temporary file // WriteTempFile writes to a new temporary file
func WriteTempFile(reqReader io.Reader, maxFileSizeBytes config.FileSizeBytes, absBasePath config.Path) (types.Base64Hash, types.FileSizeBytes, types.Path, error) { func WriteTempFile(reqReader io.Reader, maxFileSizeBytes config.FileSizeBytes, absBasePath config.Path) (hash types.Base64Hash, size types.FileSizeBytes, path types.Path, err error) {
size = -1
tmpFileWriter, tmpFile, tmpDir, err := createTempFileWriter(absBasePath) tmpFileWriter, tmpFile, tmpDir, err := createTempFileWriter(absBasePath)
if err != nil { if err != nil {
return "", -1, "", err return
} }
defer tmpFile.Close() defer (func() { err = tmpFile.Close() })()
// The amount of data read is limited to maxFileSizeBytes. At this point, if there is more data it will be truncated. // The amount of data read is limited to maxFileSizeBytes. At this point, if there is more data it will be truncated.
limitedReader := io.LimitReader(reqReader, int64(maxFileSizeBytes)) limitedReader := io.LimitReader(reqReader, int64(maxFileSizeBytes))
@ -121,13 +123,18 @@ func WriteTempFile(reqReader io.Reader, maxFileSizeBytes config.FileSizeBytes, a
teeReader := io.TeeReader(limitedReader, hasher) teeReader := io.TeeReader(limitedReader, hasher)
bytesWritten, err := io.Copy(tmpFileWriter, teeReader) bytesWritten, err := io.Copy(tmpFileWriter, teeReader)
if err != nil && err != io.EOF { if err != nil && err != io.EOF {
return "", -1, "", err return
} }
tmpFileWriter.Flush() err = tmpFileWriter.Flush()
if err != nil {
return
}
hash := hasher.Sum(nil) hash = types.Base64Hash(base64.RawURLEncoding.EncodeToString(hasher.Sum(nil)[:]))
return types.Base64Hash(base64.RawURLEncoding.EncodeToString(hash[:])), types.FileSizeBytes(bytesWritten), tmpDir, nil size = types.FileSizeBytes(bytesWritten)
path = tmpDir
return
} }
// moveFile attempts to move the file src to dst // moveFile attempts to move the file src to dst

View File

@ -83,7 +83,7 @@ func readFile(src string) (image.Image, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer file.Close() defer file.Close() // nolint: errcheck
img, _, err := image.Decode(file) img, _, err := image.Decode(file)
if err != nil { if err != nil {
@ -93,12 +93,12 @@ func readFile(src string) (image.Image, error) {
return img, nil return img, nil
} }
func writeFile(img image.Image, dst string) error { func writeFile(img image.Image, dst string) (err error) {
out, err := os.Create(dst) out, err := os.Create(dst)
if err != nil { if err != nil {
return err return err
} }
defer out.Close() defer (func() { err = out.Close() })()
return jpeg.Encode(out, img, &jpeg.Options{ return jpeg.Encode(out, img, &jpeg.Options{
Quality: 85, Quality: 85,

View File

@ -148,7 +148,9 @@ func (r *downloadRequest) jsonErrorResponse(w http.ResponseWriter, res util.JSON
// Set status code and write the body // Set status code and write the body
w.WriteHeader(res.Code) w.WriteHeader(res.Code)
r.Logger.WithField("code", res.Code).Infof("Responding (%d bytes)", len(resBytes)) r.Logger.WithField("code", res.Code).Infof("Responding (%d bytes)", len(resBytes))
w.Write(resBytes)
// we don't really care that much if we fail to write the error response
w.Write(resBytes) // nolint: errcheck
} }
// Validate validates the downloadRequest fields // Validate validates the downloadRequest fields
@ -234,7 +236,7 @@ func (r *downloadRequest) respondFromLocalFile(
return nil, errors.Wrap(err, "failed to get file path from metadata") return nil, errors.Wrap(err, "failed to get file path from metadata")
} }
file, err := os.Open(filePath) file, err := os.Open(filePath)
defer file.Close() defer file.Close() // nolint: errcheck
if err != nil { if err != nil {
return nil, errors.Wrap(err, "failed to open file") return nil, errors.Wrap(err, "failed to open file")
} }
@ -256,7 +258,7 @@ func (r *downloadRequest) respondFromLocalFile(
if r.IsThumbnailRequest { if r.IsThumbnailRequest {
thumbFile, thumbMetadata, resErr := r.getThumbnailFile(types.Path(filePath), activeThumbnailGeneration, maxThumbnailGenerators, db, dynamicThumbnails, thumbnailSizes) thumbFile, thumbMetadata, resErr := r.getThumbnailFile(types.Path(filePath), activeThumbnailGeneration, maxThumbnailGenerators, db, dynamicThumbnails, thumbnailSizes)
if thumbFile != nil { if thumbFile != nil {
defer thumbFile.Close() defer thumbFile.Close() // nolint: errcheck
} }
if resErr != nil { if resErr != nil {
return nil, resErr return nil, resErr
@ -360,16 +362,16 @@ func (r *downloadRequest) getThumbnailFile(
thumbPath := string(thumbnailer.GetThumbnailPath(types.Path(filePath), thumbnail.ThumbnailSize)) thumbPath := string(thumbnailer.GetThumbnailPath(types.Path(filePath), thumbnail.ThumbnailSize))
thumbFile, err := os.Open(string(thumbPath)) thumbFile, err := os.Open(string(thumbPath))
if err != nil { if err != nil {
thumbFile.Close() thumbFile.Close() // nolint: errcheck
return nil, nil, errors.Wrap(err, "failed to open file") return nil, nil, errors.Wrap(err, "failed to open file")
} }
thumbStat, err := thumbFile.Stat() thumbStat, err := thumbFile.Stat()
if err != nil { if err != nil {
thumbFile.Close() thumbFile.Close() // nolint: errcheck
return nil, nil, errors.Wrap(err, "failed to stat file") return nil, nil, errors.Wrap(err, "failed to stat file")
} }
if types.FileSizeBytes(thumbStat.Size()) != thumbnail.MediaMetadata.FileSizeBytes { if types.FileSizeBytes(thumbStat.Size()) != thumbnail.MediaMetadata.FileSizeBytes {
thumbFile.Close() thumbFile.Close() // nolint: errcheck
return nil, nil, errors.New("thumbnail file sizes on disk and in database differ") return nil, nil, errors.New("thumbnail file sizes on disk and in database differ")
} }
return thumbFile, thumbnail, nil return thumbFile, thumbnail, nil
@ -564,7 +566,7 @@ func (r *downloadRequest) fetchRemoteFile(absBasePath config.Path, maxFileSizeBy
// Remote file not found // Remote file not found
return "", false, nil return "", false, nil
} }
defer resp.Body.Close() defer resp.Body.Close() // nolint: errcheck
// get metadata from request and set metadata on response // get metadata from request and set metadata on response
contentLength, err := strconv.ParseInt(resp.Header.Get("Content-Length"), 10, 64) contentLength, err := strconv.ParseInt(resp.Header.Get("Content-Length"), 10, 64)

View File

@ -183,7 +183,10 @@ func (r *RoomserverAliasAPI) sendUpdatedAliasesEvent(
// Add auth events // Add auth events
authEvents := gomatrixserverlib.NewAuthEvents(nil) authEvents := gomatrixserverlib.NewAuthEvents(nil)
for i := range res.StateEvents { for i := range res.StateEvents {
authEvents.AddEvent(&res.StateEvents[i]) err = authEvents.AddEvent(&res.StateEvents[i])
if err != nil {
return err
}
} }
refs, err := eventsNeeded.AuthEventReferences(&authEvents) refs, err := eventsNeeded.AuthEventReferences(&authEvents)
if err != nil { if err != nil {

View File

@ -283,7 +283,7 @@ func (h *httpRoomserverQueryAPI) QueryServerAllowedToSeeEvent(
ctx context.Context, ctx context.Context,
request *QueryServerAllowedToSeeEventRequest, request *QueryServerAllowedToSeeEventRequest,
response *QueryServerAllowedToSeeEventResponse, response *QueryServerAllowedToSeeEventResponse,
) error { ) (err error) {
apiURL := h.roomserverURL + RoomserverQueryServerAllowedToSeeEventPath apiURL := h.roomserverURL + RoomserverQueryServerAllowedToSeeEventPath
return postJSON(ctx, h.httpClient, apiURL, request, response) return postJSON(ctx, h.httpClient, apiURL, request, response)
} }
@ -306,7 +306,7 @@ func postJSON(
res, err := httpClient.Do(req.WithContext(ctx)) res, err := httpClient.Do(req.WithContext(ctx))
if res != nil { if res != nil {
defer res.Body.Close() defer (func() { err = res.Body.Close() })()
} }
if err != nil { if err != nil {
return err return err

View File

@ -117,7 +117,10 @@ func processRoomEvent(
return err return err
} }
} }
db.SetState(ctx, stateAtEvent.EventNID, stateAtEvent.BeforeStateSnapshotNID) err = db.SetState(ctx, stateAtEvent.EventNID, stateAtEvent.BeforeStateSnapshotNID)
if err != nil {
return err
}
} }
if input.Kind == api.KindBackfill { if input.Kind == api.KindBackfill {

View File

@ -85,7 +85,7 @@ func (s *eventJSONStatements) bulkSelectEventJSON(
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer rows.Close() defer rows.Close() // nolint: errcheck
// We know that we will only get as many results as event NIDs // We know that we will only get as many results as event NIDs
// because of the unique constraint on event NIDs. // because of the unique constraint on event NIDs.

View File

@ -119,7 +119,7 @@ func (s *eventStateKeyStatements) bulkSelectEventStateKeyNID(
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer rows.Close() defer rows.Close() // nolint: errcheck
result := make(map[string]types.EventStateKeyNID, len(eventStateKeys)) result := make(map[string]types.EventStateKeyNID, len(eventStateKeys))
for rows.Next() { for rows.Next() {
@ -153,7 +153,7 @@ func (s *eventStateKeyStatements) bulkSelectEventStateKey(
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer rows.Close() defer rows.Close() // nolint: errcheck
result := make(map[types.EventStateKeyNID]string, len(eventStateKeyNIDs)) result := make(map[types.EventStateKeyNID]string, len(eventStateKeyNIDs))
for rows.Next() { for rows.Next() {

View File

@ -131,7 +131,7 @@ func (s *eventTypeStatements) bulkSelectEventTypeNID(
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer rows.Close() defer rows.Close() // nolint: errcheck
result := make(map[string]types.EventTypeNID, len(eventTypes)) result := make(map[string]types.EventTypeNID, len(eventTypes))
for rows.Next() { for rows.Next() {

View File

@ -191,7 +191,7 @@ func (s *eventStatements) bulkSelectStateEventByID(
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer rows.Close() defer rows.Close() // nolint: errcheck
// We know that we will only get as many results as event IDs // We know that we will only get as many results as event IDs
// because of the unique constraint on event IDs. // because of the unique constraint on event IDs.
// So we can allocate an array of the correct size now. // So we can allocate an array of the correct size now.
@ -231,7 +231,7 @@ func (s *eventStatements) bulkSelectStateAtEventByID(
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer rows.Close() defer rows.Close() // nolint: errcheck
results := make([]types.StateAtEvent, len(eventIDs)) results := make([]types.StateAtEvent, len(eventIDs))
i := 0 i := 0
for ; rows.Next(); i++ { for ; rows.Next(); i++ {
@ -269,7 +269,7 @@ func (s *eventStatements) selectEventSentToOutput(
ctx context.Context, txn *sql.Tx, eventNID types.EventNID, ctx context.Context, txn *sql.Tx, eventNID types.EventNID,
) (sentToOutput bool, err error) { ) (sentToOutput bool, err error) {
stmt := common.TxStmt(txn, s.selectEventSentToOutputStmt) stmt := common.TxStmt(txn, s.selectEventSentToOutputStmt)
stmt.QueryRowContext(ctx, int64(eventNID)).Scan(&sentToOutput) err = stmt.QueryRowContext(ctx, int64(eventNID)).Scan(&sentToOutput)
return return
} }
@ -295,7 +295,7 @@ func (s *eventStatements) bulkSelectStateAtEventAndReference(
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer rows.Close() defer rows.Close() // nolint: errcheck
results := make([]types.StateAtEventAndReference, len(eventNIDs)) results := make([]types.StateAtEventAndReference, len(eventNIDs))
i := 0 i := 0
for ; rows.Next(); i++ { for ; rows.Next(); i++ {
@ -333,7 +333,7 @@ func (s *eventStatements) bulkSelectEventReference(
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer rows.Close() defer rows.Close() // nolint: errcheck
results := make([]gomatrixserverlib.EventReference, len(eventNIDs)) results := make([]gomatrixserverlib.EventReference, len(eventNIDs))
i := 0 i := 0
for ; rows.Next(); i++ { for ; rows.Next(); i++ {
@ -354,7 +354,7 @@ func (s *eventStatements) bulkSelectEventID(ctx context.Context, eventNIDs []typ
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer rows.Close() defer rows.Close() // nolint: errcheck
results := make(map[types.EventNID]string, len(eventNIDs)) results := make(map[types.EventNID]string, len(eventNIDs))
i := 0 i := 0
for ; rows.Next(); i++ { for ; rows.Next(); i++ {
@ -378,7 +378,7 @@ func (s *eventStatements) bulkSelectEventNID(ctx context.Context, eventIDs []str
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer rows.Close() defer rows.Close() // nolint: errcheck
results := make(map[string]types.EventNID, len(eventIDs)) results := make(map[string]types.EventNID, len(eventIDs))
for rows.Next() { for rows.Next() {
var eventID string var eventID string

View File

@ -113,22 +113,21 @@ func (s *inviteStatements) insertInviteEvent(
func (s *inviteStatements) updateInviteRetired( func (s *inviteStatements) updateInviteRetired(
ctx context.Context, ctx context.Context,
txn *sql.Tx, roomNID types.RoomNID, targetUserNID types.EventStateKeyNID, txn *sql.Tx, roomNID types.RoomNID, targetUserNID types.EventStateKeyNID,
) ([]string, error) { ) (eventIDs []string, err error) {
stmt := common.TxStmt(txn, s.updateInviteRetiredStmt) stmt := common.TxStmt(txn, s.updateInviteRetiredStmt)
rows, err := stmt.QueryContext(ctx, roomNID, targetUserNID) rows, err := stmt.QueryContext(ctx, roomNID, targetUserNID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer rows.Close() defer (func() { err = rows.Close() })()
var result []string
for rows.Next() { for rows.Next() {
var inviteEventID string var inviteEventID string
if err := rows.Scan(&inviteEventID); err != nil { if err := rows.Scan(&inviteEventID); err != nil {
return nil, err return nil, err
} }
result = append(result, inviteEventID) eventIDs = append(eventIDs, inviteEventID)
} }
return result, nil return
} }
// selectInviteActiveForUserInRoom returns a list of sender state key NIDs // selectInviteActiveForUserInRoom returns a list of sender state key NIDs
@ -142,7 +141,7 @@ func (s *inviteStatements) selectInviteActiveForUserInRoom(
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer rows.Close() defer rows.Close() // nolint: errcheck
var result []types.EventStateKeyNID var result []types.EventStateKeyNID
for rows.Next() { for rows.Next() {
var senderUserNID int64 var senderUserNID int64

View File

@ -137,7 +137,7 @@ func (s *stateBlockStatements) bulkSelectStateBlockEntries(
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer rows.Close() defer rows.Close() // nolint: errcheck
results := make([]types.StateEntryList, len(stateBlockNIDs)) results := make([]types.StateEntryList, len(stateBlockNIDs))
// current is a pointer to the StateEntryList to append the state entries to. // current is a pointer to the StateEntryList to append the state entries to.
@ -193,7 +193,7 @@ func (s *stateBlockStatements) bulkSelectFilteredStateBlockEntries(
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer rows.Close() defer rows.Close() // nolint: errcheck
var results []types.StateEntryList var results []types.StateEntryList
var current types.StateEntryList var current types.StateEntryList

View File

@ -97,7 +97,7 @@ func (s *stateSnapshotStatements) bulkSelectStateBlockNIDs(
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer rows.Close() defer rows.Close() // nolint: errcheck
results := make([]types.StateBlockNIDList, len(stateNIDs)) results := make([]types.StateBlockNIDList, len(stateNIDs))
i := 0 i := 0
for ; rows.Next(); i++ { for ; rows.Next(); i++ {

View File

@ -287,19 +287,19 @@ func (d *Database) GetLatestEventsForUpdate(
eventNIDs, lastEventNIDSent, currentStateSnapshotNID, err := eventNIDs, lastEventNIDSent, currentStateSnapshotNID, err :=
d.statements.selectLatestEventsNIDsForUpdate(ctx, txn, roomNID) d.statements.selectLatestEventsNIDsForUpdate(ctx, txn, roomNID)
if err != nil { if err != nil {
txn.Rollback() txn.Rollback() // nolint: errcheck
return nil, err return nil, err
} }
stateAndRefs, err := d.statements.bulkSelectStateAtEventAndReference(ctx, txn, eventNIDs) stateAndRefs, err := d.statements.bulkSelectStateAtEventAndReference(ctx, txn, eventNIDs)
if err != nil { if err != nil {
txn.Rollback() txn.Rollback() // nolint: errcheck
return nil, err return nil, err
} }
var lastEventIDSent string var lastEventIDSent string
if lastEventNIDSent != 0 { if lastEventNIDSent != 0 {
lastEventIDSent, err = d.statements.selectEventID(ctx, txn, lastEventNIDSent) lastEventIDSent, err = d.statements.selectEventID(ctx, txn, lastEventNIDSent)
if err != nil { if err != nil {
txn.Rollback() txn.Rollback() // nolint: errcheck
return nil, err return nil, err
} }
} }
@ -459,7 +459,7 @@ func (d *Database) MembershipUpdater(
succeeded := false succeeded := false
defer func() { defer func() {
if !succeeded { if !succeeded {
txn.Rollback() txn.Rollback() // nolint: errcheck
} }
}() }()

View File

@ -87,7 +87,7 @@ func (s *accountDataStatements) insertAccountData(
ctx context.Context, ctx context.Context,
userID, roomID, dataType string, userID, roomID, dataType string,
) (pos int64, err error) { ) (pos int64, err error) {
s.insertAccountDataStmt.QueryRowContext(ctx, userID, roomID, dataType).Scan(&pos) err = s.insertAccountDataStmt.QueryRowContext(ctx, userID, roomID, dataType).Scan(&pos)
return return
} }

View File

@ -122,7 +122,7 @@ func (s *currentRoomStateStatements) selectJoinedUsers(
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer rows.Close() defer rows.Close() // nolint: errcheck
result := make(map[string][]string) result := make(map[string][]string)
for rows.Next() { for rows.Next() {
@ -147,7 +147,7 @@ func (s *currentRoomStateStatements) selectRoomIDsWithMembership(
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer rows.Close() defer rows.Close() // nolint: errcheck
var result []string var result []string
for rows.Next() { for rows.Next() {
@ -169,7 +169,7 @@ func (s *currentRoomStateStatements) selectCurrentState(
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer rows.Close() defer rows.Close() // nolint: errcheck
return rowsToEvents(rows) return rowsToEvents(rows)
} }
@ -208,7 +208,7 @@ func (s *currentRoomStateStatements) selectEventsWithEventIDs(
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer rows.Close() defer rows.Close() // nolint: errcheck
return rowsToStreamEvents(rows) return rowsToStreamEvents(rows)
} }

View File

@ -213,7 +213,7 @@ func (s *outputRoomEventsStatements) selectRecentEvents(
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer rows.Close() defer rows.Close() // nolint: errcheck
events, err := rowsToStreamEvents(rows) events, err := rowsToStreamEvents(rows)
if err != nil { if err != nil {
return nil, err return nil, err
@ -233,7 +233,7 @@ func (s *outputRoomEventsStatements) selectEvents(
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer rows.Close() defer rows.Close() // nolint: errcheck
return rowsToStreamEvents(rows) return rowsToStreamEvents(rows)
} }