安全Websocket协议问题

时间:2019-10-16 16:04:46

标签: go websocket protocols gorilla

在使用WebSockets协议时,Go遇到了问题。如果我连接到我的API,一切正常。如果我添加“协议”(例如“ Hey”),它将开始循环多次,并由于出现错误*github.com/gorilla/websocket.CloseError:“代码1006,文本意外EOF”而结束。

当我在连接中发送Sec-Websocket-Protocol时,我绝对不明白为什么会这样。

有我的代码:

main.go

package main

import (
    "fmt"
    "github.com/golang/glog"
    "github.com/grpc-ecosystem/grpc-gateway/runtime"
    stacktracer "gitlab.com/eyes-eyes/internals-stacktracer"
    "gitlab.com/eyesbank/go-web-sockets-server/handlers"
    "net/http"
)

const webSocketsAddr = "0.0.0.0:8082"

// main is the starting point of the current micro service.
func main() {

    // Setting the service name
    stacktracer.SetServiceName("Hello 'X' (Web Sockets)")

    // Initializing the HTTP errors handling
    runtime.HTTPError = stacktracer.DefaultHTTPError

    if err := RunWebSocketsServer(); err != nil {
        glog.Fatal(err)
    }

}

//
// WebSocket
//

func RunWebSocketsServer() error {

    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        handlers.HandleUserSocket(w, r)
    })

    fmt.Println(webSocketsAddr)

    return http.ListenAndServe(webSocketsAddr, nil)
}

func RunWebSocketsTLSServer() error {

    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        handlers.HandleUserSocket(w, r)
    })

    fmt.Println(webSocketsAddr)

    return http.ListenAndServeTLS(webSocketsAddr, "server.crt", "server.key", nil)
}

handler.go

package handlers

import (
    "fmt"
    "github.com/gorilla/websocket"
    stacktracer "gitlab.com/eyes-eyes/internals-stacktracer"
    "gitlab.com/eyes-eyes/internals-stacktracer/structs"
    "go.mongodb.org/mongo-driver/bson/primitive"
    "log"
    "net/http"
)

var upgrader = websocket.Upgrader{
    ReadBufferSize:  1024,
    WriteBufferSize: 1024,
    CheckOrigin: func(r *http.Request) bool {
        return true
    },
}

func HandleUserSocket(w http.ResponseWriter, r *http.Request) {

    var userID = primitive.NewObjectID()
    conn, err := upgrader.Upgrade(w, r, nil) // error ignored for sake of simplicity
    if err != nil {
        log.Fatalf("failed to listen: %v", err)
    } else {
        WriteOutgoingMessage(conn, "Welcome "+userID.Hex())
    }

    fmt.Println(r.Header["Sec-Websocket-Protocol"])
    if len(r.Header["Sec-Websocket-Protocol"]) > 0 {
        WriteOutgoingMessage(conn, userID.Hex() + " " + string(r.Header["Sec-Websocket-Protocol"][0]))
    }

    for {
        // Read message from browser
        _, msg, err := conn.ReadMessage()
        if err != nil {
            if err != nil {
                switch err.(type) {
                case *websocket.CloseError:
                    fmt.Println("disconnected")
                    return
                default:
                    _ = conn.WriteMessage(websocket.TextMessage, []byte(err.Error()))
                    fmt.Println(err.Error())
                    fmt.Println("disconnected")
                    return
                }
            }
        }

        if msg != nil {
            WriteOutgoingMessage(conn, userID.Hex() + " " + string(msg))
        }
    }
}

func WriteOutgoingMessage(conn *websocket.Conn, message string) *structs.StackTrace {

    // Write message back to browser
    if err := conn.WriteMessage(websocket.TextMessage, []byte("Got: \""+message+"\"")); err != nil {
        err = conn.WriteMessage(websocket.TextMessage, []byte(err.Error()))
        if err != nil {
            return stacktracer.NewStackTrace(500, err.Error(), nil)
        }
    }

    return nil

}

1 个答案:

答案 0 :(得分:1)

如果客户端请求子协议,而服务器不同意其中一个子协议,则要求客户端关闭连接。客户端使用Sec-Websocket-Protocol标头请求一个或多个子协议。服务器使用Sec-Websocket-Protocol响应标头来同意协议。有关此主题的更多信息,请参见RFC

通过同意客户端请求的一种协议来解决问题。有两种方法可以做到这一点。

首先是使用内置的协议协商功能:

var upgrader = websocket.Upgrader{
    ReadBufferSize:  1024,
    WriteBufferSize: 1024,
    Subprotocols: []string{ "hey" },  // <-- add this line
    CheckOrigin: func(r *http.Request) bool {
        return true
    },
}

第二个是在调用Upgrade之前在应用程序代码中协商协议。调用websocket.Subprotocols获取请求的协议,选择其中一个协议,然后在“升级”的标头参数中指定该协议。

h := http.Header{}
for _, sub := range websocket.Subprotocols(req) {
   if sub == "hey" {
      h.Set("Sec-Websocket-Protocol", "hey")
      break
   }
}
conn, err := upgrader.Upgrade(w, r, h)

与此问题分开,应用程序应在成功升级后defer conn.Close()

此外,可以简化错误处理逻辑。如果ReadMessage返回任何错误,应用程序应退出读取循环。连接错误后写消息毫无意义。 ReadMessage方法成功返回不为零的消息。

for {
    // Read message from browser
    _, msg, err := conn.ReadMessage()
    if err != nil {
         fmt.Println(err.Error())
          fmt.Println("disconnected")
          return
    }
    WriteOutgoingMessage(conn, userID.Hex() + " " + string(msg))
}