Fix various issues found by golangci-lint.

This commit is contained in:
Joachim Bauch 2021-04-26 17:19:39 +02:00
parent e849dc8cbd
commit c8e4bfe007
No known key found for this signature in database
GPG Key ID: 77C1D22D53E15F02
32 changed files with 556 additions and 501 deletions

View File

@ -49,8 +49,8 @@ func newRandomString(length int) string {
func CalculateBackendChecksum(random string, body []byte, secret []byte) string {
mac := hmac.New(sha256.New, secret)
mac.Write([]byte(random))
mac.Write(body)
mac.Write([]byte(random)) // nolint
mac.Write(body) // nolint
return hex.EncodeToString(mac.Sum(nil))
}

View File

@ -109,12 +109,13 @@ type ProxyServerMessage struct {
}
func (r *ProxyServerMessage) CloseAfterSend(session Session) bool {
if r.Type == "bye" {
switch r.Type {
case "bye":
return true
}
default:
return false
}
}
// Type "hello"

View File

@ -39,7 +39,7 @@ import (
)
var (
ErrUseLastResponse = fmt.Errorf("Use last response")
ErrUseLastResponse = fmt.Errorf("use last response")
)
type BackendClient struct {
@ -236,7 +236,7 @@ func performRequestWithRedirects(ctx context.Context, client *http.Client, req *
// fails, the Transport won't reuse it anyway.
const maxBodySlurpSize = 2 << 10
if resp.ContentLength == -1 || resp.ContentLength <= maxBodySlurpSize {
io.CopyN(ioutil.Discard, resp.Body, maxBodySlurpSize)
io.CopyN(ioutil.Discard, resp.Body, maxBodySlurpSize) // nolint
}
resp.Body.Close()
}
@ -289,12 +289,12 @@ func performRequestWithRedirects(ctx context.Context, client *http.Client, req *
// the result into "response".
func (b *BackendClient) PerformJSONRequest(ctx context.Context, u *url.URL, request interface{}, response interface{}) error {
if u == nil {
return fmt.Errorf("No url passed to perform JSON request %+v", request)
return fmt.Errorf("no url passed to perform JSON request %+v", request)
}
secret := b.backends.GetSecret(u)
if secret == nil {
return fmt.Errorf("No backend secret configured for for %s", u)
return fmt.Errorf("no backend secret configured for for %s", u)
}
pool, err := b.getPool(u)
@ -367,7 +367,7 @@ func (b *BackendClient) PerformJSONRequest(ctx context.Context, u *url.URL, requ
return err
} else if ocs.Ocs == nil || ocs.Ocs.Data == nil {
log.Printf("Incomplete OCS response %s from %s", string(body), u)
return fmt.Errorf("Incomplete OCS response")
return fmt.Errorf("incomplete OCS response")
} else if err := json.Unmarshal(*ocs.Ocs.Data, response); err != nil {
log.Printf("Could not decode OCS response body %s from %s: %s", string(*ocs.Ocs.Data), u, err)
return err

View File

@ -71,7 +71,9 @@ func TestPostOnRedirect(t *testing.T) {
}
w.WriteHeader(http.StatusOK)
w.Write(data)
if _, err := w.Write(data); err != nil {
t.Error(err)
}
})
server := httptest.NewServer(r)

View File

@ -99,16 +99,16 @@ func TestIsUrlAllowed_Compat(t *testing.T) {
func TestIsUrlAllowed(t *testing.T) {
valid_urls := [][]string{
[]string{"https://domain.invalid/foo", string(testBackendSecret) + "-foo"},
[]string{"https://domain.invalid/foo/", string(testBackendSecret) + "-foo"},
[]string{"https://domain.invalid:443/foo/", string(testBackendSecret) + "-foo"},
[]string{"https://domain.invalid/foo/folder", string(testBackendSecret) + "-foo"},
[]string{"https://domain.invalid/bar", string(testBackendSecret) + "-bar"},
[]string{"https://domain.invalid/bar/", string(testBackendSecret) + "-bar"},
[]string{"https://domain.invalid:443/bar/", string(testBackendSecret) + "-bar"},
[]string{"https://domain.invalid/bar/folder/", string(testBackendSecret) + "-bar"},
[]string{"https://otherdomain.invalid/", string(testBackendSecret) + "-lala"},
[]string{"https://otherdomain.invalid/folder/", string(testBackendSecret) + "-lala"},
{"https://domain.invalid/foo", string(testBackendSecret) + "-foo"},
{"https://domain.invalid/foo/", string(testBackendSecret) + "-foo"},
{"https://domain.invalid:443/foo/", string(testBackendSecret) + "-foo"},
{"https://domain.invalid/foo/folder", string(testBackendSecret) + "-foo"},
{"https://domain.invalid/bar", string(testBackendSecret) + "-bar"},
{"https://domain.invalid/bar/", string(testBackendSecret) + "-bar"},
{"https://domain.invalid:443/bar/", string(testBackendSecret) + "-bar"},
{"https://domain.invalid/bar/folder/", string(testBackendSecret) + "-bar"},
{"https://otherdomain.invalid/", string(testBackendSecret) + "-lala"},
{"https://otherdomain.invalid/folder/", string(testBackendSecret) + "-lala"},
}
invalid_urls := []string{
"https://domain.invalid",
@ -176,13 +176,13 @@ type ParseBackendIdsTestcase struct {
func TestParseBackendIds(t *testing.T) {
testcases := []ParseBackendIdsTestcase{
ParseBackendIdsTestcase{"", nil},
ParseBackendIdsTestcase{"backend1", []string{"backend1"}},
ParseBackendIdsTestcase{" backend1 ", []string{"backend1"}},
ParseBackendIdsTestcase{"backend1,", []string{"backend1"}},
ParseBackendIdsTestcase{"backend1,backend1", []string{"backend1"}},
ParseBackendIdsTestcase{"backend1, backend2", []string{"backend1", "backend2"}},
ParseBackendIdsTestcase{"backend1,backend2, backend1", []string{"backend1", "backend2"}},
{"", nil},
{"backend1", []string{"backend1"}},
{" backend1 ", []string{"backend1"}},
{"backend1,", []string{"backend1"}},
{"backend1,backend1", []string{"backend1"}},
{"backend1, backend2", []string{"backend1", "backend2"}},
{"backend1,backend2, backend1", []string{"backend1", "backend2"}},
}
for _, test := range testcases {

View File

@ -85,10 +85,10 @@ func NewBackendServer(config *goconf.ConfigFile, hub *Hub, version string) (*Bac
if len(turnserverslist) != 0 {
if turnapikey == "" {
return nil, fmt.Errorf("Need a TURN API key if TURN servers are configured.")
return nil, fmt.Errorf("need a TURN API key if TURN servers are configured")
}
if turnsecret == "" {
return nil, fmt.Errorf("Need a shared TURN secret if TURN servers are configured.")
return nil, fmt.Errorf("need a shared TURN secret if TURN servers are configured")
}
log.Printf("Using configured TURN API key")
@ -169,14 +169,14 @@ func (b *BackendServer) setComonHeaders(f func(http.ResponseWriter, *http.Reques
func (b *BackendServer) welcomeFunc(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusOK)
io.WriteString(w, b.welcomeMessage)
io.WriteString(w, b.welcomeMessage) // nolint
}
func calculateTurnSecret(username string, secret []byte, valid time.Duration) (string, string) {
expires := time.Now().Add(valid)
username = fmt.Sprintf("%d:%s", expires.Unix(), username)
m := hmac.New(sha1.New, secret)
m.Write([]byte(username))
m.Write([]byte(username)) // nolint
password := base64.StdEncoding.EncodeToString(m.Sum(nil))
return username, password
}
@ -192,19 +192,19 @@ func (b *BackendServer) getTurnCredentials(w http.ResponseWriter, r *http.Reques
}
if service != "turn" || key == "" {
w.WriteHeader(http.StatusBadRequest)
io.WriteString(w, "Invalid service and/or key sent.\n")
io.WriteString(w, "Invalid service and/or key sent.\n") // nolint
return
}
if key != b.turnapikey {
w.WriteHeader(http.StatusForbidden)
io.WriteString(w, "Not allowed to access this service.\n")
io.WriteString(w, "Not allowed to access this service.\n") // nolint
return
}
if len(b.turnservers) == 0 {
w.WriteHeader(http.StatusNotFound)
io.WriteString(w, "No TURN servers available.\n")
io.WriteString(w, "No TURN servers available.\n") // nolint
return
}
@ -225,7 +225,7 @@ func (b *BackendServer) getTurnCredentials(w http.ResponseWriter, r *http.Reques
if err != nil {
log.Printf("Could not serialize TURN credentials %+v: %s", result, err)
w.WriteHeader(http.StatusInternalServerError)
io.WriteString(w, "Could not serialize credentials.")
io.WriteString(w, "Could not serialize credentials.") // nolint
return
}
@ -235,7 +235,7 @@ func (b *BackendServer) getTurnCredentials(w http.ResponseWriter, r *http.Reques
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusOK)
w.Write(data)
w.Write(data) // nolint
}
func (b *BackendServer) parseRequestBody(f func(http.ResponseWriter, *http.Request, []byte)) func(http.ResponseWriter, *http.Request) {
@ -285,7 +285,9 @@ func (b *BackendServer) sendRoomInvite(roomid string, backend *Backend, userids
},
}
for _, userid := range userids {
b.nats.PublishMessage(GetSubjectForUserId(userid, backend), msg)
if err := b.nats.PublishMessage(GetSubjectForUserId(userid, backend), msg); err != nil {
log.Printf("Could not publish room invite for user %s in backend %s: %s", userid, backend.Id(), err)
}
}
}
@ -304,7 +306,9 @@ func (b *BackendServer) sendRoomDisinvite(roomid string, backend *Backend, reaso
},
}
for _, userid := range userids {
b.nats.PublishMessage(GetSubjectForUserId(userid, backend), msg)
if err := b.nats.PublishMessage(GetSubjectForUserId(userid, backend), msg); err != nil {
log.Printf("Could not publish room disinvite for user %s in backend %s: %s", userid, backend.Id(), err)
}
}
timeout := time.Second
@ -321,7 +325,9 @@ func (b *BackendServer) sendRoomDisinvite(roomid string, backend *Backend, reaso
if sid, err := b.lookupByRoomSessionId(sessionid, nil, timeout); err != nil {
log.Printf("Could not lookup by room session %s: %s", sessionid, err)
} else if sid != "" {
b.nats.PublishMessage("session."+sid, msg)
if err := b.nats.PublishMessage("session."+sid, msg); err != nil {
log.Printf("Could not publish room disinvite for session %s: %s", sid, err)
}
}
}(sessionid)
}
@ -350,7 +356,9 @@ func (b *BackendServer) sendRoomUpdate(roomid string, backend *Backend, notified
continue
}
b.nats.PublishMessage(GetSubjectForUserId(userid, backend), msg)
if err := b.nats.PublishMessage(GetSubjectForUserId(userid, backend), msg); err != nil {
log.Printf("Could not publish room update for user %s in backend %s: %s", userid, backend.Id(), err)
}
}
}
@ -590,7 +598,7 @@ func (b *BackendServer) roomHandler(w http.ResponseWriter, r *http.Request, body
w.Header().Set("X-Content-Type-Options", "nosniff")
w.WriteHeader(http.StatusOK)
// TODO(jojo): Return better response struct.
w.Write([]byte("{}"))
w.Write([]byte("{}")) // nolint
}
func (b *BackendServer) validateStatsRequest(f func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) {
@ -622,5 +630,5 @@ func (b *BackendServer) statsHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.WriteHeader(http.StatusOK)
w.Write(statsData)
w.Write(statsData) // nolint
}

View File

@ -328,7 +328,11 @@ func TestBackendServer_RoomInvite(t *testing.T) {
if err != nil {
t.Fatal(err)
}
defer sub.Unsubscribe()
defer func() {
if err := sub.Unsubscribe(); err != nil {
t.Error(err)
}
}()
msg := &BackendServerRoomRequest{
Type: "invite",
@ -419,7 +423,11 @@ func TestBackendServer_RoomDisinvite(t *testing.T) {
if err != nil {
t.Fatal(err)
}
defer sub.Unsubscribe()
defer func() {
if err := sub.Unsubscribe(); err != nil {
t.Error(err)
}
}()
msg := &BackendServerRoomRequest{
Type: "disinvite",
@ -635,7 +643,11 @@ func TestBackendServer_RoomUpdate(t *testing.T) {
if err != nil {
t.Fatal(err)
}
defer sub.Unsubscribe()
defer func() {
if err := sub.Unsubscribe(); err != nil {
t.Error(err)
}
}()
msg := &BackendServerRoomRequest{
Type: "update",
@ -714,7 +726,11 @@ func TestBackendServer_RoomDelete(t *testing.T) {
if err != nil {
t.Fatal(err)
}
defer sub.Unsubscribe()
defer func() {
if err := sub.Unsubscribe(); err != nil {
t.Error(err)
}
}()
msg := &BackendServerRoomRequest{
Type: "delete",
@ -832,21 +848,21 @@ func TestBackendServer_ParticipantsUpdatePermissions(t *testing.T) {
Type: "participants",
Participants: &BackendRoomParticipantsRequest{
Changed: []map[string]interface{}{
map[string]interface{}{
{
"sessionId": roomId + "-" + hello1.Hello.SessionId,
"permissions": []Permission{PERMISSION_MAY_PUBLISH_MEDIA},
},
map[string]interface{}{
{
"sessionId": roomId + "-" + hello2.Hello.SessionId,
"permissions": []Permission{PERMISSION_MAY_PUBLISH_SCREEN},
},
},
Users: []map[string]interface{}{
map[string]interface{}{
{
"sessionId": roomId + "-" + hello1.Hello.SessionId,
"permissions": []Permission{PERMISSION_MAY_PUBLISH_MEDIA},
},
map[string]interface{}{
{
"sessionId": roomId + "-" + hello2.Hello.SessionId,
"permissions": []Permission{PERMISSION_MAY_PUBLISH_SCREEN},
},
@ -928,13 +944,13 @@ func TestBackendServer_ParticipantsUpdateEmptyPermissions(t *testing.T) {
Type: "participants",
Participants: &BackendRoomParticipantsRequest{
Changed: []map[string]interface{}{
map[string]interface{}{
{
"sessionId": roomId + "-" + hello.Hello.SessionId,
"permissions": []Permission{},
},
},
Users: []map[string]interface{}{
map[string]interface{}{
{
"sessionId": roomId + "-" + hello.Hello.SessionId,
"permissions": []Permission{},
},
@ -1022,21 +1038,21 @@ func TestBackendServer_ParticipantsUpdateTimeout(t *testing.T) {
InCall: &BackendRoomInCallRequest{
InCall: json.RawMessage("7"),
Changed: []map[string]interface{}{
map[string]interface{}{
{
"sessionId": roomId + "-" + hello1.Hello.SessionId,
"inCall": 7,
},
map[string]interface{}{
{
"sessionId": "unknown-room-session-id",
"inCall": 3,
},
},
Users: []map[string]interface{}{
map[string]interface{}{
{
"sessionId": roomId + "-" + hello1.Hello.SessionId,
"inCall": 7,
},
map[string]interface{}{
{
"sessionId": "unknown-room-session-id",
"inCall": 3,
},
@ -1075,21 +1091,21 @@ func TestBackendServer_ParticipantsUpdateTimeout(t *testing.T) {
InCall: &BackendRoomInCallRequest{
InCall: json.RawMessage("7"),
Changed: []map[string]interface{}{
map[string]interface{}{
{
"sessionId": roomId + "-" + hello1.Hello.SessionId,
"inCall": 7,
},
map[string]interface{}{
{
"sessionId": roomId + "-" + hello2.Hello.SessionId,
"inCall": 3,
},
},
Users: []map[string]interface{}{
map[string]interface{}{
{
"sessionId": roomId + "-" + hello1.Hello.SessionId,
"inCall": 7,
},
map[string]interface{}{
{
"sessionId": roomId + "-" + hello2.Hello.SessionId,
"inCall": 3,
},
@ -1277,7 +1293,7 @@ func TestBackendServer_TurnCredentials(t *testing.T) {
}
m := hmac.New(sha1.New, []byte(turnSecret))
m.Write([]byte(cred.Username))
m.Write([]byte(cred.Username)) // nolint
password := base64.StdEncoding.EncodeToString(m.Sum(nil))
if cred.Password != password {
t.Errorf("Expected password %s, got %s", password, cred.Password)

View File

@ -238,7 +238,7 @@ func (c *Client) ReadPump() {
conn.SetReadLimit(maxMessageSize)
conn.SetPongHandler(func(msg string) error {
now := time.Now()
conn.SetReadDeadline(now.Add(pongWait))
conn.SetReadDeadline(now.Add(pongWait)) // nolint
if msg == "" {
return nil
}
@ -258,7 +258,7 @@ func (c *Client) ReadPump() {
decodeBuffer := bufferPool.Get().(*bytes.Buffer)
defer bufferPool.Put(decodeBuffer)
for {
conn.SetReadDeadline(time.Now().Add(pongWait))
conn.SetReadDeadline(time.Now().Add(pongWait)) // nolint
messageType, reader, err := conn.NextReader()
if err != nil {
if _, ok := err.(*websocket.CloseError); !ok || websocket.IsUnexpectedCloseError(err,
@ -301,7 +301,7 @@ func (c *Client) ReadPump() {
func (c *Client) writeInternal(message json.Marshaler) bool {
var closeData []byte
c.conn.SetWriteDeadline(time.Now().Add(writeWait))
c.conn.SetWriteDeadline(time.Now().Add(writeWait)) // nolint
writer, err := c.conn.NextWriter(websocket.TextMessage)
if err == nil {
if m, ok := (interface{}(message)).(easyjson.Marshaler); ok {
@ -330,7 +330,7 @@ func (c *Client) writeInternal(message json.Marshaler) bool {
return true
close:
c.conn.SetWriteDeadline(time.Now().Add(writeWait))
c.conn.SetWriteDeadline(time.Now().Add(writeWait)) // nolint
if err := c.conn.WriteMessage(websocket.CloseMessage, closeData); err != nil {
if session := c.GetSession(); session != nil {
log.Printf("Could not send close message to client %s: %v", session.PublicId(), err)
@ -341,7 +341,7 @@ close:
return false
}
func (c *Client) writeError(e error) bool {
func (c *Client) writeError(e error) bool { // nolint
message := &ServerMessage{
Type: "error",
Error: NewError("internal_error", e.Error()),
@ -357,7 +357,7 @@ func (c *Client) writeError(e error) bool {
}
closeData := websocket.FormatCloseMessage(websocket.CloseInternalServerErr, e.Error())
c.conn.SetWriteDeadline(time.Now().Add(writeWait))
c.conn.SetWriteDeadline(time.Now().Add(writeWait)) // nolint
if err := c.conn.WriteMessage(websocket.CloseMessage, closeData); err != nil {
if session := c.GetSession(); session != nil {
log.Printf("Could not send close message to client %s: %v", session.PublicId(), err)
@ -385,8 +385,8 @@ func (c *Client) writeMessageLocked(message WritableClientMessage) bool {
session := c.GetSession()
if message.CloseAfterSend(session) {
c.conn.SetWriteDeadline(time.Now().Add(writeWait))
c.conn.WriteMessage(websocket.CloseMessage, []byte{})
c.conn.SetWriteDeadline(time.Now().Add(writeWait)) // nolint
c.conn.WriteMessage(websocket.CloseMessage, []byte{}) // nolint
if session != nil {
go session.Close()
}
@ -406,7 +406,7 @@ func (c *Client) sendPing() bool {
now := time.Now().UnixNano()
msg := strconv.FormatInt(now, 10)
c.conn.SetWriteDeadline(time.Now().Add(writeWait))
c.conn.SetWriteDeadline(time.Now().Add(writeWait)) // nolint
if err := c.conn.WriteMessage(websocket.PingMessage, []byte(msg)); err != nil {
if session := c.GetSession(); session != nil {
log.Printf("Could not send ping to client %s: %v", session.PublicId(), err)

View File

@ -47,7 +47,7 @@ import (
"github.com/gorilla/websocket"
"github.com/mailru/easyjson"
"github.com/strukturag/nextcloud-spreed-signaling"
signaling "github.com/strukturag/nextcloud-spreed-signaling"
)
var (
@ -177,8 +177,8 @@ func (c *SignalingClient) Close() {
c.lock.Lock()
c.publicSessionId = ""
c.privateSessionId = ""
c.conn.SetWriteDeadline(time.Now().Add(writeWait))
c.conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
c.conn.SetWriteDeadline(time.Now().Add(writeWait)) // nolint
c.conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, "")) // nolint
c.conn.Close()
c.conn = nil
c.lock.Unlock()
@ -271,15 +271,15 @@ func (c *SignalingClient) readPump() {
}()
conn.SetReadLimit(maxMessageSize)
conn.SetReadDeadline(time.Now().Add(pongWait))
conn.SetReadDeadline(time.Now().Add(pongWait)) // nolint
conn.SetPongHandler(func(string) error {
conn.SetReadDeadline(time.Now().Add(pongWait))
conn.SetReadDeadline(time.Now().Add(pongWait)) // nolint
return nil
})
var decodeBuffer bytes.Buffer
for {
conn.SetReadDeadline(time.Now().Add(pongWait))
conn.SetReadDeadline(time.Now().Add(pongWait)) // nolint
messageType, reader, err := conn.NextReader()
if err != nil {
if websocket.IsUnexpectedCloseError(err,
@ -319,7 +319,7 @@ func (c *SignalingClient) readPump() {
func (c *SignalingClient) writeInternal(message *signaling.ClientMessage) bool {
var closeData []byte
c.conn.SetWriteDeadline(time.Now().Add(writeWait))
c.conn.SetWriteDeadline(time.Now().Add(writeWait)) // nolint
writer, err := c.conn.NextWriter(websocket.TextMessage)
if err == nil {
_, err = easyjson.MarshalToWriter(message, writer)
@ -341,8 +341,8 @@ func (c *SignalingClient) writeInternal(message *signaling.ClientMessage) bool {
return true
close:
c.conn.SetWriteDeadline(time.Now().Add(writeWait))
c.conn.WriteMessage(websocket.CloseMessage, closeData)
c.conn.SetWriteDeadline(time.Now().Add(writeWait)) // nolint
c.conn.WriteMessage(websocket.CloseMessage, closeData) // nolint
return false
}
@ -353,7 +353,7 @@ func (c *SignalingClient) sendPing() bool {
return false
}
c.conn.SetWriteDeadline(time.Now().Add(writeWait))
c.conn.SetWriteDeadline(time.Now().Add(writeWait)) // nolint
if err := c.conn.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
return false
}
@ -476,7 +476,7 @@ func registerAuthHandler(router *mux.Router) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(jsonpayload)
w.Write(jsonpayload) // nolint
})
}
@ -562,7 +562,7 @@ func main() {
Handler: r,
}
go func() {
server.Serve(listener)
server.Serve(listener) // nolint
}()
backendUrl := "http://" + listener.Addr().String()
log.Println("Backend server running on", backendUrl)

View File

@ -322,11 +322,15 @@ func (s *ClientSession) closeAndWait(wait bool) {
s.mu.Lock()
defer s.mu.Unlock()
if s.userSubscription != nil {
s.userSubscription.Unsubscribe()
if err := s.userSubscription.Unsubscribe(); err != nil {
log.Printf("Error closing user subscription in session %s: %s", s.PublicId(), err)
}
s.userSubscription = nil
}
if s.sessionSubscription != nil {
s.sessionSubscription.Unsubscribe()
if err := s.sessionSubscription.Unsubscribe(); err != nil {
log.Printf("Error closing session subscription in session %s: %s", s.PublicId(), err)
}
s.sessionSubscription = nil
}
go func(virtualSessions map[*VirtualSession]bool) {
@ -434,7 +438,9 @@ func (s *ClientSession) UnsubscribeRoomNats() {
func (s *ClientSession) doUnsubscribeRoomNats(notify bool) {
if s.roomSubscription != nil {
s.roomSubscription.Unsubscribe()
if err := s.roomSubscription.Unsubscribe(); err != nil {
log.Printf("Error closing room subscription in session %s: %s", s.PublicId(), err)
}
s.roomSubscription = nil
}
s.hub.roomSessions.DeleteRoomSession(s)

View File

@ -40,26 +40,26 @@ type EqualTestData struct {
func Test_permissionsEqual(t *testing.T) {
tests := []EqualTestData{
EqualTestData{
{
a: nil,
b: nil,
equal: true,
},
EqualTestData{
{
a: map[Permission]bool{
PERMISSION_MAY_PUBLISH_MEDIA: true,
},
b: nil,
equal: false,
},
EqualTestData{
{
a: nil,
b: map[Permission]bool{
PERMISSION_MAY_PUBLISH_MEDIA: true,
},
equal: false,
},
EqualTestData{
{
a: map[Permission]bool{
PERMISSION_MAY_PUBLISH_MEDIA: true,
},
@ -68,7 +68,7 @@ func Test_permissionsEqual(t *testing.T) {
},
equal: true,
},
EqualTestData{
{
a: map[Permission]bool{
PERMISSION_MAY_PUBLISH_MEDIA: true,
PERMISSION_MAY_PUBLISH_SCREEN: true,
@ -78,7 +78,7 @@ func Test_permissionsEqual(t *testing.T) {
},
equal: false,
},
EqualTestData{
{
a: map[Permission]bool{
PERMISSION_MAY_PUBLISH_MEDIA: true,
},
@ -88,7 +88,7 @@ func Test_permissionsEqual(t *testing.T) {
},
equal: false,
},
EqualTestData{
{
a: map[Permission]bool{
PERMISSION_MAY_PUBLISH_MEDIA: true,
PERMISSION_MAY_PUBLISH_SCREEN: true,
@ -99,7 +99,7 @@ func Test_permissionsEqual(t *testing.T) {
},
equal: true,
},
EqualTestData{
{
a: map[Permission]bool{
PERMISSION_MAY_PUBLISH_MEDIA: true,
PERMISSION_MAY_PUBLISH_SCREEN: true,

View File

@ -5,259 +5,259 @@ package signaling
var (
ContinentMap map[string][]string = map[string][]string{
"AD": []string{"EU"},
"AE": []string{"AS"},
"AF": []string{"AS"},
"AG": []string{"NA"},
"AI": []string{"NA"},
"AL": []string{"EU"},
"AM": []string{"EU", "AS"},
"AN": []string{"NA"},
"AO": []string{"AF"},
"AQ": []string{"AN"},
"AR": []string{"SA"},
"AS": []string{"OC"},
"AT": []string{"EU"},
"AU": []string{"OC"},
"AW": []string{"NA"},
"AX": []string{"EU"},
"AZ": []string{"EU", "AS"},
"BA": []string{"EU"},
"BB": []string{"NA"},
"BD": []string{"AS"},
"BE": []string{"EU"},
"BF": []string{"AF"},
"BG": []string{"EU"},
"BH": []string{"AS"},
"BI": []string{"AF"},
"BJ": []string{"AF"},
"BL": []string{"NA"},
"BM": []string{"NA"},
"BN": []string{"AS"},
"BO": []string{"SA"},
"BQ": []string{"NA"},
"BR": []string{"SA"},
"BS": []string{"NA"},
"BT": []string{"AS"},
"BV": []string{"AN"},
"BW": []string{"AF"},
"BY": []string{"EU"},
"BZ": []string{"NA"},
"CA": []string{"NA"},
"CC": []string{"AS"},
"CD": []string{"AF"},
"CF": []string{"AF"},
"CG": []string{"AF"},
"CH": []string{"EU"},
"CI": []string{"AF"},
"CK": []string{"OC"},
"CL": []string{"SA"},
"CM": []string{"AF"},
"CN": []string{"AS"},
"CO": []string{"SA"},
"CR": []string{"NA"},
"CU": []string{"NA"},
"CV": []string{"AF"},
"CW": []string{"NA"},
"CX": []string{"AS"},
"CY": []string{"EU", "AS"},
"CZ": []string{"EU"},
"DE": []string{"EU"},
"DJ": []string{"AF"},
"DK": []string{"EU"},
"DM": []string{"NA"},
"DO": []string{"NA"},
"DZ": []string{"AF"},
"EC": []string{"SA"},
"EE": []string{"EU"},
"EG": []string{"AF"},
"EH": []string{"AF"},
"ER": []string{"AF"},
"ES": []string{"EU"},
"ET": []string{"AF"},
"FI": []string{"EU"},
"FJ": []string{"OC"},
"FK": []string{"SA"},
"FM": []string{"OC"},
"FO": []string{"EU"},
"FR": []string{"EU"},
"GA": []string{"AF"},
"GB": []string{"EU"},
"GD": []string{"NA"},
"GE": []string{"EU", "AS"},
"GF": []string{"SA"},
"GG": []string{"EU"},
"GH": []string{"AF"},
"GI": []string{"EU"},
"GL": []string{"NA"},
"GM": []string{"AF"},
"GN": []string{"AF"},
"GP": []string{"NA"},
"GQ": []string{"AF"},
"GR": []string{"EU"},
"GS": []string{"AN"},
"GT": []string{"NA"},
"GU": []string{"OC"},
"GW": []string{"AF"},
"GY": []string{"SA"},
"HK": []string{"AS"},
"HM": []string{"AN"},
"HN": []string{"NA"},
"HR": []string{"EU"},
"HT": []string{"NA"},
"HU": []string{"EU"},
"ID": []string{"AS"},
"IE": []string{"EU"},
"IL": []string{"AS"},
"IM": []string{"EU"},
"IN": []string{"AS"},
"IO": []string{"AS"},
"IQ": []string{"AS"},
"IR": []string{"AS"},
"IS": []string{"EU"},
"IT": []string{"EU"},
"JE": []string{"EU"},
"JM": []string{"NA"},
"JO": []string{"AS"},
"JP": []string{"AS"},
"KE": []string{"AF"},
"KG": []string{"AS"},
"KH": []string{"AS"},
"KI": []string{"OC"},
"KM": []string{"AF"},
"KN": []string{"NA"},
"KP": []string{"AS"},
"KR": []string{"AS"},
"KW": []string{"AS"},
"KY": []string{"NA"},
"KZ": []string{"EU", "AS"},
"LA": []string{"AS"},
"LB": []string{"AS"},
"LC": []string{"NA"},
"LI": []string{"EU"},
"LK": []string{"AS"},
"LR": []string{"AF"},
"LS": []string{"AF"},
"LT": []string{"EU"},
"LU": []string{"EU"},
"LV": []string{"EU"},
"LY": []string{"AF"},
"MA": []string{"AF"},
"MC": []string{"EU"},
"MD": []string{"EU"},
"ME": []string{"EU"},
"MF": []string{"NA"},
"MG": []string{"AF"},
"MH": []string{"OC"},
"MK": []string{"EU"},
"ML": []string{"AF"},
"MM": []string{"AS"},
"MN": []string{"AS"},
"MO": []string{"AS"},
"MP": []string{"OC"},
"MQ": []string{"NA"},
"MR": []string{"AF"},
"MS": []string{"NA"},
"MT": []string{"EU"},
"MU": []string{"AF"},
"MV": []string{"AS"},
"MW": []string{"AF"},
"MX": []string{"NA"},
"MY": []string{"AS"},
"MZ": []string{"AF"},
"NA": []string{"AF"},
"NC": []string{"OC"},
"NE": []string{"AF"},
"NF": []string{"OC"},
"NG": []string{"AF"},
"NI": []string{"NA"},
"NL": []string{"EU"},
"NO": []string{"EU"},
"NP": []string{"AS"},
"NR": []string{"OC"},
"NU": []string{"OC"},
"NZ": []string{"OC"},
"OM": []string{"AS"},
"PA": []string{"NA"},
"PE": []string{"SA"},
"PF": []string{"OC"},
"PG": []string{"OC"},
"PH": []string{"AS"},
"PK": []string{"AS"},
"PL": []string{"EU"},
"PM": []string{"NA"},
"PN": []string{"OC"},
"PR": []string{"NA"},
"PS": []string{"AS"},
"PT": []string{"EU"},
"PW": []string{"OC"},
"PY": []string{"SA"},
"QA": []string{"AS"},
"RE": []string{"AF"},
"RO": []string{"EU"},
"RS": []string{"EU"},
"RU": []string{"EU", "AS"},
"RW": []string{"AF"},
"SA": []string{"AS"},
"SB": []string{"OC"},
"SC": []string{"AF"},
"SD": []string{"AF"},
"SE": []string{"EU"},
"SG": []string{"AS"},
"SH": []string{"AF"},
"SI": []string{"EU"},
"SJ": []string{"EU"},
"SK": []string{"EU"},
"SL": []string{"AF"},
"SM": []string{"EU"},
"SN": []string{"AF"},
"SO": []string{"AF"},
"SR": []string{"SA"},
"SS": []string{"AF"},
"ST": []string{"AF"},
"SV": []string{"NA"},
"SX": []string{"NA"},
"SY": []string{"AS"},
"SZ": []string{"AF"},
"TC": []string{"NA"},
"TD": []string{"AF"},
"TF": []string{"AN"},
"TG": []string{"AF"},
"TH": []string{"AS"},
"TJ": []string{"AS"},
"TK": []string{"OC"},
"TL": []string{"AS"},
"TM": []string{"AS"},
"TN": []string{"AF"},
"TO": []string{"OC"},
"TR": []string{"EU", "AS"},
"TT": []string{"NA"},
"TV": []string{"OC"},
"TW": []string{"AS"},
"TZ": []string{"AF"},
"UA": []string{"EU"},
"UG": []string{"AF"},
"UM": []string{"OC", "NA"},
"US": []string{"NA"},
"UY": []string{"SA"},
"UZ": []string{"AS"},
"VA": []string{"EU"},
"VC": []string{"NA"},
"VE": []string{"SA"},
"VG": []string{"NA"},
"VI": []string{"NA"},
"VN": []string{"AS"},
"VU": []string{"OC"},
"WF": []string{"OC"},
"WS": []string{"OC"},
"XD": []string{"AS"},
"XE": []string{"AS"},
"XS": []string{"AS"},
"XX": []string{"OC"},
"YE": []string{"AS"},
"YT": []string{"AF"},
"ZA": []string{"AF"},
"ZM": []string{"AF"},
"ZW": []string{"AF"},
"AD": {"EU"},
"AE": {"AS"},
"AF": {"AS"},
"AG": {"NA"},
"AI": {"NA"},
"AL": {"EU"},
"AM": {"EU", "AS"},
"AN": {"NA"},
"AO": {"AF"},
"AQ": {"AN"},
"AR": {"SA"},
"AS": {"OC"},
"AT": {"EU"},
"AU": {"OC"},
"AW": {"NA"},
"AX": {"EU"},
"AZ": {"EU", "AS"},
"BA": {"EU"},
"BB": {"NA"},
"BD": {"AS"},
"BE": {"EU"},
"BF": {"AF"},
"BG": {"EU"},
"BH": {"AS"},
"BI": {"AF"},
"BJ": {"AF"},
"BL": {"NA"},
"BM": {"NA"},
"BN": {"AS"},
"BO": {"SA"},
"BQ": {"NA"},
"BR": {"SA"},
"BS": {"NA"},
"BT": {"AS"},
"BV": {"AN"},
"BW": {"AF"},
"BY": {"EU"},
"BZ": {"NA"},
"CA": {"NA"},
"CC": {"AS"},
"CD": {"AF"},
"CF": {"AF"},
"CG": {"AF"},
"CH": {"EU"},
"CI": {"AF"},
"CK": {"OC"},
"CL": {"SA"},
"CM": {"AF"},
"CN": {"AS"},
"CO": {"SA"},
"CR": {"NA"},
"CU": {"NA"},
"CV": {"AF"},
"CW": {"NA"},
"CX": {"AS"},
"CY": {"EU", "AS"},
"CZ": {"EU"},
"DE": {"EU"},
"DJ": {"AF"},
"DK": {"EU"},
"DM": {"NA"},
"DO": {"NA"},
"DZ": {"AF"},
"EC": {"SA"},
"EE": {"EU"},
"EG": {"AF"},
"EH": {"AF"},
"ER": {"AF"},
"ES": {"EU"},
"ET": {"AF"},
"FI": {"EU"},
"FJ": {"OC"},
"FK": {"SA"},
"FM": {"OC"},
"FO": {"EU"},
"FR": {"EU"},
"GA": {"AF"},
"GB": {"EU"},
"GD": {"NA"},
"GE": {"EU", "AS"},
"GF": {"SA"},
"GG": {"EU"},
"GH": {"AF"},
"GI": {"EU"},
"GL": {"NA"},
"GM": {"AF"},
"GN": {"AF"},
"GP": {"NA"},
"GQ": {"AF"},
"GR": {"EU"},
"GS": {"AN"},
"GT": {"NA"},
"GU": {"OC"},
"GW": {"AF"},
"GY": {"SA"},
"HK": {"AS"},
"HM": {"AN"},
"HN": {"NA"},
"HR": {"EU"},
"HT": {"NA"},
"HU": {"EU"},
"ID": {"AS"},
"IE": {"EU"},
"IL": {"AS"},
"IM": {"EU"},
"IN": {"AS"},
"IO": {"AS"},
"IQ": {"AS"},
"IR": {"AS"},
"IS": {"EU"},
"IT": {"EU"},
"JE": {"EU"},
"JM": {"NA"},
"JO": {"AS"},
"JP": {"AS"},
"KE": {"AF"},
"KG": {"AS"},
"KH": {"AS"},
"KI": {"OC"},
"KM": {"AF"},
"KN": {"NA"},
"KP": {"AS"},
"KR": {"AS"},
"KW": {"AS"},
"KY": {"NA"},
"KZ": {"EU", "AS"},
"LA": {"AS"},
"LB": {"AS"},
"LC": {"NA"},
"LI": {"EU"},
"LK": {"AS"},
"LR": {"AF"},
"LS": {"AF"},
"LT": {"EU"},
"LU": {"EU"},
"LV": {"EU"},
"LY": {"AF"},
"MA": {"AF"},
"MC": {"EU"},
"MD": {"EU"},
"ME": {"EU"},
"MF": {"NA"},
"MG": {"AF"},
"MH": {"OC"},
"MK": {"EU"},
"ML": {"AF"},
"MM": {"AS"},
"MN": {"AS"},
"MO": {"AS"},
"MP": {"OC"},
"MQ": {"NA"},
"MR": {"AF"},
"MS": {"NA"},
"MT": {"EU"},
"MU": {"AF"},
"MV": {"AS"},
"MW": {"AF"},
"MX": {"NA"},
"MY": {"AS"},
"MZ": {"AF"},
"NA": {"AF"},
"NC": {"OC"},
"NE": {"AF"},
"NF": {"OC"},
"NG": {"AF"},
"NI": {"NA"},
"NL": {"EU"},
"NO": {"EU"},
"NP": {"AS"},
"NR": {"OC"},
"NU": {"OC"},
"NZ": {"OC"},
"OM": {"AS"},
"PA": {"NA"},
"PE": {"SA"},
"PF": {"OC"},
"PG": {"OC"},
"PH": {"AS"},
"PK": {"AS"},
"PL": {"EU"},
"PM": {"NA"},
"PN": {"OC"},
"PR": {"NA"},
"PS": {"AS"},
"PT": {"EU"},
"PW": {"OC"},
"PY": {"SA"},
"QA": {"AS"},
"RE": {"AF"},
"RO": {"EU"},
"RS": {"EU"},
"RU": {"EU", "AS"},
"RW": {"AF"},
"SA": {"AS"},
"SB": {"OC"},
"SC": {"AF"},
"SD": {"AF"},
"SE": {"EU"},
"SG": {"AS"},
"SH": {"AF"},
"SI": {"EU"},
"SJ": {"EU"},
"SK": {"EU"},
"SL": {"AF"},
"SM": {"EU"},
"SN": {"AF"},
"SO": {"AF"},
"SR": {"SA"},
"SS": {"AF"},
"ST": {"AF"},
"SV": {"NA"},
"SX": {"NA"},
"SY": {"AS"},
"SZ": {"AF"},
"TC": {"NA"},
"TD": {"AF"},
"TF": {"AN"},
"TG": {"AF"},
"TH": {"AS"},
"TJ": {"AS"},
"TK": {"OC"},
"TL": {"AS"},
"TM": {"AS"},
"TN": {"AF"},
"TO": {"OC"},
"TR": {"EU", "AS"},
"TT": {"NA"},
"TV": {"OC"},
"TW": {"AS"},
"TZ": {"AF"},
"UA": {"EU"},
"UG": {"AF"},
"UM": {"OC", "NA"},
"US": {"NA"},
"UY": {"SA"},
"UZ": {"AS"},
"VA": {"EU"},
"VC": {"NA"},
"VE": {"SA"},
"VG": {"NA"},
"VI": {"NA"},
"VN": {"AS"},
"VU": {"OC"},
"WF": {"OC"},
"WS": {"OC"},
"XD": {"AS"},
"XE": {"AS"},
"XS": {"AS"},
"XX": {"OC"},
"YE": {"AS"},
"YT": {"AF"},
"ZA": {"AF"},
"ZM": {"AF"},
"ZW": {"AF"},
}
)

View File

@ -153,7 +153,7 @@ func (g *GeoLookup) updateUrl() error {
log.Printf("GeoIP database at %s has not changed", g.url)
return nil
} else if response.StatusCode/100 != 2 {
return fmt.Errorf("Downloading %s returned an error: %s", g.url, response.Status)
return fmt.Errorf("downloading %s returned an error: %s", g.url, response.Status)
}
body := response.Body
@ -186,7 +186,7 @@ func (g *GeoLookup) updateUrl() error {
}
if len(geoipdata) == 0 {
return fmt.Errorf("Did not find MaxMind database in tarball from %s", g.url)
return fmt.Errorf("did not find MaxMind database in tarball from %s", g.url)
}
reader, err := maxminddb.FromBytes(geoipdata)

View File

@ -98,9 +98,9 @@ func TestGeoLookupCaching(t *testing.T) {
func TestGeoLookupContinent(t *testing.T) {
tests := map[string][]string{
"AU": []string{"OC"},
"DE": []string{"EU"},
"RU": []string{"EU", "AS"},
"AU": {"OC"},
"DE": {"EU"},
"RU": {"EU", "AS"},
"": nil,
"INVALID ": nil,
}

24
hub.go
View File

@ -161,7 +161,7 @@ func NewHub(config *goconf.ConfigFile, nats NatsClient, r *mux.Router, version s
case 24:
case 32:
default:
return nil, fmt.Errorf("The sessions block key must be 16, 24 or 32 bytes but is %d bytes", len(blockKey))
return nil, fmt.Errorf("the sessions block key must be 16, 24 or 32 bytes but is %d bytes", len(blockKey))
}
internalClientsSecret, _ := config.GetString("clients", "internalsecret")
@ -236,12 +236,12 @@ func NewHub(config *goconf.ConfigFile, nats NatsClient, r *mux.Router, version s
if strings.Contains(option, "/") {
_, ipNet, err = net.ParseCIDR(option)
if err != nil {
return nil, fmt.Errorf("Could not parse CIDR %s: %s", option, err)
return nil, fmt.Errorf("could not parse CIDR %s: %s", option, err)
}
} else {
ip = net.ParseIP(option)
if ip == nil {
return nil, fmt.Errorf("Could not parse IP %s", option)
return nil, fmt.Errorf("could not parse IP %s", option)
}
var mask net.IPMask
@ -482,7 +482,7 @@ func (h *Hub) encodeSessionId(data *SessionIdData, sessionType string) (string,
func (h *Hub) getDecodeCache(cache_key string) *LruCache {
hash := fnv.New32a()
hash.Write([]byte(cache_key))
hash.Write([]byte(cache_key)) // nolint
idx := hash.Sum32() % uint32(len(h.decodeCaches))
return h.decodeCaches[idx]
}
@ -931,7 +931,7 @@ func (h *Hub) processHelloInternal(client *Client, message *ClientMessage) {
// Validate internal connection.
rnd := message.Hello.Auth.internalParams.Random
mac := hmac.New(sha256.New, h.internalClientsSecret)
mac.Write([]byte(rnd))
mac.Write([]byte(rnd)) // nolint
check := hex.EncodeToString(mac.Sum(nil))
if len(rnd) < minTokenRandomLength || check != message.Hello.Auth.internalParams.Token {
client.SendMessage(message.NewErrorServerMessage(InvalidToken))
@ -969,7 +969,9 @@ func (h *Hub) disconnectByRoomSessionId(roomSessionId string) {
Reason: "room_session_reconnected",
},
}
h.nats.PublishMessage("session."+sessionId, msg)
if err := h.nats.PublishMessage("session."+sessionId, msg); err != nil {
log.Printf("Could not send reconnect bye to session %s: %s", sessionId, err)
}
return
}
@ -1323,7 +1325,7 @@ func (h *Hub) processMessageMsg(client *Client, message *ClientMessage) {
// client) to start his stream, so we must not block the active
// goroutine.
go h.processMcuMessage(client, recipient, recipientSession, message, msg, clientData)
} else {
} else { // nolint
// Client is not connected yet.
}
return
@ -1335,7 +1337,9 @@ func (h *Hub) processMessageMsg(client *Client, message *ClientMessage) {
log.Printf("Sending offers to remote clients is not supported yet (client %s)", session.PublicId())
return
}
h.nats.PublishMessage(subject, response)
if err := h.nats.PublishMessage(subject, response); err != nil {
log.Printf("Error publishing message to remote session: %s", err)
}
}
}
@ -1434,7 +1438,9 @@ func (h *Hub) processControlMsg(client *Client, message *ClientMessage) {
if recipient != nil {
recipient.SendMessage(response)
} else {
h.nats.PublishMessage(subject, response)
if err := h.nats.PublishMessage(subject, response); err != nil {
log.Printf("Error publishing message to remote session: %s", err)
}
}
}

View File

@ -218,7 +218,7 @@ func validateBackendChecksum(t *testing.T, f func(http.ResponseWriter, *http.Req
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(data)
w.Write(data) // nolint
}
}
@ -960,7 +960,7 @@ func TestClientHelloResumePublicId(t *testing.T) {
}
data := "from-1-to-2"
client1.SendMessage(recipient2, data)
client1.SendMessage(recipient2, data) // nolint
var payload string
var sender *MessageServerMessageSender
@ -1226,9 +1226,9 @@ func TestClientMessageToSessionId(t *testing.T) {
}
data1 := "from-1-to-2"
client1.SendMessage(recipient2, data1)
client1.SendMessage(recipient2, data1) // nolint
data2 := "from-2-to-1"
client2.SendMessage(recipient1, data2)
client2.SendMessage(recipient1, data2) // nolint
var payload string
if err := checkReceiveClientMessage(ctx, client1, "session", hello2.Hello, &payload); err != nil {
@ -1286,9 +1286,9 @@ func TestClientMessageToUserId(t *testing.T) {
}
data1 := "from-1-to-2"
client1.SendMessage(recipient2, data1)
client1.SendMessage(recipient2, data1) // nolint
data2 := "from-2-to-1"
client2.SendMessage(recipient1, data2)
client2.SendMessage(recipient1, data2) // nolint
var payload string
if err := checkReceiveClientMessage(ctx, client1, "user", hello2.Hello, &payload); err != nil {
@ -1361,7 +1361,7 @@ func TestClientMessageToUserIdMultipleSessions(t *testing.T) {
}
data1 := "from-1-to-2"
client1.SendMessage(recipient, data1)
client1.SendMessage(recipient, data1) // nolint
// Both clients will receive the message as it was sent to the user.
var payload string
@ -1484,9 +1484,9 @@ func TestClientMessageToRoom(t *testing.T) {
}
data1 := "from-1-to-2"
client1.SendMessage(recipient, data1)
client1.SendMessage(recipient, data1) // nolint
data2 := "from-2-to-1"
client2.SendMessage(recipient, data2)
client2.SendMessage(recipient, data2) // nolint
var payload string
if err := checkReceiveClientMessage(ctx, client1, "room", hello2.Hello, &payload); err != nil {
@ -1732,9 +1732,8 @@ func TestJoinMultiple(t *testing.T) {
func TestGetRealUserIP(t *testing.T) {
REMOTE_ATTR := "192.168.1.2"
var request *http.Request
request = &http.Request{
request := &http.Request{
RemoteAddr: REMOTE_ATTR,
}
if ip := getRealUserIP(request); ip != REMOTE_ATTR {
@ -1815,8 +1814,8 @@ func TestClientMessageToSessionIdWhileDisconnected(t *testing.T) {
if err := json.Unmarshal([]byte(chat_refresh), &data1); err != nil {
t.Fatal(err)
}
client1.SendMessage(recipient2, data1)
client1.SendMessage(recipient2, data1)
client1.SendMessage(recipient2, data1) // nolint
client1.SendMessage(recipient2, data1) // nolint
client2 = NewTestClient(t, server, hub)
defer client2.CloseWithBye()
@ -1909,7 +1908,7 @@ func TestRoomParticipantsListUpdateWhileDisconnected(t *testing.T) {
// Simulate request from the backend that somebody joined the call.
users := []map[string]interface{}{
map[string]interface{}{
{
"sessionId": "the-session-id",
"inCall": 1,
},
@ -1943,7 +1942,7 @@ func TestRoomParticipantsListUpdateWhileDisconnected(t *testing.T) {
if err := json.Unmarshal([]byte(chat_refresh), &data1); err != nil {
t.Fatal(err)
}
client1.SendMessage(recipient2, data1)
client1.SendMessage(recipient2, data1) // nolint
client2 = NewTestClient(t, server, hub)
defer client2.CloseWithBye()
@ -2294,9 +2293,9 @@ func TestNoSendBetweenSessionsOnDifferentBackends(t *testing.T) {
}
data1 := "from-1-to-2"
client1.SendMessage(recipient2, data1)
client1.SendMessage(recipient2, data1) // nolint
data2 := "from-2-to-1"
client2.SendMessage(recipient1, data2)
client2.SendMessage(recipient1, data2) // nolint
var payload string
ctx2, cancel2 := context.WithTimeout(context.Background(), 100*time.Millisecond)
@ -2400,9 +2399,9 @@ func TestNoSameRoomOnDifferentBackends(t *testing.T) {
}
data1 := "from-1-to-2"
client1.SendMessage(recipient, data1)
client1.SendMessage(recipient, data1) // nolint
data2 := "from-2-to-1"
client2.SendMessage(recipient, data2)
client2.SendMessage(recipient, data2) // nolint
var payload string
ctx2, cancel2 := context.WithTimeout(context.Background(), 100*time.Millisecond)

View File

@ -166,7 +166,7 @@ type TrickleMsg struct {
}
func unexpected(request string) error {
return fmt.Errorf("Unexpected response received to '%s' request", request)
return fmt.Errorf("unexpected response received to '%s' request", request)
}
type transaction struct {

View File

@ -36,7 +36,7 @@ const (
)
var (
ErrNotConnected = fmt.Errorf("Not connected")
ErrNotConnected = fmt.Errorf("not connected")
)
type McuListener interface {

View File

@ -60,10 +60,6 @@ var (
streamTypeVideo: videoPublisherUserId,
streamTypeScreen: screenPublisherUserId,
}
userIdToStreamType = map[uint64]string{
videoPublisherUserId: streamTypeVideo,
screenPublisherUserId: streamTypeScreen,
}
)
func getPluginValue(data janus.PluginData, pluginName string, key string) interface{} {
@ -209,12 +205,16 @@ func NewMcuJanus(url string, config *goconf.ConfigFile, nats NatsClient) (Mcu, e
func (m *mcuJanus) disconnect() {
if m.handle != nil {
m.handle.Detach(context.TODO())
if _, err := m.handle.Detach(context.TODO()); err != nil {
log.Printf("Error detaching handle %d: %s", m.handle.Id, err)
}
m.handle = nil
}
if m.session != nil {
m.closeChan <- true
m.session.Destroy(context.TODO())
if _, err := m.session.Destroy(context.TODO()); err != nil {
log.Printf("Error destroying session %d: %s", m.session.Id, err)
}
m.session = nil
}
if m.gw != nil {
@ -431,7 +431,7 @@ func (m *mcuJanus) sendKeepalive() {
type mcuJanusClient struct {
mcu *mcuJanus
listener McuListener
mu sync.Mutex
mu sync.Mutex // nolint
id uint64
session uint64
@ -626,13 +626,17 @@ func (m *mcuJanus) getOrCreatePublisherHandle(ctx context.Context, id string, st
create_msg["bitrate"] = bitrate
create_response, err := handle.Request(ctx, create_msg)
if err != nil {
handle.Detach(ctx)
if _, err2 := handle.Detach(ctx); err2 != nil {
log.Printf("Error detaching handle %d: %s", handle.Id, err2)
}
return nil, 0, 0, err
}
roomId = getPluginIntValue(create_response.PluginData, pluginVideoRoom, "room")
if roomId == 0 {
handle.Detach(ctx)
if _, err := handle.Detach(ctx); err != nil {
log.Printf("Error detaching handle %d: %s", handle.Id, err)
}
return nil, 0, 0, fmt.Errorf("No room id received: %+v", create_response)
}
@ -650,7 +654,9 @@ func (m *mcuJanus) getOrCreatePublisherHandle(ctx context.Context, id string, st
response, err := handle.Message(ctx, msg, nil)
if err != nil {
handle.Detach(ctx)
if _, err2 := handle.Detach(ctx); err2 != nil {
log.Printf("Error detaching handle %d: %s", handle.Id, err2)
}
return nil, 0, 0, err
}
@ -911,7 +917,11 @@ func (m *mcuJanus) getPublisherRoomId(ctx context.Context, publisher string, str
if err != nil {
return 0, err
}
defer sub.Unsubscribe()
defer func() {
if err := sub.Unsubscribe(); err != nil {
log.Printf("Error unsubscribing channel for %s publisher %s: %s", streamType, publisher, err)
}
}()
for roomId == 0 {
var err error
@ -1073,7 +1083,11 @@ func (p *mcuJanusSubscriber) joinRoom(ctx context.Context, callback func(error,
callback(err, nil)
return
}
defer sub.Unsubscribe()
defer func() {
if err := sub.Unsubscribe(); err != nil {
log.Printf("Error unsubscribing channel for %s publisher %s: %s", p.streamType, p.publisher, err)
}
}()
retry:
join_msg := map[string]interface{}{

View File

@ -379,7 +379,7 @@ func (c *mcuProxyConnection) readPump() {
conn.SetPongHandler(func(msg string) error {
now := time.Now()
conn.SetReadDeadline(now.Add(pongWait))
conn.SetReadDeadline(now.Add(pongWait)) // nolint
if msg == "" {
return nil
}
@ -392,7 +392,7 @@ func (c *mcuProxyConnection) readPump() {
})
for {
conn.SetReadDeadline(time.Now().Add(pongWait))
conn.SetReadDeadline(time.Now().Add(pongWait)) // nolint
_, message, err := conn.ReadMessage()
if err != nil {
if _, ok := err.(*websocket.CloseError); !ok || websocket.IsUnexpectedCloseError(err,
@ -423,7 +423,7 @@ func (c *mcuProxyConnection) sendPing() bool {
now := time.Now()
msg := strconv.FormatInt(now.UnixNano(), 10)
c.conn.SetWriteDeadline(now.Add(writeWait))
c.conn.SetWriteDeadline(now.Add(writeWait)) // nolint
if err := c.conn.WriteMessage(websocket.PingMessage, []byte(msg)); err != nil {
log.Printf("Could not send ping to proxy at %s: %v", c.url, err)
c.scheduleReconnect()
@ -465,7 +465,7 @@ func (c *mcuProxyConnection) sendClose() error {
return ErrNotConnected
}
c.conn.SetWriteDeadline(time.Now().Add(writeWait))
c.conn.SetWriteDeadline(time.Now().Add(writeWait)) // nolint
return c.conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
}
@ -858,7 +858,7 @@ func (c *mcuProxyConnection) sendMessageLocked(msg *ProxyClientMessage) error {
if c.conn == nil {
return ErrNotConnected
}
c.conn.SetWriteDeadline(time.Now().Add(writeWait))
c.conn.SetWriteDeadline(time.Now().Add(writeWait)) // nolint
return c.conn.WriteJSON(msg)
}
@ -971,7 +971,6 @@ type mcuProxy struct {
etcdMu sync.Mutex
client atomic.Value
keyPrefix atomic.Value
keyInfos map[string]*ProxyInformationEtcd
urlToKey map[string]string

View File

@ -39,39 +39,39 @@ func Test_sortConnectionsForCountry(t *testing.T) {
testcases := map[string][][]*mcuProxyConnection{
// Direct country match
"DE": [][]*mcuProxyConnection{
[]*mcuProxyConnection{conn_at, conn_jp, conn_de},
[]*mcuProxyConnection{conn_de, conn_at, conn_jp},
"DE": {
{conn_at, conn_jp, conn_de},
{conn_de, conn_at, conn_jp},
},
// Direct country match
"AT": [][]*mcuProxyConnection{
[]*mcuProxyConnection{conn_at, conn_jp, conn_de},
[]*mcuProxyConnection{conn_at, conn_de, conn_jp},
"AT": {
{conn_at, conn_jp, conn_de},
{conn_at, conn_de, conn_jp},
},
// Continent match
"CH": [][]*mcuProxyConnection{
[]*mcuProxyConnection{conn_de, conn_jp, conn_at},
[]*mcuProxyConnection{conn_de, conn_at, conn_jp},
"CH": {
{conn_de, conn_jp, conn_at},
{conn_de, conn_at, conn_jp},
},
// Direct country match
"JP": [][]*mcuProxyConnection{
[]*mcuProxyConnection{conn_de, conn_jp, conn_at},
[]*mcuProxyConnection{conn_jp, conn_de, conn_at},
"JP": {
{conn_de, conn_jp, conn_at},
{conn_jp, conn_de, conn_at},
},
// Continent match
"CN": [][]*mcuProxyConnection{
[]*mcuProxyConnection{conn_de, conn_jp, conn_at},
[]*mcuProxyConnection{conn_jp, conn_de, conn_at},
"CN": {
{conn_de, conn_jp, conn_at},
{conn_jp, conn_de, conn_at},
},
// Partial continent match
"RU": [][]*mcuProxyConnection{
[]*mcuProxyConnection{conn_us, conn_de, conn_jp, conn_at},
[]*mcuProxyConnection{conn_de, conn_jp, conn_at, conn_us},
"RU": {
{conn_us, conn_de, conn_jp, conn_at},
{conn_de, conn_jp, conn_at, conn_us},
},
// No match
"AU": [][]*mcuProxyConnection{
[]*mcuProxyConnection{conn_us, conn_de, conn_jp, conn_at},
[]*mcuProxyConnection{conn_us, conn_de, conn_jp, conn_at},
"AU": {
{conn_us, conn_de, conn_jp, conn_at},
{conn_us, conn_de, conn_jp, conn_at},
},
}

View File

@ -24,6 +24,7 @@ package signaling
import (
"context"
"encoding/json"
"log"
"strconv"
"strings"
"sync"
@ -169,7 +170,11 @@ func (c *LoopbackNatsClient) Request(subject string, data []byte, timeout time.D
}
defer func() {
go replySubscriber.Unsubscribe()
go func() {
if err := replySubscriber.Unsubscribe(); err != nil {
log.Printf("Error closing reply subscriber %s: %s", reply, err)
}
}()
}()
msg := &nats.Msg{
Subject: subject,

View File

@ -98,7 +98,9 @@ func TestLoopbackNatsClient_Subscribe(t *testing.T) {
}
}()
for i := int32(0); i < max; i++ {
client.Publish("foo", []byte("hello"))
if err := client.Publish("foo", []byte("hello")); err != nil {
t.Error(err)
}
}
<-ch

View File

@ -46,7 +46,7 @@ import (
"gopkg.in/dgrijalva/jwt-go.v3"
"github.com/strukturag/nextcloud-spreed-signaling"
signaling "github.com/strukturag/nextcloud-spreed-signaling"
)
const (
@ -985,5 +985,5 @@ func (s *ProxyServer) statsHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.WriteHeader(http.StatusOK)
w.Write(statsData)
w.Write(statsData) // nolint
}

View File

@ -38,7 +38,7 @@ import (
"gopkg.in/dgrijalva/jwt-go.v3"
"github.com/strukturag/nextcloud-spreed-signaling"
signaling "github.com/strukturag/nextcloud-spreed-signaling"
)
const (
@ -232,7 +232,9 @@ func (t *tokensEtcd) load(config *goconf.ConfigFile, ignoreErrors bool) error {
}
func (t *tokensEtcd) Reload(config *goconf.ConfigFile) {
t.load(config, true)
if err := t.load(config, true); err != nil {
log.Printf("Error reloading etcd tokens: %s", err)
}
}
func (t *tokensEtcd) Close() {

View File

@ -103,7 +103,7 @@ func (t *tokensStatic) load(config *goconf.ConfigFile, ignoreErrors bool) error
log.Printf("No token keys loaded")
} else {
var keyIds []string
for k, _ := range tokenKeys {
for k := range tokenKeys {
keyIds = append(keyIds, k)
}
sort.Strings(keyIds)
@ -114,7 +114,9 @@ func (t *tokensStatic) load(config *goconf.ConfigFile, ignoreErrors bool) error
}
func (t *tokensStatic) Reload(config *goconf.ConfigFile) {
t.load(config, true)
if err := t.load(config, true); err != nil {
log.Printf("Error reloading static tokens: %s", err)
}
}
func (t *tokensStatic) Close() {

42
room.go
View File

@ -177,7 +177,9 @@ func (r *Room) unsubscribeBackend() {
}
go func(subscription NatsSubscription) {
subscription.Unsubscribe()
if err := subscription.Unsubscribe(); err != nil {
log.Printf("Error closing backend subscription for room %s: %s", r.Id(), err)
}
close(r.natsReceiver)
}(r.backendSubscription)
r.backendSubscription = nil
@ -330,8 +332,8 @@ func (r *Room) RemoveSession(session Session) bool {
return false
}
func (r *Room) publish(message *ServerMessage) {
r.nats.PublishMessage(GetSubjectForRoomId(r.id, r.backend), message)
func (r *Room) publish(message *ServerMessage) error {
return r.nats.PublishMessage(GetSubjectForRoomId(r.id, r.backend), message)
}
func (r *Room) UpdateProperties(properties *json.RawMessage) {
@ -351,7 +353,9 @@ func (r *Room) UpdateProperties(properties *json.RawMessage) {
Properties: r.properties,
},
}
r.publish(message)
if err := r.publish(message); err != nil {
log.Printf("Could not publish update properties message in room %s: %s", r.Id(), err)
}
}
func (r *Room) GetRoomSessionData(session Session) *RoomSessionData {
@ -377,7 +381,7 @@ func (r *Room) PublishSessionJoined(session Session, sessionData *RoomSessionDat
Target: "room",
Type: "join",
Join: []*EventServerMessageSessionEntry{
&EventServerMessageSessionEntry{
{
SessionId: sessionId,
UserId: userid,
User: session.UserData(),
@ -385,7 +389,9 @@ func (r *Room) PublishSessionJoined(session Session, sessionData *RoomSessionDat
},
},
}
r.publish(message)
if err := r.publish(message); err != nil {
log.Printf("Could not publish session joined message in room %s: %s", r.Id(), err)
}
if session.ClientType() == HelloClientTypeInternal {
r.publishUsersChangedWithInternal()
@ -408,7 +414,9 @@ func (r *Room) PublishSessionLeft(session Session) {
},
},
}
r.publish(message)
if err := r.publish(message); err != nil {
log.Printf("Could not publish session left message in room %s: %s", r.Id(), err)
}
if session.ClientType() == HelloClientTypeInternal {
r.publishUsersChangedWithInternal()
@ -539,7 +547,9 @@ func (r *Room) PublishUsersInCallChanged(changed []map[string]interface{}, users
},
},
}
r.publish(message)
if err := r.publish(message); err != nil {
log.Printf("Could not publish incall message in room %s: %s", r.Id(), err)
}
}
func (r *Room) PublishUsersChanged(changed []map[string]interface{}, users []map[string]interface{}) {
@ -558,7 +568,9 @@ func (r *Room) PublishUsersChanged(changed []map[string]interface{}, users []map
},
},
}
r.publish(message)
if err := r.publish(message); err != nil {
log.Printf("Could not publish users changed message in room %s: %s", r.Id(), err)
}
}
func (r *Room) getParticipantsUpdateMessage(users []map[string]interface{}) *ServerMessage {
@ -603,7 +615,9 @@ func (r *Room) NotifySessionChanged(session Session) {
func (r *Room) publishUsersChangedWithInternal() {
message := r.getParticipantsUpdateMessage(r.users)
r.publish(message)
if err := r.publish(message); err != nil {
log.Printf("Could not publish users changed message in room %s: %s", r.Id(), err)
}
}
func (r *Room) publishSessionFlagsChanged(session *VirtualSession) {
@ -619,7 +633,9 @@ func (r *Room) publishSessionFlagsChanged(session *VirtualSession) {
},
},
}
r.publish(message)
if err := r.publish(message); err != nil {
log.Printf("Could not publish flags changed message in room %s: %s", r.Id(), err)
}
}
func (r *Room) publishActiveSessions() {
@ -696,7 +712,9 @@ func (r *Room) publishRoomMessage(message *BackendRoomMessageRequest) {
},
},
}
r.publish(msg)
if err := r.publish(msg); err != nil {
log.Printf("Could not publish room message in room %s: %s", r.Id(), err)
}
}
func (r *Room) notifyInternalRoomDeleted() {

View File

@ -133,8 +133,12 @@ func testRoomSessions(t *testing.T, sessions RoomSessions) {
t.Errorf("Expected session id %s, got %s", s2.PublicId(), sid)
}
sessions.SetRoomSession(s1, "room-session")
sessions.SetRoomSession(s2, "room-session")
if err := sessions.SetRoomSession(s1, "room-session"); err != nil {
t.Error(err)
}
if err := sessions.SetRoomSession(s2, "room-session"); err != nil {
t.Error(err)
}
sessions.DeleteRoomSession(s1)
if sid, err := sessions.GetSessionId("room-session"); err != nil {
t.Errorf("Expected session id %s, got error %s", s2.PublicId(), err)

View File

@ -74,7 +74,7 @@ def generate_map(filename):
value = []
for continent in continents:
value.append('"%s"' % (continent))
out.write('\t\t"%s": []string{%s},\n' % (country, ', '.join(value)))
out.write('\t\t"%s": {%s},\n' % (country, ', '.join(value)))
out.write('\t}\n')
out.write(')\n')
with opentextfile(filename, 'wb') as fp:

View File

@ -108,8 +108,10 @@ func main() {
log.Fatal(err)
}
if err := runtimepprof.StartCPUProfile(f); err != nil {
log.Fatalf("Error writing CPU profile to %s: %s", *cpuprofile, err)
}
log.Printf("Writing CPU profile to %s ...\n", *cpuprofile)
runtimepprof.StartCPUProfile(f)
defer runtimepprof.StopCPUProfile()
}
@ -122,7 +124,9 @@ func main() {
defer func() {
log.Printf("Writing Memory profile to %s ...\n", *memprofile)
runtime.GC()
runtimepprof.WriteHeapProfile(f)
if err := runtimepprof.WriteHeapProfile(f); err != nil {
log.Printf("Error writing Memory profile to %s: %s", *memprofile, err)
}
}()
}
@ -318,9 +322,7 @@ func main() {
}
loop:
for {
select {
case sig := <-sigChan:
for sig := range sigChan {
switch sig {
case os.Interrupt:
log.Println("Interrupted")
@ -335,4 +337,3 @@ loop:
}
}
}
}

View File

@ -58,14 +58,6 @@ func getWebsocketUrl(url string) string {
}
}
func getPrivateSessionIdData(h *Hub, privateId string) *SessionIdData {
decodedPrivate := h.decodeSessionId(privateId, privateSessionName)
if decodedPrivate == nil {
panic("invalid private session id")
}
return decodedPrivate
}
func getPubliceSessionIdData(h *Hub, publicId string) *SessionIdData {
decodedPublic := h.decodeSessionId(publicId, publicSessionName)
if decodedPublic == nil {
@ -74,30 +66,6 @@ func getPubliceSessionIdData(h *Hub, publicId string) *SessionIdData {
return decodedPublic
}
func privateToPublicSessionId(h *Hub, privateId string) string {
decodedPrivate := getPrivateSessionIdData(h, privateId)
if decodedPrivate == nil {
panic("invalid private session id")
}
encodedPublic, err := h.encodeSessionId(decodedPrivate, publicSessionName)
if err != nil {
panic(err)
}
return encodedPublic
}
func equalPublicAndPrivateSessionId(h *Hub, publicId, privateId string) bool {
decodedPublic := h.decodeSessionId(publicId, publicSessionName)
if decodedPublic == nil {
panic("invalid public session id")
}
decodedPrivate := h.decodeSessionId(privateId, privateSessionName)
if decodedPrivate == nil {
panic("invalid private session id")
}
return decodedPublic.Sid == decodedPrivate.Sid
}
func checkUnexpectedClose(err error) error {
if err != nil && websocket.IsUnexpectedCloseError(err,
websocket.CloseNormalClosure,
@ -254,12 +222,12 @@ func NewTestClient(t *testing.T, server *httptest.Server, hub *Hub) *TestClient
}
func (c *TestClient) CloseWithBye() {
c.SendBye()
c.SendBye() // nolint
c.Close()
}
func (c *TestClient) Close() {
c.conn.WriteMessage(websocket.CloseMessage, []byte{})
c.conn.WriteMessage(websocket.CloseMessage, []byte{}) // nolint
c.conn.Close()
// Drain any entries in the channels to terminate the read goroutine.
@ -374,7 +342,7 @@ func (c *TestClient) SendHelloClient(userid string) error {
func (c *TestClient) SendHelloInternal() error {
random := newRandomString(48)
mac := hmac.New(sha256.New, testInternalSecret)
mac.Write([]byte(random))
mac.Write([]byte(random)) // nolint
token := hex.EncodeToString(mac.Sum(nil))
backend := c.server.URL

View File

@ -205,7 +205,9 @@ func TestVirtualSession(t *testing.T) {
}
data := "from-client-to-virtual"
client.SendMessage(recipient, data)
if err := client.SendMessage(recipient, data); err != nil {
t.Fatal(err)
}
msg2, err = clientInternal.RunUntilMessage(ctx)
if err != nil {