lint: actually lint all go files

This commit is contained in:
Jimmy Zelinskie 2022-01-15 23:28:52 -05:00
parent 7166c1da17
commit 301dd22f15
21 changed files with 59 additions and 44 deletions

View file

@ -6,6 +6,9 @@ output:
linters-settings: linters-settings:
goimports: goimports:
local-prefixes: "github.com/chihaya/chihaya" local-prefixes: "github.com/chihaya/chihaya"
gosec:
excludes:
- "G404" # Allow the usage of math/rand
linters: linters:
enable: enable:
- "bidichk" - "bidichk"
@ -26,7 +29,6 @@ linters:
- "makezero" - "makezero"
- "prealloc" - "prealloc"
- "predeclared" - "predeclared"
- "promlinter"
- "revive" - "revive"
- "rowserrcheck" - "rowserrcheck"
- "staticcheck" - "staticcheck"

View file

@ -100,7 +100,7 @@ func (r *Run) Start(ps storage.PeerStore) error {
} }
func combineErrors(prefix string, errs []error) error { func combineErrors(prefix string, errs []error) error {
var errStrs []string errStrs := make([]string, 0, len(errs))
for _, err := range errs { for _, err := range errs {
errStrs = append(errStrs, err.Error()) errStrs = append(errStrs, err.Error())
} }

View file

@ -66,7 +66,7 @@ func marshal(w io.Writer, data interface{}) (err error) {
err = marshalInt(w, int64(v)) err = marshalInt(w, int64(v))
case int64: case int64:
err = marshalInt(w, int64(v)) err = marshalInt(w, v)
case uint: case uint:
err = marshalUint(w, uint64(v)) err = marshalUint(w, uint64(v))
@ -78,7 +78,7 @@ func marshal(w io.Writer, data interface{}) (err error) {
err = marshalUint(w, uint64(v)) err = marshalUint(w, uint64(v))
case uint64: case uint64:
err = marshalUint(w, uint64(v)) err = marshalUint(w, v)
case time.Duration: // Assume seconds case time.Duration: // Assume seconds
err = marshalInt(w, int64(v/time.Second)) err = marshalInt(w, int64(v/time.Second))

View file

@ -164,6 +164,7 @@ func NewFrontend(logic frontend.TrackerLogic, provided Config) (*Frontend, error
if cfg.TLSCertPath != "" && cfg.TLSKeyPath != "" { if cfg.TLSCertPath != "" && cfg.TLSKeyPath != "" {
var err error var err error
f.tlsCfg = &tls.Config{ f.tlsCfg = &tls.Config{
MinVersion: tls.VersionTLS12,
Certificates: make([]tls.Certificate, 1), Certificates: make([]tls.Certificate, 1),
} }
f.tlsCfg.Certificates[0], err = tls.LoadX509KeyPair(cfg.TLSCertPath, cfg.TLSKeyPath) f.tlsCfg.Certificates[0], err = tls.LoadX509KeyPair(cfg.TLSCertPath, cfg.TLSKeyPath)
@ -265,7 +266,7 @@ func (f *Frontend) serveHTTP(l net.Listener) error {
f.srv.SetKeepAlivesEnabled(f.EnableKeepAlive) f.srv.SetKeepAlivesEnabled(f.EnableKeepAlive)
// Start the HTTP server. // Start the HTTP server.
if err := f.srv.Serve(l); err != http.ErrServerClosed { if err := f.srv.Serve(l); !errors.Is(err, http.ErrServerClosed) {
return err return err
} }
return nil return nil
@ -285,7 +286,7 @@ func (f *Frontend) serveHTTPS(l net.Listener) error {
f.tlsSrv.SetKeepAlivesEnabled(f.EnableKeepAlive) f.tlsSrv.SetKeepAlivesEnabled(f.EnableKeepAlive)
// Start the HTTP server. // Start the HTTP server.
if err := f.tlsSrv.ServeTLS(l, "", ""); err != http.ErrServerClosed { if err := f.tlsSrv.ServeTLS(l, "", ""); !errors.Is(err, http.ErrServerClosed) {
return err return err
} }
return nil return nil

View file

@ -1,6 +1,7 @@
package http package http
import ( import (
"errors"
"net" "net"
"net/http" "net/http"
@ -92,7 +93,7 @@ func ParseAnnounce(r *http.Request, opts ParseOptions) (*bittorrent.AnnounceRequ
// Determine the number of peers the client wants in the response. // Determine the number of peers the client wants in the response.
numwant, err := qp.Uint64("numwant", 32) numwant, err := qp.Uint64("numwant", 32)
if err != nil && err != bittorrent.ErrKeyNotFound { if err != nil && !errors.Is(err, bittorrent.ErrKeyNotFound) {
return nil, bittorrent.ClientError("failed to parse parameter: numwant") return nil, bittorrent.ClientError("failed to parse parameter: numwant")
} }
// If there were no errors, the user actually provided the numwant. // If there were no errors, the user actually provided the numwant.

View file

@ -1,6 +1,7 @@
package http package http
import ( import (
"errors"
"time" "time"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
@ -26,8 +27,9 @@ var promResponseDurationMilliseconds = prometheus.NewHistogramVec(
func recordResponseDuration(action string, af *bittorrent.AddressFamily, err error, duration time.Duration) { func recordResponseDuration(action string, af *bittorrent.AddressFamily, err error, duration time.Duration) {
var errString string var errString string
if err != nil { if err != nil {
if _, ok := err.(bittorrent.ClientError); ok { var clientErr bittorrent.ClientError
errString = err.Error() if errors.As(err, &clientErr) {
errString = clientErr.Error()
} else { } else {
errString = "internal error" errString = "internal error"
} }

View file

@ -1,6 +1,7 @@
package http package http
import ( import (
"errors"
"net/http" "net/http"
"github.com/chihaya/chihaya/bittorrent" "github.com/chihaya/chihaya/bittorrent"
@ -11,8 +12,9 @@ import (
// WriteError communicates an error to a BitTorrent client over HTTP. // WriteError communicates an error to a BitTorrent client over HTTP.
func WriteError(w http.ResponseWriter, err error) error { func WriteError(w http.ResponseWriter, err error) error {
message := "internal server error" message := "internal server error"
if _, clientErr := err.(bittorrent.ClientError); clientErr { var clientErr bittorrent.ClientError
message = err.Error() if errors.As(err, &clientErr) {
message = clientErr.Error()
} else { } else {
log.Error("http: internal error", log.Err(err)) log.Error("http: internal error", log.Err(err))
} }
@ -57,7 +59,7 @@ func WriteAnnounceResponse(w http.ResponseWriter, resp *bittorrent.AnnounceRespo
} }
// Add the peers to the dictionary. // Add the peers to the dictionary.
var peers []bencode.Dict peers := make([]bencode.Dict, 0, len(resp.IPv4Peers)+len(resp.IPv6Peers))
for _, peer := range resp.IPv4Peers { for _, peer := range resp.IPv4Peers {
peers = append(peers, dict(peer)) peers = append(peers, dict(peer))
} }

View file

@ -6,6 +6,7 @@ import (
"bytes" "bytes"
"context" "context"
"encoding/binary" "encoding/binary"
"errors"
"fmt" "fmt"
"math/rand" "math/rand"
"net" "net"
@ -123,8 +124,7 @@ func NewFrontend(logic frontend.TrackerLogic, provided Config) (*Frontend, error
}, },
} }
err := f.listen() if err := f.listen(); err != nil {
if err != nil {
return nil, err return nil, err
} }
@ -188,7 +188,8 @@ func (t *Frontend) serve() error {
n, addr, err := t.socket.ReadFromUDP(*buffer) n, addr, err := t.socket.ReadFromUDP(*buffer)
if err != nil { if err != nil {
pool.Put(buffer) pool.Put(buffer)
if netErr, ok := err.(net.Error); ok && netErr.Temporary() { var netErr net.Error
if errors.As(err, &netErr); netErr.Temporary() {
// A temporary failure is not fatal; just pretend it never happened. // A temporary failure is not fatal; just pretend it never happened.
continue continue
} }

View file

@ -115,7 +115,7 @@ func ParseAnnounce(r Request, v6Action bool, opts ParseOptions) (*bittorrent.Ann
request := &bittorrent.AnnounceRequest{ request := &bittorrent.AnnounceRequest{
Event: eventIDs[eventID], Event: eventIDs[eventID],
InfoHash: bittorrent.InfoHashFromBytes(infohash), InfoHash: bittorrent.InfoHashFromBytes(infohash),
NumWant: uint32(numWant), NumWant: numWant,
Left: left, Left: left,
Downloaded: downloaded, Downloaded: downloaded,
Uploaded: uploaded, Uploaded: uploaded,

View file

@ -1,6 +1,7 @@
package udp package udp
import ( import (
"errors"
"fmt" "fmt"
"testing" "testing"
) )
@ -51,7 +52,7 @@ func TestHandleOptionalParameters(t *testing.T) {
for _, tt := range table { for _, tt := range table {
t.Run(fmt.Sprintf("%#v as %#v", tt.data, tt.values), func(t *testing.T) { t.Run(fmt.Sprintf("%#v as %#v", tt.data, tt.values), func(t *testing.T) {
params, err := handleOptionalParameters(tt.data) params, err := handleOptionalParameters(tt.data)
if err != tt.err { if !errors.Is(err, tt.err) {
if tt.err == nil { if tt.err == nil {
t.Fatalf("expected no parsing error for %x but got %s", tt.data, err) t.Fatalf("expected no parsing error for %x but got %s", tt.data, err)
} else { } else {

View file

@ -1,6 +1,7 @@
package udp package udp
import ( import (
"errors"
"time" "time"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
@ -26,8 +27,9 @@ var promResponseDurationMilliseconds = prometheus.NewHistogramVec(
func recordResponseDuration(action string, af *bittorrent.AddressFamily, err error, duration time.Duration) { func recordResponseDuration(action string, af *bittorrent.AddressFamily, err error, duration time.Duration) {
var errString string var errString string
if err != nil { if err != nil {
if _, ok := err.(bittorrent.ClientError); ok { var clientErr bittorrent.ClientError
errString = err.Error() if errors.As(err, &clientErr) {
errString = clientErr.Error()
} else { } else {
errString = "internal error" errString = "internal error"
} }

View file

@ -2,6 +2,7 @@ package udp
import ( import (
"encoding/binary" "encoding/binary"
"errors"
"fmt" "fmt"
"io" "io"
"time" "time"
@ -12,8 +13,9 @@ import (
// WriteError writes the failure reason as a null-terminated string. // WriteError writes the failure reason as a null-terminated string.
func WriteError(w io.Writer, txID []byte, err error) { func WriteError(w io.Writer, txID []byte, err error) {
// If the client wasn't at fault, acknowledge it. // If the client wasn't at fault, acknowledge it.
if _, ok := err.(bittorrent.ClientError); !ok { var clientErr bittorrent.ClientError
err = fmt.Errorf("internal error occurred: %s", err.Error()) if !errors.As(err, &clientErr) {
err = fmt.Errorf("internal error occurred: %w", err)
} }
buf := newBuffer() buf := newBuffer()

View file

@ -28,7 +28,7 @@ func (d driver) NewHook(optionBytes []byte) (middleware.Hook, error) {
var cfg Config var cfg Config
err := yaml.Unmarshal(optionBytes, &cfg) err := yaml.Unmarshal(optionBytes, &cfg)
if err != nil { if err != nil {
return nil, fmt.Errorf("invalid options for middleware %s: %s", Name, err) return nil, fmt.Errorf("invalid options for middleware %s: %w", Name, err)
} }
return NewHook(cfg) return NewHook(cfg)

View file

@ -2,6 +2,7 @@ package middleware
import ( import (
"context" "context"
"errors"
"github.com/chihaya/chihaya/bittorrent" "github.com/chihaya/chihaya/bittorrent"
"github.com/chihaya/chihaya/storage" "github.com/chihaya/chihaya/storage"
@ -37,12 +38,12 @@ func (h *swarmInteractionHook) HandleAnnounce(ctx context.Context, req *bittorre
switch { switch {
case req.Event == bittorrent.Stopped: case req.Event == bittorrent.Stopped:
err = h.store.DeleteSeeder(req.InfoHash, req.Peer) err = h.store.DeleteSeeder(req.InfoHash, req.Peer)
if err != nil && err != storage.ErrResourceDoesNotExist { if err != nil && !errors.Is(err, storage.ErrResourceDoesNotExist) {
return ctx, err return ctx, err
} }
err = h.store.DeleteLeecher(req.InfoHash, req.Peer) err = h.store.DeleteLeecher(req.InfoHash, req.Peer)
if err != nil && err != storage.ErrResourceDoesNotExist { if err != nil && !errors.Is(err, storage.ErrResourceDoesNotExist) {
return ctx, err return ctx, err
} }
case req.Event == bittorrent.Completed: case req.Event == bittorrent.Completed:
@ -106,7 +107,7 @@ func (h *responseHook) HandleAnnounce(ctx context.Context, req *bittorrent.Annou
func (h *responseHook) appendPeers(req *bittorrent.AnnounceRequest, resp *bittorrent.AnnounceResponse) error { func (h *responseHook) appendPeers(req *bittorrent.AnnounceRequest, resp *bittorrent.AnnounceResponse) error {
seeding := req.Left == 0 seeding := req.Left == 0
peers, err := h.store.AnnouncePeers(req.InfoHash, seeding, int(req.NumWant), req.Peer) peers, err := h.store.AnnouncePeers(req.InfoHash, seeding, int(req.NumWant), req.Peer)
if err != nil && err != storage.ErrResourceDoesNotExist { if err != nil && !errors.Is(err, storage.ErrResourceDoesNotExist) {
return err return err
} }

View file

@ -44,7 +44,7 @@ func (d driver) NewHook(optionBytes []byte) (middleware.Hook, error) {
var cfg Config var cfg Config
err := yaml.Unmarshal(optionBytes, &cfg) err := yaml.Unmarshal(optionBytes, &cfg)
if err != nil { if err != nil {
return nil, fmt.Errorf("invalid options for middleware %s: %s", Name, err) return nil, fmt.Errorf("invalid options for middleware %s: %w", Name, err)
} }
return NewHook(cfg) return NewHook(cfg)
@ -93,8 +93,7 @@ func NewHook(cfg Config) (middleware.Hook, error) {
} }
log.Debug("performing initial fetch of JWKs") log.Debug("performing initial fetch of JWKs")
err := h.updateKeys() if err := h.updateKeys(); err != nil {
if err != nil {
return nil, errors.New("failed to fetch initial JWK Set: " + err.Error()) return nil, errors.New("failed to fetch initial JWK Set: " + err.Error())
} }

View file

@ -11,7 +11,7 @@ import (
// //
// Calling DeriveEntropyFromRequest multiple times yields the same values. // Calling DeriveEntropyFromRequest multiple times yields the same values.
func DeriveEntropyFromRequest(req *bittorrent.AnnounceRequest) (uint64, uint64) { func DeriveEntropyFromRequest(req *bittorrent.AnnounceRequest) (uint64, uint64) {
v0 := binary.BigEndian.Uint64([]byte(req.InfoHash[:8])) + binary.BigEndian.Uint64([]byte(req.InfoHash[8:16])) v0 := binary.BigEndian.Uint64(req.InfoHash[:8]) + binary.BigEndian.Uint64(req.InfoHash[8:16])
v1 := binary.BigEndian.Uint64([]byte(req.Peer.ID[:8])) + binary.BigEndian.Uint64([]byte(req.Peer.ID[8:16])) v1 := binary.BigEndian.Uint64(req.Peer.ID[:8]) + binary.BigEndian.Uint64(req.Peer.ID[8:16])
return v0, v1 return v0, v1
} }

View file

@ -28,7 +28,7 @@ func (d driver) NewHook(optionBytes []byte) (middleware.Hook, error) {
var cfg Config var cfg Config
err := yaml.Unmarshal(optionBytes, &cfg) err := yaml.Unmarshal(optionBytes, &cfg)
if err != nil { if err != nil {
return nil, fmt.Errorf("invalid options for middleware %s: %s", Name, err) return nil, fmt.Errorf("invalid options for middleware %s: %w", Name, err)
} }
return NewHook(cfg) return NewHook(cfg)

View file

@ -29,7 +29,7 @@ func (d driver) NewHook(optionBytes []byte) (middleware.Hook, error) {
var cfg Config var cfg Config
err := yaml.Unmarshal(optionBytes, &cfg) err := yaml.Unmarshal(optionBytes, &cfg)
if err != nil { if err != nil {
return nil, fmt.Errorf("invalid options for middleware %s: %s", Name, err) return nil, fmt.Errorf("invalid options for middleware %s: %w", Name, err)
} }
return NewHook(cfg) return NewHook(cfg)
@ -77,8 +77,7 @@ type hook struct {
// NewHook creates a middleware to randomly modify the announce interval from // NewHook creates a middleware to randomly modify the announce interval from
// the given config. // the given config.
func NewHook(cfg Config) (middleware.Hook, error) { func NewHook(cfg Config) (middleware.Hook, error) {
err := checkConfig(cfg) if err := checkConfig(cfg); err != nil {
if err != nil {
return nil, err return nil, err
} }
@ -96,12 +95,12 @@ func (h *hook) HandleAnnounce(ctx context.Context, req *bittorrent.AnnounceReque
if h.cfg.ModifyResponseProbability == 1 || p < h.cfg.ModifyResponseProbability { if h.cfg.ModifyResponseProbability == 1 || p < h.cfg.ModifyResponseProbability {
// Generate the increase delta. // Generate the increase delta.
v, _, _ = random.Intn(s0, s1, h.cfg.MaxIncreaseDelta) v, _, _ = random.Intn(s0, s1, h.cfg.MaxIncreaseDelta)
addSeconds := time.Duration(v+1) * time.Second deltaDuration := time.Duration(v+1) * time.Second
resp.Interval += addSeconds resp.Interval += deltaDuration
if h.cfg.ModifyMinInterval { if h.cfg.ModifyMinInterval {
resp.MinInterval += addSeconds resp.MinInterval += deltaDuration
} }
return ctx, nil return ctx, nil

View file

@ -4,6 +4,7 @@ package metrics
import ( import (
"context" "context"
"errors"
"net/http" "net/http"
"net/http/pprof" "net/http/pprof"
@ -49,7 +50,7 @@ func NewServer(addr string) *Server {
} }
go func() { go func() {
if err := s.srv.ListenAndServe(); err != http.ErrServerClosed { if err := s.srv.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
log.Fatal("failed while serving prometheus", log.Err(err)) log.Fatal("failed while serving prometheus", log.Err(err))
} }
}() }()

View file

@ -25,6 +25,7 @@ package redis
import ( import (
"encoding/binary" "encoding/binary"
"errors"
"net" "net"
"strconv" "strconv"
"sync" "sync"
@ -301,7 +302,7 @@ func (ps *peerStore) populateProm() {
defer conn.Close() defer conn.Close()
for _, group := range ps.groups() { for _, group := range ps.groups() {
if n, err := redis.Int64(conn.Do("GET", ps.infohashCountKey(group))); err != nil && err != redis.ErrNil { if n, err := redis.Int64(conn.Do("GET", ps.infohashCountKey(group))); err != nil && !errors.Is(err, redis.ErrNil) {
log.Error("storage: GET counter failure", log.Fields{ log.Error("storage: GET counter failure", log.Fields{
"key": ps.infohashCountKey(group), "key": ps.infohashCountKey(group),
"error": err, "error": err,
@ -309,7 +310,7 @@ func (ps *peerStore) populateProm() {
} else { } else {
numInfohashes += n numInfohashes += n
} }
if n, err := redis.Int64(conn.Do("GET", ps.seederCountKey(group))); err != nil && err != redis.ErrNil { if n, err := redis.Int64(conn.Do("GET", ps.seederCountKey(group))); err != nil && !errors.Is(err, redis.ErrNil) {
log.Error("storage: GET counter failure", log.Fields{ log.Error("storage: GET counter failure", log.Fields{
"key": ps.seederCountKey(group), "key": ps.seederCountKey(group),
"error": err, "error": err,
@ -317,7 +318,7 @@ func (ps *peerStore) populateProm() {
} else { } else {
numSeeders += n numSeeders += n
} }
if n, err := redis.Int64(conn.Do("GET", ps.leecherCountKey(group))); err != nil && err != redis.ErrNil { if n, err := redis.Int64(conn.Do("GET", ps.leecherCountKey(group))); err != nil && !errors.Is(err, redis.ErrNil) {
log.Error("storage: GET counter failure", log.Fields{ log.Error("storage: GET counter failure", log.Fields{
"key": ps.leecherCountKey(group), "key": ps.leecherCountKey(group),
"error": err, "error": err,
@ -789,7 +790,7 @@ func (ps *peerStore) collectGarbage(cutoff time.Time) error {
_ = conn.Send("DECR", ps.infohashCountKey(group)) _ = conn.Send("DECR", ps.infohashCountKey(group))
} }
_, err = redis.Values(conn.Do("EXEC")) _, err = redis.Values(conn.Do("EXEC"))
if err != nil && err != redis.ErrNil { if err != nil && !errors.Is(err, redis.ErrNil) {
log.Error("storage: Redis EXEC failure", log.Fields{ log.Error("storage: Redis EXEC failure", log.Fields{
"group": group, "group": group,
"infohash": ihStr, "infohash": ihStr,
@ -797,7 +798,7 @@ func (ps *peerStore) collectGarbage(cutoff time.Time) error {
}) })
} }
} else { } else {
if _, err = conn.Do("UNWATCH"); err != nil && err != redis.ErrNil { if _, err = conn.Do("UNWATCH"); err != nil && !errors.Is(err, redis.ErrNil) {
log.Error("storage: Redis UNWATCH failure", log.Fields{"error": err}) log.Error("storage: Redis UNWATCH failure", log.Fields{"error": err})
} }
} }

View file

@ -69,7 +69,7 @@ func (rc *redisConnector) NewPool() *redis.Pool {
}, },
// PINGs connections that have been idle more than 10 seconds // PINGs connections that have been idle more than 10 seconds
TestOnBorrow: func(c redis.Conn, t time.Time) error { TestOnBorrow: func(c redis.Conn, t time.Time) error {
if time.Since(t) < time.Duration(10*time.Second) { if time.Since(t) < 10*time.Second {
return nil return nil
} }
_, err := c.Do("PING") _, err := c.Do("PING")