From 8a36a7e89b5408f22b5c83cf5ec358e7affc2127 Mon Sep 17 00:00:00 2001 From: Erik Johnston Date: Wed, 20 Sep 2017 10:59:19 +0100 Subject: [PATCH] Add errcheck linter (#238) * Add errcheck linter * Add config for 'fast' linters * Fix errcheck lint stuff * Fix errcheck lint --- linter-fast.json | 15 +++++++++++ linter.json | 3 ++- .../auth/storage/accounts/membership_table.go | 2 +- .../dendrite/clientapi/events/events.go | 5 +++- .../dendrite/clientapi/httputil/httputil.go | 2 +- .../clientapi/readers/account_data.go | 2 +- .../dendrite/clientapi/writers/createroom.go | 12 ++++++--- .../dendrite/clientapi/writers/joinroom.go | 27 +++++++++++++++---- .../dendrite/clientapi/writers/sendevent.go | 5 +++- .../dendrite/cmd/create-room-events/main.go | 6 ++--- .../cmd/mediaapi-integration-tests/main.go | 9 ++++--- .../cmd/roomserver-integration-tests/main.go | 10 ++++--- .../cmd/syncserver-integration-tests/main.go | 20 ++++++++++---- .../matrix-org/dendrite/common/consumers.go | 4 +-- .../matrix-org/dendrite/common/keydb/keydb.go | 5 +++- .../dendrite/common/keydb/server_key_table.go | 2 +- .../dendrite/common/partition_offset_table.go | 2 +- .../matrix-org/dendrite/common/sql.go | 4 +-- .../matrix-org/dendrite/common/test/client.go | 4 +-- .../matrix-org/dendrite/common/test/config.go | 15 +++++++---- .../dendrite/federationapi/writers/send.go | 5 +++- .../federationapi/writers/threepid.go | 5 +++- .../storage/joined_hosts_table.go | 2 +- .../dendrite/mediaapi/fileutils/fileutils.go | 21 ++++++++++----- .../mediaapi/thumbnailer/thumbnailer_nfnt.go | 6 ++--- .../dendrite/mediaapi/writers/download.go | 16 ++++++----- .../dendrite/roomserver/alias/alias.go | 5 +++- .../dendrite/roomserver/api/query.go | 4 +-- .../dendrite/roomserver/input/events.go | 5 +++- .../roomserver/storage/event_json_table.go | 2 +- .../storage/event_state_keys_table.go | 4 +-- .../roomserver/storage/event_types_table.go | 2 +- .../roomserver/storage/events_table.go | 14 +++++----- .../roomserver/storage/invite_table.go | 11 ++++---- .../roomserver/storage/state_block_table.go | 4 +-- .../storage/state_snapshot_table.go | 2 +- .../dendrite/roomserver/storage/storage.go | 8 +++--- .../syncapi/storage/account_data_table.go | 2 +- .../storage/current_room_state_table.go | 8 +++--- .../storage/output_room_events_table.go | 4 +-- 40 files changed, 186 insertions(+), 98 deletions(-) create mode 100644 linter-fast.json diff --git a/linter-fast.json b/linter-fast.json new file mode 100644 index 000000000..2abb30aff --- /dev/null +++ b/linter-fast.json @@ -0,0 +1,15 @@ +{ + "Vendor": true, + "Cyclo": 12, + "Deadline": "5m", + "Enable": [ + "vetshadow", + "gotype", + "deadcode", + "gocyclo", + "ineffassign", + "gas", + "misspell", + "errcheck" + ] +} diff --git a/linter.json b/linter.json index 1c8525159..649e6a0e5 100644 --- a/linter.json +++ b/linter.json @@ -14,6 +14,7 @@ "ineffassign", "gas", "misspell", - "unparam" + "unparam", + "errcheck" ] } diff --git a/src/github.com/matrix-org/dendrite/clientapi/auth/storage/accounts/membership_table.go b/src/github.com/matrix-org/dendrite/clientapi/auth/storage/accounts/membership_table.go index 75b65b53b..11cecb8b6 100644 --- a/src/github.com/matrix-org/dendrite/clientapi/auth/storage/accounts/membership_table.go +++ b/src/github.com/matrix-org/dendrite/clientapi/auth/storage/accounts/membership_table.go @@ -108,7 +108,7 @@ func (s *membershipStatements) selectMembershipsByLocalpart( memberships = []authtypes.Membership{} - defer rows.Close() + defer rows.Close() // nolint: errcheck for rows.Next() { var m authtypes.Membership m.Localpart = localpart diff --git a/src/github.com/matrix-org/dendrite/clientapi/events/events.go b/src/github.com/matrix-org/dendrite/clientapi/events/events.go index f61ca937f..23cb5bbc2 100644 --- a/src/github.com/matrix-org/dendrite/clientapi/events/events.go +++ b/src/github.com/matrix-org/dendrite/clientapi/events/events.go @@ -69,7 +69,10 @@ func BuildEvent( authEvents := gomatrixserverlib.NewAuthEvents(nil) 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) diff --git a/src/github.com/matrix-org/dendrite/clientapi/httputil/httputil.go b/src/github.com/matrix-org/dendrite/clientapi/httputil/httputil.go index 7bc8a46d2..8135b9ddb 100644 --- a/src/github.com/matrix-org/dendrite/clientapi/httputil/httputil.go +++ b/src/github.com/matrix-org/dendrite/clientapi/httputil/httputil.go @@ -25,7 +25,7 @@ import ( // UnmarshalJSONRequest into the given interface pointer. Returns an error JSON response if // there was a problem unmarshalling. Calling this function consumes the request body. 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 { // 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 diff --git a/src/github.com/matrix-org/dendrite/clientapi/readers/account_data.go b/src/github.com/matrix-org/dendrite/clientapi/readers/account_data.go index bd64e2b03..9846fd61b 100644 --- a/src/github.com/matrix-org/dendrite/clientapi/readers/account_data.go +++ b/src/github.com/matrix-org/dendrite/clientapi/readers/account_data.go @@ -52,7 +52,7 @@ func SaveAccountData( return httputil.LogThenError(req, err) } - defer req.Body.Close() + defer req.Body.Close() // nolint: errcheck body, err := ioutil.ReadAll(req.Body) if err != nil { diff --git a/src/github.com/matrix-org/dendrite/clientapi/writers/createroom.go b/src/github.com/matrix-org/dendrite/clientapi/writers/createroom.go index d948c919d..7d5d318db 100644 --- a/src/github.com/matrix-org/dendrite/clientapi/writers/createroom.go +++ b/src/github.com/matrix-org/dendrite/clientapi/writers/createroom.go @@ -185,7 +185,10 @@ func createRoom(req *http.Request, device *authtypes.Device, StateKey: &e.StateKey, Depth: int64(depth), } - builder.SetContent(e.Content) + err = builder.SetContent(e.Content) + if err != nil { + return httputil.LogThenError(req, err) + } if i > 0 { 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) } - if err := gomatrixserverlib.Allowed(*ev, &authEvents); err != nil { + if err = gomatrixserverlib.Allowed(*ev, &authEvents); err != nil { return httputil.LogThenError(req, err) } // Add the event to the list of auth events 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 diff --git a/src/github.com/matrix-org/dendrite/clientapi/writers/joinroom.go b/src/github.com/matrix-org/dendrite/clientapi/writers/joinroom.go index b6520d83b..fde934ac2 100644 --- a/src/github.com/matrix-org/dendrite/clientapi/writers/joinroom.go +++ b/src/github.com/matrix-org/dendrite/clientapi/writers/joinroom.go @@ -153,21 +153,35 @@ func (r joinRoomReq) joinRoomByRemoteAlias( 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.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.StateKey = &r.userID eb.RoomID = roomID eb.Redacts = "" + + return nil } func (r joinRoomReq) joinRoomUsingServers( roomID string, servers []gomatrixserverlib.ServerName, ) util.JSONResponse { 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 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 // 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() eventID := fmt.Sprintf("$%s:%s", util.RandomString(16), r.cfg.Matrix.ServerName) diff --git a/src/github.com/matrix-org/dendrite/clientapi/writers/sendevent.go b/src/github.com/matrix-org/dendrite/clientapi/writers/sendevent.go index 904e7eaba..f11d04217 100644 --- a/src/github.com/matrix-org/dendrite/clientapi/writers/sendevent.go +++ b/src/github.com/matrix-org/dendrite/clientapi/writers/sendevent.go @@ -60,7 +60,10 @@ func SendEvent( Type: eventType, StateKey: stateKey, } - builder.SetContent(r) + err := builder.SetContent(r) + if err != nil { + return httputil.LogThenError(req, err) + } var queryRes api.QueryLatestEventsAndStateResponse e, err := events.BuildEvent(req.Context(), &builder, cfg, queryAPI, &queryRes) diff --git a/src/github.com/matrix-org/dendrite/cmd/create-room-events/main.go b/src/github.com/matrix-org/dendrite/cmd/create-room-events/main.go index c7b9d953b..2992cba9d 100644 --- a/src/github.com/matrix-org/dendrite/cmd/create-room-events/main.go +++ b/src/github.com/matrix-org/dendrite/cmd/create-room-events/main.go @@ -80,20 +80,20 @@ func main() { b.RoomID = *roomID b.Type = "m.room.create" b.StateKey = &emptyString - b.SetContent(map[string]string{"creator": *userID}) + b.SetContent(map[string]string{"creator": *userID}) // nolint: errcheck create := buildAndOutput() // Build a m.room.member event. b.Type = "m.room.member" b.StateKey = userID - b.SetContent(map[string]string{"membership": "join"}) + b.SetContent(map[string]string{"membership": "join"}) // nolint: errcheck b.AuthEvents = []gomatrixserverlib.EventReference{create} member := buildAndOutput() // Build a number of m.room.message events. b.Type = "m.room.message" 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} for i := 0; i < *messageCount; i++ { buildAndOutput() diff --git a/src/github.com/matrix-org/dendrite/cmd/mediaapi-integration-tests/main.go b/src/github.com/matrix-org/dendrite/cmd/mediaapi-integration-tests/main.go index 6eaa9ea3a..c190c10bf 100644 --- a/src/github.com/matrix-org/dendrite/cmd/mediaapi-integration-tests/main.go +++ b/src/github.com/matrix-org/dendrite/cmd/mediaapi-integration-tests/main.go @@ -125,7 +125,8 @@ func startMediaAPI(suffix string, dynamicThumbnails bool) (*exec.Cmd, chan error } 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 { 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 server1Cmd, server1CmdChan, _, server1ProxyCmd, _, server1ProxyAddr, server1Dir := startMediaAPI("1", false) defer cleanUpServer(server1Cmd, server1Dir) - defer server1ProxyCmd.Process.Kill() + defer server1ProxyCmd.Process.Kill() // nolint: errcheck testDownload(server1ProxyAddr, server1ProxyAddr, "doesnotexist", 404, server1CmdChan) // upload a JPEG file @@ -163,7 +164,7 @@ func main() { // create server2 with dynamic thumbnail generation server2Cmd, server2CmdChan, _, server2ProxyCmd, _, server2ProxyAddr, server2Dir := startMediaAPI("2", true) defer cleanUpServer(server2Cmd, server2Dir) - defer server2ProxyCmd.Process.Kill() + defer server2ProxyCmd.Process.Kill() // nolint: errcheck testDownload(server2ProxyAddr, server2ProxyAddr, "doesnotexist", 404, server2CmdChan) // 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) { fmt.Printf("==TESTING== upload %v to %v\n", filePath, host) file, err := os.Open(filePath) - defer file.Close() + defer file.Close() // nolint: errcheck if err != nil { panic(err) } diff --git a/src/github.com/matrix-org/dendrite/cmd/roomserver-integration-tests/main.go b/src/github.com/matrix-org/dendrite/cmd/roomserver-integration-tests/main.go index 06f9af138..126a91437 100644 --- a/src/github.com/matrix-org/dendrite/cmd/roomserver-integration-tests/main.go +++ b/src/github.com/matrix-org/dendrite/cmd/roomserver-integration-tests/main.go @@ -114,8 +114,8 @@ func runAndReadFromTopic(runCmd *exec.Cmd, readyURL string, doInput func(), topi readCmd.Stderr = os.Stderr // Kill both processes before we exit. - defer func() { runCmd.Process.Kill() }() - defer func() { readCmd.Process.Kill() }() + defer func() { runCmd.Process.Kill() }() // nolint: errcheck + defer func() { readCmd.Process.Kill() }() // nolint: errcheck // Run the command, read the messages and wait for a timeout in parallel. go func() { @@ -228,7 +228,11 @@ func testRoomserver(input []string, wantOutput []string, checkQueries func(api.R 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 { panic(err) } diff --git a/src/github.com/matrix-org/dendrite/cmd/syncserver-integration-tests/main.go b/src/github.com/matrix-org/dendrite/cmd/syncserver-integration-tests/main.go index e39a89808..7f315cd33 100644 --- a/src/github.com/matrix-org/dendrite/cmd/syncserver-integration-tests/main.go +++ b/src/github.com/matrix-org/dendrite/cmd/syncserver-integration-tests/main.go @@ -175,12 +175,21 @@ func startSyncServer() (*exec.Cmd, chan error) { // prepareKafka creates the topics which will be written to by the tests. func prepareKafka() { - exe.DeleteTopic(inputTopic) - if err := exe.CreateTopic(inputTopic); err != nil { + err := exe.DeleteTopic(inputTopic) + if err != nil { 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) } } @@ -225,7 +234,8 @@ func main() { fmt.Println("==TESTING==", os.Args[0]) prepareKafka() 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 -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" diff --git a/src/github.com/matrix-org/dendrite/common/consumers.go b/src/github.com/matrix-org/dendrite/common/consumers.go index 8f900ab67..e3f999111 100644 --- a/src/github.com/matrix-org/dendrite/common/consumers.go +++ b/src/github.com/matrix-org/dendrite/common/consumers.go @@ -91,7 +91,7 @@ func (c *ContinualConsumer) Start() error { pc, err := c.Consumer.ConsumePartition(c.Topic, partition, offset) if err != nil { for _, p := range partitionConsumers { - p.Close() + p.Close() // nolint: errcheck } return err } @@ -106,7 +106,7 @@ func (c *ContinualConsumer) Start() error { // consumePartition consumes the room events for a single partition of the kafkaesque stream. func (c *ContinualConsumer) consumePartition(pc sarama.PartitionConsumer) { - defer pc.Close() + defer pc.Close() // nolint: errcheck for message := range pc.Messages() { msgErr := c.ProcessMessage(message) // Advance our position in the stream so that we will start at the right position after a restart. diff --git a/src/github.com/matrix-org/dendrite/common/keydb/keydb.go b/src/github.com/matrix-org/dendrite/common/keydb/keydb.go index cfb1d34ed..8d5a6ddee 100644 --- a/src/github.com/matrix-org/dendrite/common/keydb/keydb.go +++ b/src/github.com/matrix-org/dendrite/common/keydb/keydb.go @@ -37,7 +37,10 @@ func NewDatabase(dataSourceName string) (*Database, error) { return nil, err } d := &Database{} - d.statements.prepare(db) + err = d.statements.prepare(db) + if err != nil { + return nil, err + } return d, nil } diff --git a/src/github.com/matrix-org/dendrite/common/keydb/server_key_table.go b/src/github.com/matrix-org/dendrite/common/keydb/server_key_table.go index 936470d7b..a459bd8c3 100644 --- a/src/github.com/matrix-org/dendrite/common/keydb/server_key_table.go +++ b/src/github.com/matrix-org/dendrite/common/keydb/server_key_table.go @@ -83,7 +83,7 @@ func (s *serverKeyStatements) bulkSelectServerKeys( if err != nil { return nil, err } - defer rows.Close() + defer rows.Close() // nolint: errcheck results := map[gomatrixserverlib.PublicKeyRequest]gomatrixserverlib.ServerKeys{} for rows.Next() { var serverName string diff --git a/src/github.com/matrix-org/dendrite/common/partition_offset_table.go b/src/github.com/matrix-org/dendrite/common/partition_offset_table.go index 3898cc1f7..63aa61a57 100644 --- a/src/github.com/matrix-org/dendrite/common/partition_offset_table.go +++ b/src/github.com/matrix-org/dendrite/common/partition_offset_table.go @@ -71,7 +71,7 @@ func (s *PartitionOffsetStatements) SelectPartitionOffsets(topic string) ([]Part if err != nil { return nil, err } - defer rows.Close() + defer rows.Close() // nolint: errcheck var results []PartitionOffset for rows.Next() { var offset PartitionOffset diff --git a/src/github.com/matrix-org/dendrite/common/sql.go b/src/github.com/matrix-org/dendrite/common/sql.go index c2fb753fc..f3de66f11 100644 --- a/src/github.com/matrix-org/dendrite/common/sql.go +++ b/src/github.com/matrix-org/dendrite/common/sql.go @@ -30,9 +30,9 @@ type Transaction interface { // If the transaction succeeded then it is committed, otherwise it is rolledback. func EndTransaction(txn Transaction, succeeded *bool) { if *succeeded { - txn.Commit() + txn.Commit() // nolint: errcheck } else { - txn.Rollback() + txn.Rollback() // nolint: errcheck } } diff --git a/src/github.com/matrix-org/dendrite/common/test/client.go b/src/github.com/matrix-org/dendrite/common/test/client.go index 7d7b0589b..d1c40e53f 100644 --- a/src/github.com/matrix-org/dendrite/common/test/client.go +++ b/src/github.com/matrix-org/dendrite/common/test/client.go @@ -69,7 +69,7 @@ func CanonicalJSONInput(jsonData []string) []string { } // 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{ Timeout: 5 * time.Second, Transport: &http.Transport{ @@ -82,7 +82,7 @@ func (r *Request) Do() error { if err != nil { return err } - defer res.Body.Close() + defer (func() { err = res.Body.Close() })() if res.StatusCode != r.WantedStatusCode { return fmt.Errorf("incorrect status code. Expected: %d Got: %d", r.WantedStatusCode, res.StatusCode) diff --git a/src/github.com/matrix-org/dendrite/common/test/config.go b/src/github.com/matrix-org/dendrite/common/test/config.go index 1e5d08210..d29b754ea 100644 --- a/src/github.com/matrix-org/dendrite/common/test/config.go +++ b/src/github.com/matrix-org/dendrite/common/test/config.go @@ -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. -func NewMatrixKey(matrixKeyPath string) error { +func NewMatrixKey(matrixKeyPath string) (err error) { var data [35]byte - if _, err := rand.Read(data[:]); err != nil { + _, err = rand.Read(data[:]) + if err != nil { return err } keyOut, err := os.OpenFile(matrixKeyPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) if err != nil { return err } - defer keyOut.Close() + + defer (func() { + err = keyOut.Close() + })() + if err = pem.Encode(keyOut, &pem.Block{ Type: "MATRIX PRIVATE KEY", Headers: map[string]string{ @@ -176,7 +181,7 @@ func NewTLSKey(tlsKeyPath, tlsCertPath string) error { if err != nil { return err } - defer certOut.Close() + defer certOut.Close() // nolint: errcheck if err = pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}); err != nil { return err } @@ -185,7 +190,7 @@ func NewTLSKey(tlsKeyPath, tlsCertPath string) error { if err != nil { return err } - defer keyOut.Close() + defer keyOut.Close() // nolint: errcheck if err = pem.Encode(keyOut, &pem.Block{ Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv), diff --git a/src/github.com/matrix-org/dendrite/federationapi/writers/send.go b/src/github.com/matrix-org/dendrite/federationapi/writers/send.go index 3b66ca43f..00e1d8d57 100644 --- a/src/github.com/matrix-org/dendrite/federationapi/writers/send.go +++ b/src/github.com/matrix-org/dendrite/federationapi/writers/send.go @@ -180,7 +180,10 @@ func (t *txnReq) processEvent(e gomatrixserverlib.Event) error { func checkAllowedByState(e gomatrixserverlib.Event, stateEvents []gomatrixserverlib.Event) error { authUsingState := gomatrixserverlib.NewAuthEvents(nil) for i := range stateEvents { - authUsingState.AddEvent(&stateEvents[i]) + err := authUsingState.AddEvent(&stateEvents[i]) + if err != nil { + return err + } } return gomatrixserverlib.Allowed(e, &authUsingState) } diff --git a/src/github.com/matrix-org/dendrite/federationapi/writers/threepid.go b/src/github.com/matrix-org/dendrite/federationapi/writers/threepid.go index 2d7bac3de..1ab03a341 100644 --- a/src/github.com/matrix-org/dendrite/federationapi/writers/threepid.go +++ b/src/github.com/matrix-org/dendrite/federationapi/writers/threepid.go @@ -257,7 +257,10 @@ func buildMembershipEvent( authEvents := gomatrixserverlib.NewAuthEvents(nil) 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 { diff --git a/src/github.com/matrix-org/dendrite/federationsender/storage/joined_hosts_table.go b/src/github.com/matrix-org/dendrite/federationsender/storage/joined_hosts_table.go index 3b9510d70..487de9e61 100644 --- a/src/github.com/matrix-org/dendrite/federationsender/storage/joined_hosts_table.go +++ b/src/github.com/matrix-org/dendrite/federationsender/storage/joined_hosts_table.go @@ -105,7 +105,7 @@ func (s *joinedHostsStatements) selectJoinedHosts( if err != nil { return nil, err } - defer rows.Close() + defer rows.Close() // nolint: errcheck var result []types.JoinedHost for rows.Next() { diff --git a/src/github.com/matrix-org/dendrite/mediaapi/fileutils/fileutils.go b/src/github.com/matrix-org/dendrite/mediaapi/fileutils/fileutils.go index 0c2ba876a..e9a1a5193 100644 --- a/src/github.com/matrix-org/dendrite/mediaapi/fileutils/fileutils.go +++ b/src/github.com/matrix-org/dendrite/mediaapi/fileutils/fileutils.go @@ -105,12 +105,14 @@ func RemoveDir(dir types.Path, logger *log.Entry) { } // 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) 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. limitedReader := io.LimitReader(reqReader, int64(maxFileSizeBytes)) @@ -121,13 +123,18 @@ func WriteTempFile(reqReader io.Reader, maxFileSizeBytes config.FileSizeBytes, a teeReader := io.TeeReader(limitedReader, hasher) bytesWritten, err := io.Copy(tmpFileWriter, teeReader) if err != nil && err != io.EOF { - return "", -1, "", err + return } - tmpFileWriter.Flush() + err = tmpFileWriter.Flush() + if err != nil { + return + } - hash := hasher.Sum(nil) - return types.Base64Hash(base64.RawURLEncoding.EncodeToString(hash[:])), types.FileSizeBytes(bytesWritten), tmpDir, nil + hash = types.Base64Hash(base64.RawURLEncoding.EncodeToString(hasher.Sum(nil)[:])) + size = types.FileSizeBytes(bytesWritten) + path = tmpDir + return } // moveFile attempts to move the file src to dst diff --git a/src/github.com/matrix-org/dendrite/mediaapi/thumbnailer/thumbnailer_nfnt.go b/src/github.com/matrix-org/dendrite/mediaapi/thumbnailer/thumbnailer_nfnt.go index 3e822dd02..06607f719 100644 --- a/src/github.com/matrix-org/dendrite/mediaapi/thumbnailer/thumbnailer_nfnt.go +++ b/src/github.com/matrix-org/dendrite/mediaapi/thumbnailer/thumbnailer_nfnt.go @@ -83,7 +83,7 @@ func readFile(src string) (image.Image, error) { if err != nil { return nil, err } - defer file.Close() + defer file.Close() // nolint: errcheck img, _, err := image.Decode(file) if err != nil { @@ -93,12 +93,12 @@ func readFile(src string) (image.Image, error) { 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) if err != nil { return err } - defer out.Close() + defer (func() { err = out.Close() })() return jpeg.Encode(out, img, &jpeg.Options{ Quality: 85, diff --git a/src/github.com/matrix-org/dendrite/mediaapi/writers/download.go b/src/github.com/matrix-org/dendrite/mediaapi/writers/download.go index 926d2fbe7..490685809 100644 --- a/src/github.com/matrix-org/dendrite/mediaapi/writers/download.go +++ b/src/github.com/matrix-org/dendrite/mediaapi/writers/download.go @@ -148,7 +148,9 @@ func (r *downloadRequest) jsonErrorResponse(w http.ResponseWriter, res util.JSON // Set status code and write the body w.WriteHeader(res.Code) 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 @@ -234,7 +236,7 @@ func (r *downloadRequest) respondFromLocalFile( return nil, errors.Wrap(err, "failed to get file path from metadata") } file, err := os.Open(filePath) - defer file.Close() + defer file.Close() // nolint: errcheck if err != nil { return nil, errors.Wrap(err, "failed to open file") } @@ -256,7 +258,7 @@ func (r *downloadRequest) respondFromLocalFile( if r.IsThumbnailRequest { thumbFile, thumbMetadata, resErr := r.getThumbnailFile(types.Path(filePath), activeThumbnailGeneration, maxThumbnailGenerators, db, dynamicThumbnails, thumbnailSizes) if thumbFile != nil { - defer thumbFile.Close() + defer thumbFile.Close() // nolint: errcheck } if resErr != nil { return nil, resErr @@ -360,16 +362,16 @@ func (r *downloadRequest) getThumbnailFile( thumbPath := string(thumbnailer.GetThumbnailPath(types.Path(filePath), thumbnail.ThumbnailSize)) thumbFile, err := os.Open(string(thumbPath)) if err != nil { - thumbFile.Close() + thumbFile.Close() // nolint: errcheck return nil, nil, errors.Wrap(err, "failed to open file") } thumbStat, err := thumbFile.Stat() if err != nil { - thumbFile.Close() + thumbFile.Close() // nolint: errcheck return nil, nil, errors.Wrap(err, "failed to stat file") } 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 thumbFile, thumbnail, nil @@ -564,7 +566,7 @@ func (r *downloadRequest) fetchRemoteFile(absBasePath config.Path, maxFileSizeBy // Remote file not found return "", false, nil } - defer resp.Body.Close() + defer resp.Body.Close() // nolint: errcheck // get metadata from request and set metadata on response contentLength, err := strconv.ParseInt(resp.Header.Get("Content-Length"), 10, 64) diff --git a/src/github.com/matrix-org/dendrite/roomserver/alias/alias.go b/src/github.com/matrix-org/dendrite/roomserver/alias/alias.go index 0ea3f238e..91aa3a262 100644 --- a/src/github.com/matrix-org/dendrite/roomserver/alias/alias.go +++ b/src/github.com/matrix-org/dendrite/roomserver/alias/alias.go @@ -183,7 +183,10 @@ func (r *RoomserverAliasAPI) sendUpdatedAliasesEvent( // Add auth events authEvents := gomatrixserverlib.NewAuthEvents(nil) 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) if err != nil { diff --git a/src/github.com/matrix-org/dendrite/roomserver/api/query.go b/src/github.com/matrix-org/dendrite/roomserver/api/query.go index c42c6821a..9222b1687 100644 --- a/src/github.com/matrix-org/dendrite/roomserver/api/query.go +++ b/src/github.com/matrix-org/dendrite/roomserver/api/query.go @@ -283,7 +283,7 @@ func (h *httpRoomserverQueryAPI) QueryServerAllowedToSeeEvent( ctx context.Context, request *QueryServerAllowedToSeeEventRequest, response *QueryServerAllowedToSeeEventResponse, -) error { +) (err error) { apiURL := h.roomserverURL + RoomserverQueryServerAllowedToSeeEventPath return postJSON(ctx, h.httpClient, apiURL, request, response) } @@ -306,7 +306,7 @@ func postJSON( res, err := httpClient.Do(req.WithContext(ctx)) if res != nil { - defer res.Body.Close() + defer (func() { err = res.Body.Close() })() } if err != nil { return err diff --git a/src/github.com/matrix-org/dendrite/roomserver/input/events.go b/src/github.com/matrix-org/dendrite/roomserver/input/events.go index c7a33f52e..57b20961d 100644 --- a/src/github.com/matrix-org/dendrite/roomserver/input/events.go +++ b/src/github.com/matrix-org/dendrite/roomserver/input/events.go @@ -117,7 +117,10 @@ func processRoomEvent( 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 { diff --git a/src/github.com/matrix-org/dendrite/roomserver/storage/event_json_table.go b/src/github.com/matrix-org/dendrite/roomserver/storage/event_json_table.go index 63792d154..b81667d9d 100644 --- a/src/github.com/matrix-org/dendrite/roomserver/storage/event_json_table.go +++ b/src/github.com/matrix-org/dendrite/roomserver/storage/event_json_table.go @@ -85,7 +85,7 @@ func (s *eventJSONStatements) bulkSelectEventJSON( if err != nil { return nil, err } - defer rows.Close() + defer rows.Close() // nolint: errcheck // We know that we will only get as many results as event NIDs // because of the unique constraint on event NIDs. diff --git a/src/github.com/matrix-org/dendrite/roomserver/storage/event_state_keys_table.go b/src/github.com/matrix-org/dendrite/roomserver/storage/event_state_keys_table.go index 46f2434a8..0bf711323 100644 --- a/src/github.com/matrix-org/dendrite/roomserver/storage/event_state_keys_table.go +++ b/src/github.com/matrix-org/dendrite/roomserver/storage/event_state_keys_table.go @@ -119,7 +119,7 @@ func (s *eventStateKeyStatements) bulkSelectEventStateKeyNID( if err != nil { return nil, err } - defer rows.Close() + defer rows.Close() // nolint: errcheck result := make(map[string]types.EventStateKeyNID, len(eventStateKeys)) for rows.Next() { @@ -153,7 +153,7 @@ func (s *eventStateKeyStatements) bulkSelectEventStateKey( if err != nil { return nil, err } - defer rows.Close() + defer rows.Close() // nolint: errcheck result := make(map[types.EventStateKeyNID]string, len(eventStateKeyNIDs)) for rows.Next() { diff --git a/src/github.com/matrix-org/dendrite/roomserver/storage/event_types_table.go b/src/github.com/matrix-org/dendrite/roomserver/storage/event_types_table.go index 2d9f290e3..7b8d53a5d 100644 --- a/src/github.com/matrix-org/dendrite/roomserver/storage/event_types_table.go +++ b/src/github.com/matrix-org/dendrite/roomserver/storage/event_types_table.go @@ -131,7 +131,7 @@ func (s *eventTypeStatements) bulkSelectEventTypeNID( if err != nil { return nil, err } - defer rows.Close() + defer rows.Close() // nolint: errcheck result := make(map[string]types.EventTypeNID, len(eventTypes)) for rows.Next() { diff --git a/src/github.com/matrix-org/dendrite/roomserver/storage/events_table.go b/src/github.com/matrix-org/dendrite/roomserver/storage/events_table.go index bcf17c26c..5bad939fa 100644 --- a/src/github.com/matrix-org/dendrite/roomserver/storage/events_table.go +++ b/src/github.com/matrix-org/dendrite/roomserver/storage/events_table.go @@ -191,7 +191,7 @@ func (s *eventStatements) bulkSelectStateEventByID( if err != nil { return nil, err } - defer rows.Close() + defer rows.Close() // nolint: errcheck // We know that we will only get as many results as event IDs // because of the unique constraint on event IDs. // So we can allocate an array of the correct size now. @@ -231,7 +231,7 @@ func (s *eventStatements) bulkSelectStateAtEventByID( if err != nil { return nil, err } - defer rows.Close() + defer rows.Close() // nolint: errcheck results := make([]types.StateAtEvent, len(eventIDs)) i := 0 for ; rows.Next(); i++ { @@ -269,7 +269,7 @@ func (s *eventStatements) selectEventSentToOutput( ctx context.Context, txn *sql.Tx, eventNID types.EventNID, ) (sentToOutput bool, err error) { stmt := common.TxStmt(txn, s.selectEventSentToOutputStmt) - stmt.QueryRowContext(ctx, int64(eventNID)).Scan(&sentToOutput) + err = stmt.QueryRowContext(ctx, int64(eventNID)).Scan(&sentToOutput) return } @@ -295,7 +295,7 @@ func (s *eventStatements) bulkSelectStateAtEventAndReference( if err != nil { return nil, err } - defer rows.Close() + defer rows.Close() // nolint: errcheck results := make([]types.StateAtEventAndReference, len(eventNIDs)) i := 0 for ; rows.Next(); i++ { @@ -333,7 +333,7 @@ func (s *eventStatements) bulkSelectEventReference( if err != nil { return nil, err } - defer rows.Close() + defer rows.Close() // nolint: errcheck results := make([]gomatrixserverlib.EventReference, len(eventNIDs)) i := 0 for ; rows.Next(); i++ { @@ -354,7 +354,7 @@ func (s *eventStatements) bulkSelectEventID(ctx context.Context, eventNIDs []typ if err != nil { return nil, err } - defer rows.Close() + defer rows.Close() // nolint: errcheck results := make(map[types.EventNID]string, len(eventNIDs)) i := 0 for ; rows.Next(); i++ { @@ -378,7 +378,7 @@ func (s *eventStatements) bulkSelectEventNID(ctx context.Context, eventIDs []str if err != nil { return nil, err } - defer rows.Close() + defer rows.Close() // nolint: errcheck results := make(map[string]types.EventNID, len(eventIDs)) for rows.Next() { var eventID string diff --git a/src/github.com/matrix-org/dendrite/roomserver/storage/invite_table.go b/src/github.com/matrix-org/dendrite/roomserver/storage/invite_table.go index 76fa3e044..4f9cdfb41 100644 --- a/src/github.com/matrix-org/dendrite/roomserver/storage/invite_table.go +++ b/src/github.com/matrix-org/dendrite/roomserver/storage/invite_table.go @@ -113,22 +113,21 @@ func (s *inviteStatements) insertInviteEvent( func (s *inviteStatements) updateInviteRetired( ctx context.Context, txn *sql.Tx, roomNID types.RoomNID, targetUserNID types.EventStateKeyNID, -) ([]string, error) { +) (eventIDs []string, err error) { stmt := common.TxStmt(txn, s.updateInviteRetiredStmt) rows, err := stmt.QueryContext(ctx, roomNID, targetUserNID) if err != nil { return nil, err } - defer rows.Close() - var result []string + defer (func() { err = rows.Close() })() for rows.Next() { var inviteEventID string if err := rows.Scan(&inviteEventID); err != nil { return nil, err } - result = append(result, inviteEventID) + eventIDs = append(eventIDs, inviteEventID) } - return result, nil + return } // selectInviteActiveForUserInRoom returns a list of sender state key NIDs @@ -142,7 +141,7 @@ func (s *inviteStatements) selectInviteActiveForUserInRoom( if err != nil { return nil, err } - defer rows.Close() + defer rows.Close() // nolint: errcheck var result []types.EventStateKeyNID for rows.Next() { var senderUserNID int64 diff --git a/src/github.com/matrix-org/dendrite/roomserver/storage/state_block_table.go b/src/github.com/matrix-org/dendrite/roomserver/storage/state_block_table.go index 136f61c47..b2e8ef8a6 100644 --- a/src/github.com/matrix-org/dendrite/roomserver/storage/state_block_table.go +++ b/src/github.com/matrix-org/dendrite/roomserver/storage/state_block_table.go @@ -137,7 +137,7 @@ func (s *stateBlockStatements) bulkSelectStateBlockEntries( if err != nil { return nil, err } - defer rows.Close() + defer rows.Close() // nolint: errcheck results := make([]types.StateEntryList, len(stateBlockNIDs)) // current is a pointer to the StateEntryList to append the state entries to. @@ -193,7 +193,7 @@ func (s *stateBlockStatements) bulkSelectFilteredStateBlockEntries( if err != nil { return nil, err } - defer rows.Close() + defer rows.Close() // nolint: errcheck var results []types.StateEntryList var current types.StateEntryList diff --git a/src/github.com/matrix-org/dendrite/roomserver/storage/state_snapshot_table.go b/src/github.com/matrix-org/dendrite/roomserver/storage/state_snapshot_table.go index a0dace829..aa14daad7 100644 --- a/src/github.com/matrix-org/dendrite/roomserver/storage/state_snapshot_table.go +++ b/src/github.com/matrix-org/dendrite/roomserver/storage/state_snapshot_table.go @@ -97,7 +97,7 @@ func (s *stateSnapshotStatements) bulkSelectStateBlockNIDs( if err != nil { return nil, err } - defer rows.Close() + defer rows.Close() // nolint: errcheck results := make([]types.StateBlockNIDList, len(stateNIDs)) i := 0 for ; rows.Next(); i++ { diff --git a/src/github.com/matrix-org/dendrite/roomserver/storage/storage.go b/src/github.com/matrix-org/dendrite/roomserver/storage/storage.go index 239837fc8..ad4fed659 100644 --- a/src/github.com/matrix-org/dendrite/roomserver/storage/storage.go +++ b/src/github.com/matrix-org/dendrite/roomserver/storage/storage.go @@ -287,19 +287,19 @@ func (d *Database) GetLatestEventsForUpdate( eventNIDs, lastEventNIDSent, currentStateSnapshotNID, err := d.statements.selectLatestEventsNIDsForUpdate(ctx, txn, roomNID) if err != nil { - txn.Rollback() + txn.Rollback() // nolint: errcheck return nil, err } stateAndRefs, err := d.statements.bulkSelectStateAtEventAndReference(ctx, txn, eventNIDs) if err != nil { - txn.Rollback() + txn.Rollback() // nolint: errcheck return nil, err } var lastEventIDSent string if lastEventNIDSent != 0 { lastEventIDSent, err = d.statements.selectEventID(ctx, txn, lastEventNIDSent) if err != nil { - txn.Rollback() + txn.Rollback() // nolint: errcheck return nil, err } } @@ -459,7 +459,7 @@ func (d *Database) MembershipUpdater( succeeded := false defer func() { if !succeeded { - txn.Rollback() + txn.Rollback() // nolint: errcheck } }() diff --git a/src/github.com/matrix-org/dendrite/syncapi/storage/account_data_table.go b/src/github.com/matrix-org/dendrite/syncapi/storage/account_data_table.go index 72aaf3551..d4d74d158 100644 --- a/src/github.com/matrix-org/dendrite/syncapi/storage/account_data_table.go +++ b/src/github.com/matrix-org/dendrite/syncapi/storage/account_data_table.go @@ -87,7 +87,7 @@ func (s *accountDataStatements) insertAccountData( ctx context.Context, userID, roomID, dataType string, ) (pos int64, err error) { - s.insertAccountDataStmt.QueryRowContext(ctx, userID, roomID, dataType).Scan(&pos) + err = s.insertAccountDataStmt.QueryRowContext(ctx, userID, roomID, dataType).Scan(&pos) return } diff --git a/src/github.com/matrix-org/dendrite/syncapi/storage/current_room_state_table.go b/src/github.com/matrix-org/dendrite/syncapi/storage/current_room_state_table.go index 307af4338..e5430d14d 100644 --- a/src/github.com/matrix-org/dendrite/syncapi/storage/current_room_state_table.go +++ b/src/github.com/matrix-org/dendrite/syncapi/storage/current_room_state_table.go @@ -122,7 +122,7 @@ func (s *currentRoomStateStatements) selectJoinedUsers( if err != nil { return nil, err } - defer rows.Close() + defer rows.Close() // nolint: errcheck result := make(map[string][]string) for rows.Next() { @@ -147,7 +147,7 @@ func (s *currentRoomStateStatements) selectRoomIDsWithMembership( if err != nil { return nil, err } - defer rows.Close() + defer rows.Close() // nolint: errcheck var result []string for rows.Next() { @@ -169,7 +169,7 @@ func (s *currentRoomStateStatements) selectCurrentState( if err != nil { return nil, err } - defer rows.Close() + defer rows.Close() // nolint: errcheck return rowsToEvents(rows) } @@ -208,7 +208,7 @@ func (s *currentRoomStateStatements) selectEventsWithEventIDs( if err != nil { return nil, err } - defer rows.Close() + defer rows.Close() // nolint: errcheck return rowsToStreamEvents(rows) } diff --git a/src/github.com/matrix-org/dendrite/syncapi/storage/output_room_events_table.go b/src/github.com/matrix-org/dendrite/syncapi/storage/output_room_events_table.go index 660a3074d..ac6e3d7f3 100644 --- a/src/github.com/matrix-org/dendrite/syncapi/storage/output_room_events_table.go +++ b/src/github.com/matrix-org/dendrite/syncapi/storage/output_room_events_table.go @@ -213,7 +213,7 @@ func (s *outputRoomEventsStatements) selectRecentEvents( if err != nil { return nil, err } - defer rows.Close() + defer rows.Close() // nolint: errcheck events, err := rowsToStreamEvents(rows) if err != nil { return nil, err @@ -233,7 +233,7 @@ func (s *outputRoomEventsStatements) selectEvents( if err != nil { return nil, err } - defer rows.Close() + defer rows.Close() // nolint: errcheck return rowsToStreamEvents(rows) }