Browse Source

Fix issues reported by revive.

pull/197/head
Joachim Bauch 4 months ago
parent
commit
614c5f6e21
No known key found for this signature in database
GPG Key ID: 77C1D22D53E15F02
  1. 24
      api_signaling.go
  2. 4
      backend_configuration.go
  3. 8
      backend_server.go
  4. 6
      client.go
  5. 48
      client/main.go
  6. 19
      clientsession.go
  7. 2
      continentmap.go
  8. 4
      deferred_executor_test.go
  9. 11
      geoip.go
  10. 14
      hub_test.go
  11. 2
      janus_client.go
  12. 13
      mcu_janus.go
  13. 2
      pool.go
  14. 8
      room.go
  15. 7
      roomsessions_builtin.go
  16. 2
      scripts/get_continent_map.py
  17. 8
      server/main.go
  18. 81
      testclient_test.go

24
api_signaling.go

@ -332,10 +332,10 @@ const (
)
var (
DefaultFeatures []string = []string{
DefaultFeatures = []string{
ServerFeatureAudioVideoPermissions,
}
DefaultFeaturesInternal []string = []string{
DefaultFeaturesInternal = []string{
ServerFeatureInternalVirtualSessions,
}
)
@ -467,10 +467,7 @@ type ControlClientMessage struct {
}
func (m *ControlClientMessage) CheckValid() error {
if err := m.MessageClientMessage.CheckValid(); err != nil {
return err
}
return nil
return m.MessageClientMessage.CheckValid()
}
type ControlServerMessage struct {
@ -514,10 +511,7 @@ type AddSessionInternalClientMessage struct {
}
func (m *AddSessionInternalClientMessage) CheckValid() error {
if err := m.CommonSessionInternalClientMessage.CheckValid(); err != nil {
return err
}
return nil
return m.CommonSessionInternalClientMessage.CheckValid()
}
type UpdateSessionInternalClientMessage struct {
@ -527,10 +521,7 @@ type UpdateSessionInternalClientMessage struct {
}
func (m *UpdateSessionInternalClientMessage) CheckValid() error {
if err := m.CommonSessionInternalClientMessage.CheckValid(); err != nil {
return err
}
return nil
return m.CommonSessionInternalClientMessage.CheckValid()
}
type RemoveSessionInternalClientMessage struct {
@ -540,10 +531,7 @@ type RemoveSessionInternalClientMessage struct {
}
func (m *RemoveSessionInternalClientMessage) CheckValid() error {
if err := m.CommonSessionInternalClientMessage.CheckValid(); err != nil {
return err
}
return nil
return m.CommonSessionInternalClientMessage.CheckValid()
}
type InternalClientMessage struct {

4
backend_configuration.go

@ -139,7 +139,7 @@ func NewBackendConfiguration(config *goconf.ConfigFile) (*BackendConfiguration,
if sessionLimit > 0 {
log.Printf("Allow a maximum of %d sessions", sessionLimit)
}
numBackends += 1
numBackends++
} else if backendIds, _ := config.GetString("backend", "backends"); backendIds != "" {
for host, configuredBackends := range getConfiguredHosts(backendIds, config) {
backends[host] = append(backends[host], configuredBackends...)
@ -186,7 +186,7 @@ func NewBackendConfiguration(config *goconf.ConfigFile) (*BackendConfiguration,
if sessionLimit > 0 {
log.Printf("Allow a maximum of %d sessions", sessionLimit)
}
numBackends += 1
numBackends++
}
}

8
backend_server.go

@ -143,12 +143,14 @@ func (b *BackendServer) Start(r *mux.Router) error {
"nextcloud-spreed-signaling": "Welcome",
"version": b.version,
}
if welcomeMessage, err := json.Marshal(welcome); err != nil {
welcomeMessage, err := json.Marshal(welcome)
if err != nil {
// Should never happen.
return err
} else {
b.welcomeMessage = string(welcomeMessage) + "\n"
}
b.welcomeMessage = string(welcomeMessage) + "\n"
s := r.PathPrefix("/api/v1").Subrouter()
s.HandleFunc("/welcome", b.setComonHeaders(b.welcomeFunc)).Methods("GET")
s.HandleFunc("/room/{roomid}", b.setComonHeaders(b.parseRequestBody(b.roomHandler))).Methods("POST")

6
client.go

@ -51,11 +51,11 @@ const (
)
var (
noCountry string = "no-country"
noCountry = "no-country"
loopback string = "loopback"
loopback = "loopback"
unknownCountry string = "unknown-country"
unknownCountry = "unknown-country"
)
func init() {

48
client/main.go

@ -119,8 +119,8 @@ type MessagePayload struct {
}
type SignalingClient struct {
ready_wg *sync.WaitGroup
cookie *securecookie.SecureCookie
readyWg *sync.WaitGroup
cookie *securecookie.SecureCookie
conn *websocket.Conn
@ -135,15 +135,15 @@ type SignalingClient struct {
userId string
}
func NewSignalingClient(cookie *securecookie.SecureCookie, url string, stats *Stats, ready_wg *sync.WaitGroup, done_wg *sync.WaitGroup) (*SignalingClient, error) {
func NewSignalingClient(cookie *securecookie.SecureCookie, url string, stats *Stats, readyWg *sync.WaitGroup, doneWg *sync.WaitGroup) (*SignalingClient, error) {
conn, _, err := websocket.DefaultDialer.Dial(url, nil)
if err != nil {
return nil, err
}
client := &SignalingClient{
ready_wg: ready_wg,
cookie: cookie,
readyWg: readyWg,
cookie: cookie,
conn: conn,
@ -151,13 +151,13 @@ func NewSignalingClient(cookie *securecookie.SecureCookie, url string, stats *St
stopChan: make(chan bool),
}
done_wg.Add(2)
doneWg.Add(2)
go func() {
defer done_wg.Done()
defer doneWg.Done()
client.readPump()
}()
go func() {
defer done_wg.Done()
defer doneWg.Done()
client.writePump()
}()
return client, nil
@ -240,7 +240,7 @@ func (c *SignalingClient) processHelloMessage(message *signaling.ServerMessage)
c.publicSessionId = c.privateToPublicSessionId(c.privateSessionId)
c.userId = message.Hello.UserId
log.Printf("Registered as %s (userid %s)", c.privateSessionId, c.userId)
c.ready_wg.Done()
c.readyWg.Done()
}
func (c *SignalingClient) PublicSessionId() string {
@ -381,21 +381,21 @@ func (c *SignalingClient) writePump() {
}
func (c *SignalingClient) SendMessages(clients []*SignalingClient) {
session_ids := make(map[*SignalingClient]string)
sessionIds := make(map[*SignalingClient]string)
for _, c := range clients {
session_ids[c] = c.PublicSessionId()
sessionIds[c] = c.PublicSessionId()
}
for atomic.LoadUint32(&c.closed) == 0 {
now := time.Now()
sender := c
recipient_idx := pseudorand.Int() % len(clients)
recipientIdx := pseudorand.Int() % len(clients)
// Make sure a client is not sending to himself
for clients[recipient_idx] == sender {
recipient_idx = pseudorand.Int() % len(clients)
for clients[recipientIdx] == sender {
recipientIdx = pseudorand.Int() % len(clients)
}
recipient := clients[recipient_idx]
recipient := clients[recipientIdx]
msgdata := MessagePayload{
Now: now,
}
@ -405,7 +405,7 @@ func (c *SignalingClient) SendMessages(clients []*SignalingClient) {
Message: &signaling.MessageClientMessage{
Recipient: signaling.MessageClientMessageRecipient{
Type: "session",
SessionId: session_ids[recipient],
SessionId: sessionIds[recipient],
},
Data: (*json.RawMessage)(&data),
},
@ -589,16 +589,16 @@ func main() {
log.Printf("Starting %d clients", *maxClients)
var done_wg sync.WaitGroup
var ready_wg sync.WaitGroup
var doneWg sync.WaitGroup
var readyWg sync.WaitGroup
for i := 0; i < *maxClients; i++ {
client, err := NewSignalingClient(cookie, urls[i%len(urls)].String(), stats, &ready_wg, &done_wg)
client, err := NewSignalingClient(cookie, urls[i%len(urls)].String(), stats, &readyWg, &doneWg)
if err != nil {
log.Fatal(err)
}
defer client.Close()
ready_wg.Add(1)
readyWg.Add(1)
request := &signaling.ClientMessage{
Type: "hello",
@ -616,14 +616,14 @@ func main() {
}
log.Println("Clients created")
ready_wg.Wait()
readyWg.Wait()
log.Println("All connections established")
for _, c := range clients {
done_wg.Add(1)
doneWg.Add(1)
go func(c *SignalingClient) {
defer done_wg.Done()
defer doneWg.Done()
c.SendMessages(clients)
}(c)
}
@ -646,5 +646,5 @@ loop:
for _, c := range clients {
c.Close()
}
done_wg.Wait()
doneWg.Wait()
}

19
clientsession.go

@ -124,16 +124,17 @@ func NewClientSession(hub *Hub, privateId string, publicId string, data *Session
backendUrl += "/"
}
backendUrl += PathToOcsSignalingBackend
if u, err := url.Parse(backendUrl); err != nil {
u, err := url.Parse(backendUrl)
if err != nil {
return nil, err
} else {
if strings.Contains(u.Host, ":") && hasStandardPort(u) {
u.Host = u.Hostname()
}
}
s.backendUrl = backendUrl
s.parsedBackendUrl = u
if strings.Contains(u.Host, ":") && hasStandardPort(u) {
u.Host = u.Hostname()
}
s.backendUrl = backendUrl
s.parsedBackendUrl = u
}
if err := s.SubscribeNats(hub.nats); err != nil {
@ -405,9 +406,9 @@ func (s *ClientSession) closeAndWait(wait bool) {
func GetSubjectForUserId(userId string, backend *Backend) string {
if backend == nil || backend.IsCompat() {
return GetEncodedSubject("user", userId)
} else {
return GetEncodedSubject("user", userId+"|"+backend.Id())
}
return GetEncodedSubject("user", userId+"|"+backend.Id())
}
func (s *ClientSession) SubscribeNats(n NatsClient) error {

2
continentmap.go

@ -4,7 +4,7 @@ package signaling
// Source: https://datahub.io/core/country-codes/r/country-codes.json
var (
ContinentMap map[string][]string = map[string][]string{
ContinentMap = map[string][]string{
"AD": {"EU"},
"AE": {"AS"},
"AF": {"AS"},

4
deferred_executor_test.go

@ -70,7 +70,7 @@ func TestDeferredExecutor_Order(t *testing.T) {
}
done := make(chan bool)
for x := 0; x < 10; x += 1 {
for x := 0; x < 10; x++ {
e.Execute(getFunc(x))
}
@ -79,7 +79,7 @@ func TestDeferredExecutor_Order(t *testing.T) {
})
<-done
for x := 0; x < 10; x += 1 {
for x := 0; x < 10; x++ {
if entries[x] != x {
t.Errorf("Expected %d at position %d, got %d", x, x, entries[x])
}

11
geoip.go

@ -98,9 +98,9 @@ func (g *GeoLookup) Close() {
func (g *GeoLookup) Update() error {
if g.isFile {
return g.updateFile()
} else {
return g.updateUrl()
}
return g.updateUrl()
}
func (g *GeoLookup) updateFile() error {
@ -233,11 +233,12 @@ func (g *GeoLookup) LookupCountry(ip net.IP) (string, error) {
}
func LookupContinents(country string) []string {
if continents, found := ContinentMap[country]; !found {
continents, found := ContinentMap[country]
if !found {
return nil
} else {
return continents
}
return continents
}
func IsValidContinent(continent string) bool {

14
hub_test.go

@ -2061,7 +2061,7 @@ func TestClientMessageToSessionIdWhileDisconnected(t *testing.T) {
defer cancel2()
if err := checkReceiveClientMessage(ctx2, client2, "session", hello1.Hello, &payload); err != nil {
if err != NoMessageReceivedError {
if err != ErrNoMessageReceived {
t.Error(err)
}
} else {
@ -2194,7 +2194,7 @@ func TestRoomParticipantsListUpdateWhileDisconnected(t *testing.T) {
defer cancel2()
if err := checkReceiveClientMessage(ctx2, client2, "session", hello1.Hello, &payload); err != nil {
if err != NoMessageReceivedError {
if err != ErrNoMessageReceived {
t.Error(err)
}
} else {
@ -2310,7 +2310,7 @@ func TestClientTakeoverRoomSession(t *testing.T) {
ctx2, cancel2 := context.WithTimeout(context.Background(), 200*time.Millisecond)
defer cancel2()
if message, err := client2.RunUntilMessage(ctx2); err != nil && err != NoMessageReceivedError && err != context.DeadlineExceeded {
if message, err := client2.RunUntilMessage(ctx2); err != nil && err != ErrNoMessageReceived && err != context.DeadlineExceeded {
t.Error(err)
} else if message != nil {
t.Errorf("Expected no message, got %+v", message)
@ -3049,7 +3049,7 @@ func TestNoSendBetweenSessionsOnDifferentBackends(t *testing.T) {
ctx2, cancel2 := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel2()
if err := checkReceiveClientMessage(ctx2, client1, "session", hello2.Hello, &payload); err != nil {
if err != NoMessageReceivedError {
if err != ErrNoMessageReceived {
t.Error(err)
}
} else {
@ -3059,7 +3059,7 @@ func TestNoSendBetweenSessionsOnDifferentBackends(t *testing.T) {
ctx3, cancel3 := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel3()
if err := checkReceiveClientMessage(ctx3, client2, "session", hello1.Hello, &payload); err != nil {
if err != NoMessageReceivedError {
if err != ErrNoMessageReceived {
t.Error(err)
}
} else {
@ -3159,7 +3159,7 @@ func TestNoSameRoomOnDifferentBackends(t *testing.T) {
ctx2, cancel2 := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel2()
if err := checkReceiveClientMessage(ctx2, client1, "session", hello2.Hello, &payload); err != nil {
if err != NoMessageReceivedError {
if err != ErrNoMessageReceived {
t.Error(err)
}
} else {
@ -3169,7 +3169,7 @@ func TestNoSameRoomOnDifferentBackends(t *testing.T) {
ctx3, cancel3 := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel3()
if err := checkReceiveClientMessage(ctx3, client2, "session", hello1.Hello, &payload); err != nil {
if err != NoMessageReceivedError {
if err != ErrNoMessageReceived {
t.Error(err)
}
} else {

2
janus_client.go

@ -454,6 +454,7 @@ func (gateway *JanusGateway) recv() {
if base.Handle == 0 {
// Nope. No idea what's going on...
// Error()
log.Printf("Received event without handle, ignoring: %s", decodeBuffer.String())
} else {
// Lookup Session
gateway.Lock()
@ -489,6 +490,7 @@ func (gateway *JanusGateway) recv() {
gateway.Unlock()
if transaction == nil {
// Error()
log.Printf("Received event for unknown transaction, ignoring: %s", decodeBuffer.String())
continue
}

13
mcu_janus.go

@ -291,18 +291,17 @@ func (m *mcuJanus) Start() error {
}
log.Printf("Connected to %s %s by %s", info.Name, info.VersionString, info.Author)
if plugin, found := info.Plugins[pluginVideoRoom]; !found {
plugin, found := info.Plugins[pluginVideoRoom]
if !found {
return fmt.Errorf("Plugin %s is not supported", pluginVideoRoom)
} else {
log.Printf("Found %s %s by %s", plugin.Name, plugin.VersionString, plugin.Author)
}
log.Printf("Found %s %s by %s", plugin.Name, plugin.VersionString, plugin.Author)
if !info.DataChannels {
return fmt.Errorf("Data channels are not supported")
} else {
log.Println("Data channels are supported")
}
log.Println("Data channels are supported")
if !info.FullTrickle {
log.Println("WARNING: Full-Trickle is NOT enabled in Janus!")
} else {
@ -709,9 +708,9 @@ func (m *mcuJanus) SubscriberDisconnected(id string, publisher string, streamTyp
func min(a, b int) int {
if a <= b {
return a
} else {
return b
}
return b
}
func (m *mcuJanus) getOrCreatePublisherHandle(ctx context.Context, id string, streamType string, bitrate int) (*JanusHandle, uint64, uint64, error) {

2
pool.go

@ -42,7 +42,7 @@ func NewHttpClientPool(constructor func() *http.Client, size int) (*HttpClientPo
for size > 0 {
c := constructor()
p.pool <- c
size -= 1
size--
}
return p, nil
}

8
room.go

@ -84,17 +84,17 @@ type Room struct {
func GetSubjectForRoomId(roomId string, backend *Backend) string {
if backend == nil || backend.IsCompat() {
return GetEncodedSubject("room", roomId)
} else {
return GetEncodedSubject("room", roomId+"|"+backend.Id())
}
return GetEncodedSubject("room", roomId+"|"+backend.Id())
}
func GetSubjectForBackendRoomId(roomId string, backend *Backend) string {
if backend == nil || backend.IsCompat() {
return GetEncodedSubject("backend.room", roomId)
} else {
return GetEncodedSubject("backend.room", roomId+"|"+backend.Id())
}
return GetEncodedSubject("backend.room", roomId+"|"+backend.Id())
}
func getRoomIdForBackend(id string, backend *Backend) string {

7
roomsessions_builtin.go

@ -69,9 +69,10 @@ func (r *BuiltinRoomSessions) DeleteRoomSession(session Session) {
func (r *BuiltinRoomSessions) GetSessionId(roomSessionId string) (string, error) {
r.mu.Lock()
defer r.mu.Unlock()
if sid, found := r.roomSessionToSessionid[roomSessionId]; !found {
sid, found := r.roomSessionToSessionid[roomSessionId]
if !found {
return "", ErrNoSuchRoomSession
} else {
return sid, nil
}
return sid, nil
}

2
scripts/get_continent_map.py

@ -72,7 +72,7 @@ def generate_map(filename):
out.write('// Source: %s\n' % (URL))
out.write('\n')
out.write('var (\n')
out.write('\tContinentMap map[string][]string = map[string][]string{\n')
out.write('\tContinentMap = map[string][]string{\n')
for country, continents in sorted(continents.items()):
value = []
for continent in continents:

8
server/main.go

@ -68,9 +68,9 @@ func createListener(addr string) (net.Listener, error) {
if addr[0] == '/' {
os.Remove(addr)
return net.Listen("unix", addr)
} else {
return net.Listen("tcp", addr)
}
return net.Listen("tcp", addr)
}
func createTLSListener(addr string, certFile, keyFile string) (net.Listener, error) {
@ -84,9 +84,9 @@ func createTLSListener(addr string, certFile, keyFile string) (net.Listener, err
if addr[0] == '/' {
os.Remove(addr)
return tls.Listen("unix", addr, &config)
} else {
return tls.Listen("tcp", addr, &config)
}
return tls.Listen("tcp", addr, &config)
}
func main() {

81
testclient_test.go

@ -41,7 +41,7 @@ var (
testBackendSecret = []byte("secret")
testInternalSecret = []byte("internal-secret")
NoMessageReceivedError = fmt.Errorf("No message was received by the server.")
ErrNoMessageReceived = fmt.Errorf("no message was received by the server")
)
type TestBackendClientAuthParams struct {
@ -87,7 +87,7 @@ func toJsonString(o interface{}) string {
func checkMessageType(message *ServerMessage, expectedType string) error {
if message == nil {
return NoMessageReceivedError
return ErrNoMessageReceived
}
if message.Type != expectedType {
@ -546,39 +546,40 @@ func (c *TestClient) checkSingleMessageJoined(message *ServerMessage) error {
func (c *TestClient) checkMessageJoinedSession(message *ServerMessage, sessionId string, userId string) error {
if err := c.checkSingleMessageJoined(message); err != nil {
return err
} else {
evt := message.Event.Join[0]
if sessionId != "" && evt.SessionId != sessionId {
return fmt.Errorf("Expected join session id %+v, got %+v",
getPubliceSessionIdData(c.hub, sessionId), getPubliceSessionIdData(c.hub, evt.SessionId))
}
if evt.UserId != userId {
return fmt.Errorf("Expected join user id %s, got %+v", userId, evt)
}
}
evt := message.Event.Join[0]
if sessionId != "" && evt.SessionId != sessionId {
return fmt.Errorf("Expected join session id %+v, got %+v",
getPubliceSessionIdData(c.hub, sessionId), getPubliceSessionIdData(c.hub, evt.SessionId))
}
if evt.UserId != userId {
return fmt.Errorf("Expected join user id %s, got %+v", userId, evt)
}
return nil
}
func (c *TestClient) RunUntilJoined(ctx context.Context, hello ...*HelloServerMessage) error {
for len(hello) > 0 {
if message, err := c.RunUntilMessage(ctx); err != nil {
message, err := c.RunUntilMessage(ctx)
if err != nil {
return err
} else {
if err := c.checkSingleMessageJoined(message); err != nil {
return err
}
found := false
for idx, h := range hello {
if err := c.checkMessageJoined(message, h); err == nil {
hello = append(hello[:idx], hello[idx+1:]...)
found = true
break
}
}
if !found {
return fmt.Errorf("expected one of the passed hello sessions, got %+v", message.Event.Join[0])
}
if err := c.checkSingleMessageJoined(message); err != nil {
return err
}
found := false
for idx, h := range hello {
if err := c.checkMessageJoined(message, h); err == nil {
hello = append(hello[:idx], hello[idx+1:]...)
found = true
break
}
}
if !found {
return fmt.Errorf("expected one of the passed hello sessions, got %+v", message.Event.Join[0])
}
}
return nil
}
@ -604,11 +605,12 @@ func (c *TestClient) checkMessageRoomLeaveSession(message *ServerMessage, sessio
}
func (c *TestClient) RunUntilLeft(ctx context.Context, hello *HelloServerMessage) error {
if message, err := c.RunUntilMessage(ctx); err != nil {
message, err := c.RunUntilMessage(ctx)
if err != nil {
return err
} else {
return c.checkMessageRoomLeave(message, hello)
}
return c.checkMessageRoomLeave(message, hello)
}
func checkMessageRoomlistUpdate(message *ServerMessage) (*RoomEventServerMessage, error) {
@ -624,11 +626,12 @@ func checkMessageRoomlistUpdate(message *ServerMessage) (*RoomEventServerMessage
}
func (c *TestClient) RunUntilRoomlistUpdate(ctx context.Context) (*RoomEventServerMessage, error) {
if message, err := c.RunUntilMessage(ctx); err != nil {
message, err := c.RunUntilMessage(ctx)
if err != nil {
return nil, err
} else {
return checkMessageRoomlistUpdate(message)
}
return checkMessageRoomlistUpdate(message)
}
func checkMessageRoomlistDisinvite(message *ServerMessage) (*RoomDisinviteEventServerMessage, error) {
@ -644,11 +647,12 @@ func checkMessageRoomlistDisinvite(message *ServerMessage) (*RoomDisinviteEventS
}
func (c *TestClient) RunUntilRoomlistDisinvite(ctx context.Context) (*RoomDisinviteEventServerMessage, error) {
if message, err := c.RunUntilMessage(ctx); err != nil {
message, err := c.RunUntilMessage(ctx)
if err != nil {
return nil, err
} else {
return checkMessageRoomlistDisinvite(message)
}
return checkMessageRoomlistDisinvite(message)
}
func checkMessageParticipantsInCall(message *ServerMessage) (*RoomEventServerMessage, error) {
@ -688,11 +692,12 @@ func checkMessageRoomMessage(message *ServerMessage) (*RoomEventMessage, error)
}
func (c *TestClient) RunUntilRoomMessage(ctx context.Context) (*RoomEventMessage, error) {
if message, err := c.RunUntilMessage(ctx); err != nil {
message, err := c.RunUntilMessage(ctx)
if err != nil {
return nil, err
} else {
return checkMessageRoomMessage(message)
}
return checkMessageRoomMessage(message)
}
func checkMessageError(message *ServerMessage, msgid string) error {

Loading…
Cancel
Save