diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 0a64656..6bf908c 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -28,9 +28,9 @@ jobs: - run: (cd ui && yarn) - run: (cd ui && yarn build) - run: (cd ui && yarn testformat) - - uses: golangci/golangci-lint-action@v2 + - uses: golangci/golangci-lint-action@v3 with: - version: v1.50.1 + version: v1.51.1 - run: go build ./... - run: go test -race ./... - if: startsWith(github.ref, 'refs/tags/v') diff --git a/.golangci.yml b/.golangci.yml index 0f54208..fcf2e5f 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,46 +1,35 @@ -inters: +linters: enable: - asciicheck - bodyclose - - deadcode - depguard - dogsled - - dupl - errcheck - exhaustive - exportloopref - - gci - - gocritic - godot - - goerr113 - gofmt - gofumpt - goimports - - golint - gomodguard - goprintffuncname - - gosec - gosimple - govet - ineffassign - - interfacer - misspell - nakedret - nolintlint - - prealloc - - rowserrcheck - - scopelint - sqlclosecheck - staticcheck - - structcheck - stylecheck - typecheck - - unconvert - unparam - unused - - varcheck - whitespace disable: + - dupl + - gocritic + - goerr113 - funlen - gochecknoglobals - gocognit @@ -59,7 +48,5 @@ inters: linters-settings: gofumpt: extra-rules: true - goimports: - local-prefixes: github.com/screego/server misspell: locale: US diff --git a/auth/auth.go b/auth/auth.go index c38664c..c0044fd 100644 --- a/auth/auth.go +++ b/auth/auth.go @@ -8,9 +8,8 @@ import ( "net/http" "os" - "github.com/rs/zerolog/log" - "github.com/gorilla/sessions" + "github.com/rs/zerolog/log" "golang.org/x/crypto/bcrypt" ) @@ -32,7 +31,6 @@ func read(r io.Reader) ([]UserPW, error) { reader.TrimLeadingSpace = true records, err := reader.ReadAll() - if err != nil { return nil, err } @@ -130,7 +128,7 @@ func (u *Users) Authenticate(w http.ResponseWriter, r *http.Request) { }) } -func (u Users) Validate(user string, password string) bool { +func (u Users) Validate(user, password string) bool { realPassword, exists := u.Lookup[user] return exists && bcrypt.CompareHashAndPassword([]byte(realPassword), []byte(password)) == nil } diff --git a/cmd/serve.go b/cmd/serve.go index 2ab36fd..ba133df 100644 --- a/cmd/serve.go +++ b/cmd/serve.go @@ -1,9 +1,7 @@ package cmd import ( - mrand "math/rand" "os" - "time" "github.com/rs/zerolog" "github.com/rs/zerolog/log" @@ -21,8 +19,6 @@ func serveCmd(version string) cli.Command { return cli.Command{ Name: "serve", Action: func(ctx *cli.Context) { - - mrand.Seed(time.Now().Unix()) conf, errs := config.Get() logger.Init(conf.LogLevel.AsZeroLogLevel()) diff --git a/config/config.go b/config/config.go index ead1229..29bf1cf 100644 --- a/config/config.go +++ b/config/config.go @@ -112,14 +112,16 @@ func Get() (Config, []FutureLog) { } else { logs = append(logs, FutureLog{ Level: zerolog.DebugLevel, - Msg: fmt.Sprintf("Loading file %s", file)}) + Msg: fmt.Sprintf("Loading file %s", file), + }) } } else if os.IsNotExist(fileErr) { continue } else { logs = append(logs, FutureLog{ Level: zerolog.WarnLevel, - Msg: fmt.Sprintf("cannot read file %s because %s", file, fileErr)}) + Msg: fmt.Sprintf("cannot read file %s because %s", file, fileErr), + }) } } @@ -171,7 +173,8 @@ func Get() (Config, []FutureLog) { if _, err := rand.Read(config.Secret); err == nil { logs = append(logs, FutureLog{ Level: zerolog.InfoLevel, - Msg: "SCREEGO_SECRET unset, user logins will be invalidated on restart"}) + Msg: "SCREEGO_SECRET unset, user logins will be invalidated on restart", + }) } else { logs = append(logs, futureFatal(fmt.Sprintf("cannot create secret %s", err))) } @@ -212,7 +215,8 @@ func Get() (Config, []FutureLog) { } else if (max - min) < 40 { logs = append(logs, FutureLog{ Level: zerolog.WarnLevel, - Msg: "Less than 40 ports are available for turn. When using multiple TURN connections this may not be enough"}) + Msg: "Less than 40 ports are available for turn. When using multiple TURN connections this may not be enough", + }) } return config, logs @@ -277,7 +281,8 @@ func getExecutableDir() (string, *FutureLog) { if err != nil { return "", &FutureLog{ Level: zerolog.ErrorLevel, - Msg: "Could not get path of executable using working directory instead. " + err.Error()} + Msg: "Could not get path of executable using working directory instead. " + err.Error(), + } } return filepath.Dir(ex), nil } diff --git a/config/mode/mode.go b/config/mode/mode.go index 6a9204d..fb166b2 100644 --- a/config/mode/mode.go +++ b/config/mode/mode.go @@ -1,9 +1,9 @@ package mode const ( - // Dev for development mode + // Dev for development mode. Dev = "dev" - // Prod for production mode + // Prod for production mode. Prod = "prod" ) diff --git a/logger/logger.go b/logger/logger.go index 0674b13..35fa0e7 100644 --- a/logger/logger.go +++ b/logger/logger.go @@ -8,7 +8,7 @@ import ( "github.com/rs/zerolog/log" ) -// Init initializes the logger +// Init initializes the logger. func Init(lvl zerolog.Level) { log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stdout, TimeFormat: time.RFC3339}).Level(lvl) log.Debug().Msg("Logger initialized") diff --git a/router/router.go b/router/router.go index 6ab716f..5b0d875 100644 --- a/router/router.go +++ b/router/router.go @@ -2,13 +2,13 @@ package router import ( "encoding/json" - "github.com/rs/zerolog/hlog" "net/http" "time" "github.com/gorilla/handlers" "github.com/gorilla/mux" "github.com/prometheus/client_golang/prometheus/promhttp" + "github.com/rs/zerolog/hlog" "github.com/rs/zerolog/log" "github.com/screego/server/auth" "github.com/screego/server/config" @@ -68,13 +68,12 @@ func accessLogger(r *http.Request, status, size int, dur time.Duration) { func basicAuth(handler http.Handler, users *auth.Users) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - user, pass, ok := r.BasicAuth() if !ok || !users.Validate(user, pass) { w.Header().Set("WWW-Authenticate", `Basic realm="screego"`) w.WriteHeader(401) - _, _ = w.Write([]byte("Unauthorised.\n")) + _, _ = w.Write([]byte("Unauthorized.\n")) return } diff --git a/server/server.go b/server/server.go index 0e13fb1..af4ce74 100644 --- a/server/server.go +++ b/server/server.go @@ -9,17 +9,18 @@ import ( "strings" "time" - "github.com/rs/zerolog/log" - "github.com/gorilla/mux" + "github.com/rs/zerolog/log" ) -var notifySignal = signal.Notify -var serverShutdown = func(server *http.Server, ctx context.Context) error { - return server.Shutdown(ctx) -} +var ( + notifySignal = signal.Notify + serverShutdown = func(server *http.Server, ctx context.Context) error { + return server.Shutdown(ctx) + } +) -// Start starts the http server +// Start starts the http server. func Start(mux *mux.Router, address, cert, key string) error { server, shutdown := startServer(mux, address, cert, key) shutdownOnInterruptSignal(server, 2*time.Second, shutdown) diff --git a/turn/none.go b/turn/none.go index 0b26a8b..24a2ef9 100644 --- a/turn/none.go +++ b/turn/none.go @@ -6,7 +6,7 @@ import ( "strconv" ) -type RelayAddressGeneratorNone struct {} +type RelayAddressGeneratorNone struct{} func (r *RelayAddressGeneratorNone) Validate() error { return nil diff --git a/turn/server.go b/turn/server.go index 534fc3a..81861e2 100644 --- a/turn/server.go +++ b/turn/server.go @@ -148,12 +148,12 @@ func (a *InternalServer) authenticate(username, realm string, addr net.Addr) ([] a.lock.RLock() defer a.lock.RUnlock() - var connectedIp net.IP + var connectedIP net.IP switch addr := addr.(type) { case *net.UDPAddr: - connectedIp = addr.IP + connectedIP = addr.IP case *net.TCPAddr: - connectedIp = addr.IP + connectedIP = addr.IP default: log.Error().Interface("type", fmt.Sprintf("%T", addr)).Msg("unknown addr type") return nil, false @@ -167,7 +167,7 @@ func (a *InternalServer) authenticate(username, realm string, addr net.Addr) ([] authIP := entry.addr - if a.strictAuth && !connectedIp.Equal(authIP) { + if a.strictAuth && !connectedIP.Equal(authIP) { log.Debug().Interface("allowedIp", addr.String()).Interface("connectingIp", entry.addr.String()).Msg("TURN strict auth check failed") return nil, false } diff --git a/util/sillyname.go b/util/sillyname.go index e22271d..6790f84 100644 --- a/util/sillyname.go +++ b/util/sillyname.go @@ -18,6 +18,7 @@ var adjectives = []string{ "optimistic", "patient", "pioneering", "polite", "powerful", "reliable", "resourceful", "sensible", "sincere", "thoughtful", "tough", "versatile", } + var animals = []string{ "Dog", "Puppy", "Turtle", "Rabbit", "Parrot", "Cat", "Kitten", "Goldfish", "Mouse", "Hamster", "Fish", "Cow", "Rabbit", "Duck", "Shrimp", "Pig", @@ -28,10 +29,10 @@ var animals = []string{ "Coyote", "Hedgehong", "Sheep", "Deer", } -func r(l []string) string { - return l[rand.Intn(len(l)-1)] +func r(r *rand.Rand, l []string) string { + return l[r.Intn(len(l)-1)] } -func NewName() string { - return cases.Title(language.English).String(r(adjectives) + " " + r(animals)) +func NewName(s *rand.Rand) string { + return cases.Title(language.English).String(r(s, adjectives) + " " + r(s, animals)) } diff --git a/ws/client.go b/ws/client.go index 7c275d9..765de92 100644 --- a/ws/client.go +++ b/ws/client.go @@ -2,15 +2,16 @@ package ws import ( "fmt" + "net" + "net/http" + "strings" + "time" + "github.com/gorilla/websocket" "github.com/rs/xid" "github.com/rs/zerolog" "github.com/rs/zerolog/log" "github.com/screego/server/ws/outgoing" - "net" - "net/http" - "strings" - "time" ) var ping = func(conn *websocket.Conn) error { @@ -48,7 +49,6 @@ type ClientInfo struct { } func newClient(conn *websocket.Conn, req *http.Request, read chan ClientMessage, authenticatedUser string, authenticated, trustProxy bool) *Client { - ip := conn.RemoteAddr().(*net.TCPAddr).IP if realIP := req.Header.Get("X-Real-IP"); trustProxy && realIP != "" { ip = net.ParseIP(realIP) @@ -122,7 +122,7 @@ func (c *Client) startReading(pongWait time.Duration) { // startWriteHandler starts the write loop. The method has the following tasks: // * ping the client in the interval provided as parameter // * write messages send by the channel to the client -// * on errors exit the loop +// * on errors exit the loop. func (c *Client) startWriteHandler(pingPeriod time.Duration) { pingTicker := time.NewTicker(pingPeriod) diff --git a/ws/event_clientanswer.go b/ws/event_clientanswer.go index 52b727f..eb4ad55 100644 --- a/ws/event_clientanswer.go +++ b/ws/event_clientanswer.go @@ -2,6 +2,7 @@ package ws import ( "fmt" + "github.com/rs/zerolog/log" "github.com/screego/server/ws/outgoing" ) diff --git a/ws/event_clientice.go b/ws/event_clientice.go index 29a4edd..9701ee9 100644 --- a/ws/event_clientice.go +++ b/ws/event_clientice.go @@ -2,6 +2,7 @@ package ws import ( "fmt" + "github.com/rs/zerolog/log" "github.com/screego/server/ws/outgoing" ) diff --git a/ws/event_create.go b/ws/event_create.go index 45c350d..2a28078 100644 --- a/ws/event_create.go +++ b/ws/event_create.go @@ -6,7 +6,6 @@ import ( "github.com/rs/xid" "github.com/screego/server/config" - "github.com/screego/server/util" ) func init() { @@ -42,7 +41,7 @@ func (e *Create) Execute(rooms *Rooms, current ClientInfo) error { name = current.AuthenticatedUser } if name == "" { - name = util.NewName() + name = rooms.RandUserName() } switch rooms.config.AuthMode { diff --git a/ws/event_disconnected.go b/ws/event_disconnected.go index 89d49e7..f448867 100644 --- a/ws/event_disconnected.go +++ b/ws/event_disconnected.go @@ -2,11 +2,11 @@ package ws import ( "bytes" + "github.com/screego/server/ws/outgoing" ) -type Disconnected struct { -} +type Disconnected struct{} func (e *Disconnected) Execute(rooms *Rooms, current ClientInfo) error { if current.RoomID == "" { diff --git a/ws/event_hostice.go b/ws/event_hostice.go index 67d748b..2b5a84e 100644 --- a/ws/event_hostice.go +++ b/ws/event_hostice.go @@ -2,6 +2,7 @@ package ws import ( "fmt" + "github.com/rs/zerolog/log" "github.com/screego/server/ws/outgoing" ) diff --git a/ws/event_hostoffer.go b/ws/event_hostoffer.go index ad10267..658a5fe 100644 --- a/ws/event_hostoffer.go +++ b/ws/event_hostoffer.go @@ -2,6 +2,7 @@ package ws import ( "fmt" + "github.com/rs/zerolog/log" "github.com/screego/server/ws/outgoing" ) diff --git a/ws/event_join.go b/ws/event_join.go index 17e2403..90bd003 100644 --- a/ws/event_join.go +++ b/ws/event_join.go @@ -2,8 +2,6 @@ package ws import ( "fmt" - - "github.com/screego/server/util" ) func init() { @@ -31,7 +29,7 @@ func (e *Join) Execute(rooms *Rooms, current ClientInfo) error { name = current.AuthenticatedUser } if name == "" { - name = util.NewName() + name = rooms.RandUserName() } room.Users[current.ID] = &User{ diff --git a/ws/event_share.go b/ws/event_share.go index 88067b6..475465a 100644 --- a/ws/event_share.go +++ b/ws/event_share.go @@ -10,8 +10,7 @@ func init() { }) } -type StartShare struct { -} +type StartShare struct{} func (e *StartShare) Execute(rooms *Rooms, current ClientInfo) error { if current.RoomID == "" { diff --git a/ws/event_stop_share.go b/ws/event_stop_share.go index ddf346b..81c809b 100644 --- a/ws/event_stop_share.go +++ b/ws/event_stop_share.go @@ -13,8 +13,7 @@ func init() { }) } -type StopShare struct { -} +type StopShare struct{} func (e *StopShare) Execute(rooms *Rooms, current ClientInfo) error { if current.RoomID == "" { diff --git a/ws/room.go b/ws/room.go index 034be7d..3ca9ff0 100644 --- a/ws/room.go +++ b/ws/room.go @@ -59,7 +59,6 @@ func (r *Room) newSession(host, client xid.ID, rooms *Rooms) { Credential: clientPW, Username: clientName, }} - } r.Users[host].Write <- outgoing.HostSession{Peer: client, ID: id, ICEServers: iceHost} r.Users[client].Write <- outgoing.ClientSession{Peer: host, ID: id, ICEServers: iceClient} diff --git a/ws/rooms.go b/ws/rooms.go index 397949b..1dec306 100644 --- a/ws/rooms.go +++ b/ws/rooms.go @@ -2,6 +2,7 @@ package ws import ( "fmt" + "math/rand" "net/http" "net/url" "time" @@ -11,6 +12,7 @@ import ( "github.com/screego/server/auth" "github.com/screego/server/config" "github.com/screego/server/turn" + "github.com/screego/server/util" ) func NewRooms(tServer turn.Server, users *auth.Users, conf config.Config) *Rooms { @@ -20,6 +22,7 @@ func NewRooms(tServer turn.Server, users *auth.Users, conf config.Config) *Rooms turnServer: tServer, users: users, config: conf, + r: rand.New(rand.NewSource(time.Now().Unix())), upgrader: websocket.Upgrader{ ReadBufferSize: 1024, WriteBufferSize: 1024, @@ -45,11 +48,15 @@ type Rooms struct { upgrader websocket.Upgrader users *auth.Users config config.Config + r *rand.Rand +} + +func (r *Rooms) RandUserName() string { + return util.NewName(r.r) } func (r *Rooms) Upgrade(w http.ResponseWriter, req *http.Request) { conn, err := r.upgrader.Upgrade(w, req, nil) - if err != nil { log.Debug().Err(err).Msg("Websocket upgrade") w.WriteHeader(400) @@ -73,8 +80,8 @@ func (r *Rooms) Start() { } } -func (r *Rooms) closeRoom(roomId string) { - room, ok := r.Rooms[roomId] +func (r *Rooms) closeRoom(roomID string) { + room, ok := r.Rooms[roomID] if !ok { return } @@ -83,6 +90,6 @@ func (r *Rooms) closeRoom(roomId string) { room.closeSession(r, id) } - delete(r.Rooms, roomId) + delete(r.Rooms, roomID) roomsClosedTotal.Inc() }