[relay-server] Use X-Real-IP in case of reverse proxy (#2848)

* Use X-Real-IP in case of reverse proxy

* Use sprintf
This commit is contained in:
Zoltan Papp 2024-11-07 16:14:53 +01:00 committed by GitHub
parent 509e184e10
commit cbf500024f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -63,13 +63,14 @@ func (l *Listener) Shutdown(ctx context.Context) error {
} }
func (l *Listener) onAccept(w http.ResponseWriter, r *http.Request) { func (l *Listener) onAccept(w http.ResponseWriter, r *http.Request) {
connRemoteAddr := remoteAddr(r)
wsConn, err := websocket.Accept(w, r, nil) wsConn, err := websocket.Accept(w, r, nil)
if err != nil { if err != nil {
log.Errorf("failed to accept ws connection from %s: %s", r.RemoteAddr, err) log.Errorf("failed to accept ws connection from %s: %s", connRemoteAddr, err)
return return
} }
rAddr, err := net.ResolveTCPAddr("tcp", r.RemoteAddr) rAddr, err := net.ResolveTCPAddr("tcp", connRemoteAddr)
if err != nil { if err != nil {
err = wsConn.Close(websocket.StatusInternalError, "internal error") err = wsConn.Close(websocket.StatusInternalError, "internal error")
if err != nil { if err != nil {
@ -90,3 +91,10 @@ func (l *Listener) onAccept(w http.ResponseWriter, r *http.Request) {
conn := NewConn(wsConn, lAddr, rAddr) conn := NewConn(wsConn, lAddr, rAddr)
l.acceptFn(conn) l.acceptFn(conn)
} }
func remoteAddr(r *http.Request) string {
if r.Header.Get("X-Real-Ip") == "" || r.Header.Get("X-Real-Port") == "" {
return r.RemoteAddr
}
return fmt.Sprintf("%s:%s", r.Header.Get("X-Real-Ip"), r.Header.Get("X-Real-Port"))
}