Xray-core/transport/internet/websocket/hub.go

165 lines
4.6 KiB
Go
Raw Permalink Normal View History

2020-11-25 11:01:53 +00:00
package websocket
import (
2021-03-14 07:10:10 +00:00
"bytes"
2020-11-25 11:01:53 +00:00
"context"
"crypto/tls"
2021-03-14 07:10:10 +00:00
"encoding/base64"
"io"
2020-11-25 11:01:53 +00:00
"net/http"
2021-03-23 09:25:35 +00:00
"strings"
2020-11-25 11:01:53 +00:00
"sync"
"time"
"github.com/gorilla/websocket"
2020-12-04 01:36:16 +00:00
"github.com/xtls/xray-core/common"
"github.com/xtls/xray-core/common/errors"
2020-12-04 01:36:16 +00:00
"github.com/xtls/xray-core/common/net"
http_proto "github.com/xtls/xray-core/common/protocol/http"
"github.com/xtls/xray-core/transport/internet"
v2tls "github.com/xtls/xray-core/transport/internet/tls"
2020-11-25 11:01:53 +00:00
)
type requestHandler struct {
2024-03-29 06:27:02 +00:00
host string
2020-11-25 11:01:53 +00:00
path string
ln *Listener
}
2021-03-23 09:25:35 +00:00
var replacer = strings.NewReplacer("+", "-", "/", "_", "=", "")
2020-11-25 11:01:53 +00:00
var upgrader = &websocket.Upgrader{
ReadBufferSize: 0,
WriteBufferSize: 0,
2020-11-25 11:01:53 +00:00
HandshakeTimeout: time.Second * 4,
CheckOrigin: func(r *http.Request) bool {
return true
},
}
func (h *requestHandler) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
if len(h.host) > 0 && !internet.IsValidHTTPHost(request.Host, h.host) {
errors.LogInfo(context.Background(), "failed to validate host, request:", request.Host, ", config:", h.host)
2024-03-29 06:27:02 +00:00
writer.WriteHeader(http.StatusNotFound)
return
}
2020-11-25 11:01:53 +00:00
if request.URL.Path != h.path {
errors.LogInfo(context.Background(), "failed to validate path, request:", request.URL.Path, ", config:", h.path)
2020-11-25 11:01:53 +00:00
writer.WriteHeader(http.StatusNotFound)
return
}
2021-03-23 09:25:35 +00:00
var extraReader io.Reader
2021-10-19 16:57:14 +00:00
responseHeader := http.Header{}
2021-03-23 09:25:35 +00:00
if str := request.Header.Get("Sec-WebSocket-Protocol"); str != "" {
if ed, err := base64.RawURLEncoding.DecodeString(replacer.Replace(str)); err == nil && len(ed) > 0 {
extraReader = bytes.NewReader(ed)
responseHeader.Set("Sec-WebSocket-Protocol", str)
}
}
conn, err := upgrader.Upgrade(writer, request, responseHeader)
2020-11-25 11:01:53 +00:00
if err != nil {
errors.LogInfoInner(context.Background(), err, "failed to convert to WebSocket connection")
2020-11-25 11:01:53 +00:00
return
}
forwardedAddrs := http_proto.ParseXForwardedFor(request.Header)
remoteAddr := conn.RemoteAddr()
if len(forwardedAddrs) > 0 && forwardedAddrs[0].Family().IsIP() {
remoteAddr = &net.TCPAddr{
IP: forwardedAddrs[0].IP(),
Port: int(0),
}
}
h.ln.addConn(NewConnection(conn, remoteAddr, extraReader, h.ln.config.HeartbeatPeriod))
2020-11-25 11:01:53 +00:00
}
type Listener struct {
sync.Mutex
server http.Server
listener net.Listener
config *Config
addConn internet.ConnHandler
}
func ListenWS(ctx context.Context, address net.Address, port net.Port, streamSettings *internet.MemoryStreamConfig, addConn internet.ConnHandler) (internet.Listener, error) {
l := &Listener{
addConn: addConn,
}
wsSettings := streamSettings.ProtocolSettings.(*Config)
l.config = wsSettings
if l.config != nil {
if streamSettings.SocketSettings == nil {
streamSettings.SocketSettings = &internet.SocketConfig{}
}
2022-05-18 07:29:01 +00:00
streamSettings.SocketSettings.AcceptProxyProtocol = l.config.AcceptProxyProtocol || streamSettings.SocketSettings.AcceptProxyProtocol
2020-11-25 11:01:53 +00:00
}
var listener net.Listener
var err error
2021-10-19 16:57:14 +00:00
if port == net.Port(0) { // unix
2020-11-25 11:01:53 +00:00
listener, err = internet.ListenSystem(ctx, &net.UnixAddr{
Name: address.Domain(),
Net: "unix",
}, streamSettings.SocketSettings)
if err != nil {
return nil, errors.New("failed to listen unix domain socket(for WS) on ", address).Base(err)
2020-11-25 11:01:53 +00:00
}
errors.LogInfo(ctx, "listening unix domain socket(for WS) on ", address)
2021-10-19 16:57:14 +00:00
} else { // tcp
2020-11-25 11:01:53 +00:00
listener, err = internet.ListenSystem(ctx, &net.TCPAddr{
IP: address.IP(),
Port: int(port),
}, streamSettings.SocketSettings)
if err != nil {
return nil, errors.New("failed to listen TCP(for WS) on ", address, ":", port).Base(err)
2020-11-25 11:01:53 +00:00
}
errors.LogInfo(ctx, "listening TCP(for WS) on ", address, ":", port)
2020-11-25 11:01:53 +00:00
}
if streamSettings.SocketSettings != nil && streamSettings.SocketSettings.AcceptProxyProtocol {
errors.LogWarning(ctx, "accepting PROXY protocol")
2020-11-25 11:01:53 +00:00
}
if config := v2tls.ConfigFromStreamSettings(streamSettings); config != nil {
if tlsConfig := config.GetTLSConfig(); tlsConfig != nil {
listener = tls.NewListener(listener, tlsConfig)
}
}
l.listener = listener
l.server = http.Server{
Handler: &requestHandler{
2024-03-29 06:27:02 +00:00
host: wsSettings.Host,
2020-11-25 11:01:53 +00:00
path: wsSettings.GetNormalizedPath(),
ln: l,
},
ReadHeaderTimeout: time.Second * 4,
MaxHeaderBytes: 8192,
2020-11-25 11:01:53 +00:00
}
go func() {
if err := l.server.Serve(l.listener); err != nil {
errors.LogWarningInner(ctx, err, "failed to serve http for WebSocket")
2020-11-25 11:01:53 +00:00
}
}()
return l, err
}
// Addr implements net.Listener.Addr().
func (ln *Listener) Addr() net.Addr {
return ln.listener.Addr()
}
// Close implements net.Listener.Close().
func (ln *Listener) Close() error {
return ln.listener.Close()
}
func init() {
common.Must(internet.RegisterTransportListener(protocolName, ListenWS))
}