2018-10-28 23:46:32 +08:00
|
|
|
package vmess
|
|
|
|
|
|
|
|
import (
|
2021-08-22 00:25:29 +08:00
|
|
|
"bytes"
|
|
|
|
"context"
|
2023-11-03 11:02:19 +08:00
|
|
|
"crypto/sha1"
|
2018-11-04 21:36:20 +08:00
|
|
|
"crypto/tls"
|
2021-08-22 00:25:29 +08:00
|
|
|
"encoding/base64"
|
2023-01-16 09:42:03 +08:00
|
|
|
"encoding/binary"
|
2021-08-22 00:25:29 +08:00
|
|
|
"errors"
|
2018-10-28 23:46:32 +08:00
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"net"
|
2018-12-11 00:25:05 +08:00
|
|
|
"net/http"
|
2018-11-04 21:36:20 +08:00
|
|
|
"net/url"
|
2021-08-22 16:03:46 +08:00
|
|
|
"strconv"
|
2018-10-28 23:46:32 +08:00
|
|
|
"strings"
|
|
|
|
"time"
|
|
|
|
|
2023-01-16 10:50:31 +08:00
|
|
|
"github.com/Dreamacro/clash/common/buf"
|
|
|
|
N "github.com/Dreamacro/clash/common/net"
|
2023-02-07 16:08:59 +08:00
|
|
|
tlsC "github.com/Dreamacro/clash/component/tls"
|
2023-11-03 11:02:19 +08:00
|
|
|
"github.com/Dreamacro/clash/log"
|
2023-03-06 18:10:14 +08:00
|
|
|
|
2023-10-06 17:44:36 +08:00
|
|
|
"github.com/gobwas/ws"
|
|
|
|
"github.com/gobwas/ws/wsutil"
|
2023-03-06 18:10:14 +08:00
|
|
|
"github.com/zhangyunhao116/fastrand"
|
2018-10-28 23:46:32 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
type websocketConn struct {
|
2023-10-06 17:44:36 +08:00
|
|
|
net.Conn
|
|
|
|
state ws.State
|
|
|
|
reader *wsutil.Reader
|
|
|
|
controlHandler wsutil.FrameHandlerFunc
|
2019-12-05 14:12:29 +08:00
|
|
|
|
2023-01-16 10:50:31 +08:00
|
|
|
rawWriter N.ExtendedWriter
|
2018-10-28 23:46:32 +08:00
|
|
|
}
|
2021-10-10 23:44:09 +08:00
|
|
|
|
2021-08-22 00:25:29 +08:00
|
|
|
type websocketWithEarlyDataConn struct {
|
|
|
|
net.Conn
|
2023-01-16 10:50:31 +08:00
|
|
|
wsWriter N.ExtendedWriter
|
2021-08-22 00:25:29 +08:00
|
|
|
underlay net.Conn
|
|
|
|
closed bool
|
|
|
|
dialed chan bool
|
|
|
|
cancel context.CancelFunc
|
|
|
|
ctx context.Context
|
|
|
|
config *WebsocketConfig
|
|
|
|
}
|
2018-10-28 23:46:32 +08:00
|
|
|
|
2019-02-11 15:25:10 +08:00
|
|
|
type WebsocketConfig struct {
|
2021-08-22 00:25:29 +08:00
|
|
|
Host string
|
|
|
|
Port string
|
|
|
|
Path string
|
|
|
|
Headers http.Header
|
|
|
|
TLS bool
|
2021-10-16 20:19:59 +08:00
|
|
|
TLSConfig *tls.Config
|
2021-08-22 00:25:29 +08:00
|
|
|
MaxEarlyData int
|
|
|
|
EarlyDataHeaderName string
|
2023-02-01 22:16:06 +08:00
|
|
|
ClientFingerprint string
|
2023-11-02 11:11:19 +08:00
|
|
|
V2rayHttpUpgrade bool
|
2018-11-04 21:36:20 +08:00
|
|
|
}
|
|
|
|
|
2018-10-28 23:46:32 +08:00
|
|
|
// Read implements net.Conn.Read()
|
2023-10-06 17:44:36 +08:00
|
|
|
// modify from gobwas/ws/wsutil.readData
|
|
|
|
func (wsc *websocketConn) Read(b []byte) (n int, err error) {
|
|
|
|
var header ws.Header
|
2018-10-28 23:46:32 +08:00
|
|
|
for {
|
2023-10-06 17:44:36 +08:00
|
|
|
n, err = wsc.reader.Read(b)
|
|
|
|
// in gobwas/ws: "The error is io.EOF only if all of message bytes were read."
|
|
|
|
// but maybe next frame still have data, so drop it
|
|
|
|
if errors.Is(err, io.EOF) {
|
|
|
|
err = nil
|
|
|
|
}
|
|
|
|
if !errors.Is(err, wsutil.ErrNoFrameAdvance) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
header, err = wsc.reader.NextFrame()
|
2018-10-28 23:46:32 +08:00
|
|
|
if err != nil {
|
2023-10-06 17:44:36 +08:00
|
|
|
return
|
2018-10-28 23:46:32 +08:00
|
|
|
}
|
2023-10-06 17:44:36 +08:00
|
|
|
if header.OpCode.IsControl() {
|
|
|
|
err = wsc.controlHandler(header, wsc.reader)
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
if header.OpCode&(ws.OpBinary|ws.OpText) == 0 {
|
|
|
|
err = wsc.reader.Discard()
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
2018-10-28 23:46:32 +08:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Write implements io.Writer.
|
2023-10-06 17:44:36 +08:00
|
|
|
func (wsc *websocketConn) Write(b []byte) (n int, err error) {
|
|
|
|
err = wsutil.WriteMessage(wsc.Conn, wsc.state, ws.OpBinary, b)
|
|
|
|
if err != nil {
|
|
|
|
return
|
2018-10-28 23:46:32 +08:00
|
|
|
}
|
2023-10-06 17:44:36 +08:00
|
|
|
n = len(b)
|
|
|
|
return
|
2018-10-28 23:46:32 +08:00
|
|
|
}
|
|
|
|
|
2023-01-16 09:42:03 +08:00
|
|
|
func (wsc *websocketConn) WriteBuffer(buffer *buf.Buffer) error {
|
|
|
|
var payloadBitLength int
|
|
|
|
dataLen := buffer.Len()
|
|
|
|
data := buffer.Bytes()
|
|
|
|
if dataLen < 126 {
|
|
|
|
payloadBitLength = 1
|
|
|
|
} else if dataLen < 65536 {
|
|
|
|
payloadBitLength = 3
|
|
|
|
} else {
|
|
|
|
payloadBitLength = 9
|
|
|
|
}
|
|
|
|
|
|
|
|
var headerLen int
|
|
|
|
headerLen += 1 // FIN / RSV / OPCODE
|
|
|
|
headerLen += payloadBitLength
|
2023-10-07 16:45:15 +08:00
|
|
|
if wsc.state.ClientSide() {
|
|
|
|
headerLen += 4 // MASK KEY
|
|
|
|
}
|
2023-01-16 09:42:03 +08:00
|
|
|
|
|
|
|
header := buffer.ExtendHeader(headerLen)
|
2023-10-06 17:44:36 +08:00
|
|
|
header[0] = byte(ws.OpBinary) | 0x80
|
2023-10-07 16:45:15 +08:00
|
|
|
if wsc.state.ClientSide() {
|
|
|
|
header[1] = 1 << 7
|
|
|
|
} else {
|
|
|
|
header[1] = 0
|
|
|
|
}
|
2023-01-16 09:42:03 +08:00
|
|
|
|
|
|
|
if dataLen < 126 {
|
|
|
|
header[1] |= byte(dataLen)
|
|
|
|
} else if dataLen < 65536 {
|
|
|
|
header[1] |= 126
|
|
|
|
binary.BigEndian.PutUint16(header[2:], uint16(dataLen))
|
|
|
|
} else {
|
|
|
|
header[1] |= 127
|
|
|
|
binary.BigEndian.PutUint64(header[2:], uint64(dataLen))
|
|
|
|
}
|
|
|
|
|
2023-10-06 17:44:36 +08:00
|
|
|
if wsc.state.ClientSide() {
|
|
|
|
maskKey := fastrand.Uint32()
|
|
|
|
binary.LittleEndian.PutUint32(header[1+payloadBitLength:], maskKey)
|
|
|
|
N.MaskWebSocket(maskKey, data)
|
|
|
|
}
|
2023-01-16 09:42:03 +08:00
|
|
|
|
|
|
|
return wsc.rawWriter.WriteBuffer(buffer)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (wsc *websocketConn) FrontHeadroom() int {
|
|
|
|
return 14
|
|
|
|
}
|
|
|
|
|
|
|
|
func (wsc *websocketConn) Upstream() any {
|
2023-10-06 17:44:36 +08:00
|
|
|
return wsc.Conn
|
2023-01-16 09:42:03 +08:00
|
|
|
}
|
|
|
|
|
2018-10-28 23:46:32 +08:00
|
|
|
func (wsc *websocketConn) Close() error {
|
2023-10-06 17:44:36 +08:00
|
|
|
_ = wsc.Conn.SetWriteDeadline(time.Now().Add(time.Second * 5))
|
|
|
|
_ = wsutil.WriteMessage(wsc.Conn, wsc.state, ws.OpClose, ws.NewCloseFrameBody(ws.StatusNormalClosure, ""))
|
|
|
|
_ = wsc.Conn.Close()
|
2018-10-28 23:46:32 +08:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-08-22 00:25:29 +08:00
|
|
|
func (wsedc *websocketWithEarlyDataConn) Dial(earlyData []byte) error {
|
2021-08-22 16:16:45 +08:00
|
|
|
base64DataBuf := &bytes.Buffer{}
|
|
|
|
base64EarlyDataEncoder := base64.NewEncoder(base64.RawURLEncoding, base64DataBuf)
|
2021-08-22 00:25:29 +08:00
|
|
|
|
2021-08-22 16:16:45 +08:00
|
|
|
earlyDataBuf := bytes.NewBuffer(earlyData)
|
|
|
|
if _, err := base64EarlyDataEncoder.Write(earlyDataBuf.Next(wsedc.config.MaxEarlyData)); err != nil {
|
2023-05-18 13:15:08 +08:00
|
|
|
return fmt.Errorf("failed to encode early data: %w", err)
|
2021-08-22 00:25:29 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
if errc := base64EarlyDataEncoder.Close(); errc != nil {
|
2023-05-18 13:15:08 +08:00
|
|
|
return fmt.Errorf("failed to encode early data tail: %w", errc)
|
2021-08-22 00:25:29 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
var err error
|
2023-05-18 13:15:08 +08:00
|
|
|
if wsedc.Conn, err = streamWebsocketConn(wsedc.ctx, wsedc.underlay, wsedc.config, base64DataBuf); err != nil {
|
2021-08-22 00:25:29 +08:00
|
|
|
wsedc.Close()
|
2023-05-18 13:15:08 +08:00
|
|
|
return fmt.Errorf("failed to dial WebSocket: %w", err)
|
2021-08-22 00:25:29 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
wsedc.dialed <- true
|
2023-01-16 10:50:31 +08:00
|
|
|
wsedc.wsWriter = N.NewExtendedWriter(wsedc.Conn)
|
2021-08-22 16:16:45 +08:00
|
|
|
if earlyDataBuf.Len() != 0 {
|
|
|
|
_, err = wsedc.Conn.Write(earlyDataBuf.Bytes())
|
2021-08-22 00:25:29 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
func (wsedc *websocketWithEarlyDataConn) Write(b []byte) (int, error) {
|
|
|
|
if wsedc.closed {
|
|
|
|
return 0, io.ErrClosedPipe
|
|
|
|
}
|
|
|
|
if wsedc.Conn == nil {
|
|
|
|
if err := wsedc.Dial(b); err != nil {
|
|
|
|
return 0, err
|
|
|
|
}
|
|
|
|
return len(b), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return wsedc.Conn.Write(b)
|
|
|
|
}
|
|
|
|
|
2023-01-16 09:42:03 +08:00
|
|
|
func (wsedc *websocketWithEarlyDataConn) WriteBuffer(buffer *buf.Buffer) error {
|
|
|
|
if wsedc.closed {
|
|
|
|
return io.ErrClosedPipe
|
|
|
|
}
|
|
|
|
if wsedc.Conn == nil {
|
|
|
|
if err := wsedc.Dial(buffer.Bytes()); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return wsedc.wsWriter.WriteBuffer(buffer)
|
|
|
|
}
|
|
|
|
|
2021-08-22 00:25:29 +08:00
|
|
|
func (wsedc *websocketWithEarlyDataConn) Read(b []byte) (int, error) {
|
|
|
|
if wsedc.closed {
|
|
|
|
return 0, io.ErrClosedPipe
|
|
|
|
}
|
|
|
|
if wsedc.Conn == nil {
|
|
|
|
select {
|
|
|
|
case <-wsedc.ctx.Done():
|
|
|
|
return 0, io.ErrUnexpectedEOF
|
|
|
|
case <-wsedc.dialed:
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return wsedc.Conn.Read(b)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (wsedc *websocketWithEarlyDataConn) Close() error {
|
|
|
|
wsedc.closed = true
|
|
|
|
wsedc.cancel()
|
|
|
|
if wsedc.Conn == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return wsedc.Conn.Close()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (wsedc *websocketWithEarlyDataConn) LocalAddr() net.Addr {
|
|
|
|
if wsedc.Conn == nil {
|
|
|
|
return wsedc.underlay.LocalAddr()
|
|
|
|
}
|
|
|
|
return wsedc.Conn.LocalAddr()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (wsedc *websocketWithEarlyDataConn) RemoteAddr() net.Addr {
|
|
|
|
if wsedc.Conn == nil {
|
|
|
|
return wsedc.underlay.RemoteAddr()
|
|
|
|
}
|
|
|
|
return wsedc.Conn.RemoteAddr()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (wsedc *websocketWithEarlyDataConn) SetDeadline(t time.Time) error {
|
|
|
|
if err := wsedc.SetReadDeadline(t); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return wsedc.SetWriteDeadline(t)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (wsedc *websocketWithEarlyDataConn) SetReadDeadline(t time.Time) error {
|
|
|
|
if wsedc.Conn == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return wsedc.Conn.SetReadDeadline(t)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (wsedc *websocketWithEarlyDataConn) SetWriteDeadline(t time.Time) error {
|
|
|
|
if wsedc.Conn == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return wsedc.Conn.SetWriteDeadline(t)
|
|
|
|
}
|
|
|
|
|
2023-02-27 00:26:49 +08:00
|
|
|
func (wsedc *websocketWithEarlyDataConn) FrontHeadroom() int {
|
|
|
|
return 14
|
2023-02-18 13:58:08 +08:00
|
|
|
}
|
|
|
|
|
2023-01-16 09:42:03 +08:00
|
|
|
func (wsedc *websocketWithEarlyDataConn) Upstream() any {
|
2023-02-27 00:26:49 +08:00
|
|
|
return wsedc.underlay
|
|
|
|
}
|
|
|
|
|
|
|
|
//func (wsedc *websocketWithEarlyDataConn) LazyHeadroom() bool {
|
|
|
|
// return wsedc.Conn == nil
|
|
|
|
//}
|
|
|
|
//
|
|
|
|
//func (wsedc *websocketWithEarlyDataConn) Upstream() any {
|
|
|
|
// if wsedc.Conn == nil { // ensure return a nil interface not an interface with nil value
|
|
|
|
// return nil
|
|
|
|
// }
|
|
|
|
// return wsedc.Conn
|
|
|
|
//}
|
|
|
|
|
|
|
|
func (wsedc *websocketWithEarlyDataConn) NeedHandshake() bool {
|
|
|
|
return wsedc.Conn == nil
|
2023-01-16 09:42:03 +08:00
|
|
|
}
|
|
|
|
|
2021-08-22 00:25:29 +08:00
|
|
|
func streamWebsocketWithEarlyDataConn(conn net.Conn, c *WebsocketConfig) (net.Conn, error) {
|
|
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
|
|
conn = &websocketWithEarlyDataConn{
|
|
|
|
dialed: make(chan bool, 1),
|
|
|
|
cancel: cancel,
|
|
|
|
ctx: ctx,
|
|
|
|
underlay: conn,
|
|
|
|
config: c,
|
|
|
|
}
|
2023-04-17 00:23:12 +08:00
|
|
|
// websocketWithEarlyDataConn can't correct handle Deadline
|
|
|
|
// it will not apply the already set Deadline after Dial()
|
|
|
|
// so call N.NewDeadlineConn to add a safe wrapper
|
|
|
|
return N.NewDeadlineConn(conn), nil
|
2021-08-22 00:25:29 +08:00
|
|
|
}
|
|
|
|
|
2023-05-18 13:15:08 +08:00
|
|
|
func streamWebsocketConn(ctx context.Context, conn net.Conn, c *WebsocketConfig, earlyData *bytes.Buffer) (net.Conn, error) {
|
2023-11-03 11:02:19 +08:00
|
|
|
u, err := url.Parse(c.Path)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("parse url %s error: %w", c.Path, err)
|
2018-11-04 21:36:20 +08:00
|
|
|
}
|
2023-11-03 11:02:19 +08:00
|
|
|
|
2023-11-03 12:04:22 +08:00
|
|
|
uri := url.URL{
|
|
|
|
Scheme: "ws",
|
|
|
|
Host: net.JoinHostPort(c.Host, c.Port),
|
|
|
|
Path: u.Path,
|
|
|
|
RawQuery: u.RawQuery,
|
|
|
|
}
|
|
|
|
|
2019-02-11 15:25:10 +08:00
|
|
|
if c.TLS {
|
2023-11-03 12:04:22 +08:00
|
|
|
uri.Scheme = "wss"
|
|
|
|
config := c.TLSConfig
|
|
|
|
if config == nil { // The config cannot be nil
|
|
|
|
config = &tls.Config{NextProtos: []string{"http/1.1"}}
|
|
|
|
}
|
|
|
|
if config.ServerName == "" && !config.InsecureSkipVerify { // users must set either ServerName or InsecureSkipVerify in the config.
|
|
|
|
config = config.Clone()
|
|
|
|
config.ServerName = uri.Host
|
|
|
|
}
|
|
|
|
|
2023-02-01 22:16:06 +08:00
|
|
|
if len(c.ClientFingerprint) != 0 {
|
2023-02-07 16:08:59 +08:00
|
|
|
if fingerprint, exists := tlsC.GetFingerprint(c.ClientFingerprint); exists {
|
2023-11-03 12:04:22 +08:00
|
|
|
utlsConn := tlsC.UClient(conn, config, fingerprint)
|
2023-11-03 11:02:19 +08:00
|
|
|
if err = utlsConn.BuildWebsocketHandshakeState(); err != nil {
|
2023-10-06 17:44:36 +08:00
|
|
|
return nil, fmt.Errorf("parse url %s error: %w", c.Path, err)
|
|
|
|
}
|
2023-11-03 11:02:19 +08:00
|
|
|
conn = utlsConn
|
2023-02-01 22:16:06 +08:00
|
|
|
}
|
2023-11-03 11:02:19 +08:00
|
|
|
} else {
|
2023-11-03 12:04:22 +08:00
|
|
|
conn = tls.Client(conn, config)
|
2023-02-01 22:16:06 +08:00
|
|
|
}
|
2018-11-04 21:36:20 +08:00
|
|
|
|
2023-11-03 11:02:19 +08:00
|
|
|
if tlsConn, ok := conn.(interface {
|
|
|
|
HandshakeContext(ctx context.Context) error
|
|
|
|
}); ok {
|
|
|
|
if err = tlsConn.HandshakeContext(ctx); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
2022-07-10 14:56:34 +08:00
|
|
|
}
|
|
|
|
|
2023-11-03 11:02:19 +08:00
|
|
|
request := &http.Request{
|
|
|
|
Method: http.MethodGet,
|
|
|
|
URL: &uri,
|
|
|
|
Header: c.Headers.Clone(),
|
|
|
|
Host: c.Host,
|
2023-11-02 11:11:19 +08:00
|
|
|
}
|
|
|
|
|
2023-11-03 11:02:19 +08:00
|
|
|
request.Header.Set("Connection", "Upgrade")
|
|
|
|
request.Header.Set("Upgrade", "websocket")
|
|
|
|
|
|
|
|
if host := request.Header.Get("Host"); host != "" {
|
|
|
|
// For client requests, Host optionally overrides the Host
|
|
|
|
// header to send. If empty, the Request.Write method uses
|
|
|
|
// the value of URL.Host. Host may contain an international
|
|
|
|
// domain name.
|
|
|
|
request.Host = host
|
|
|
|
}
|
|
|
|
request.Header.Del("Host")
|
|
|
|
|
|
|
|
var nonce string
|
|
|
|
if !c.V2rayHttpUpgrade {
|
|
|
|
const nonceKeySize = 16
|
|
|
|
// NOTE: bts does not escape.
|
|
|
|
bts := make([]byte, nonceKeySize)
|
|
|
|
if _, err = fastrand.Read(bts); err != nil {
|
|
|
|
return nil, fmt.Errorf("rand read error: %w", err)
|
2018-12-11 00:25:05 +08:00
|
|
|
}
|
2023-11-03 11:02:19 +08:00
|
|
|
nonce = base64.StdEncoding.EncodeToString(bts)
|
|
|
|
request.Header.Set("Sec-WebSocket-Version", "13")
|
|
|
|
request.Header.Set("Sec-WebSocket-Key", nonce)
|
2018-12-11 00:25:05 +08:00
|
|
|
}
|
|
|
|
|
2021-08-22 00:25:29 +08:00
|
|
|
if earlyData != nil {
|
2023-10-06 17:44:36 +08:00
|
|
|
earlyDataString := earlyData.String()
|
2021-08-22 00:25:29 +08:00
|
|
|
if c.EarlyDataHeaderName == "" {
|
2023-10-06 17:44:36 +08:00
|
|
|
uri.Path += earlyDataString
|
2021-08-22 00:25:29 +08:00
|
|
|
} else {
|
2023-11-03 11:02:19 +08:00
|
|
|
request.Header.Set(c.EarlyDataHeaderName, earlyDataString)
|
2021-08-22 00:25:29 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-11-03 11:02:19 +08:00
|
|
|
if ctx.Done() != nil {
|
|
|
|
done := N.SetupContextForConn(ctx, conn)
|
|
|
|
defer done(&err)
|
2023-10-17 12:46:41 +08:00
|
|
|
}
|
|
|
|
|
2023-11-03 11:02:19 +08:00
|
|
|
err = request.Write(conn)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
2023-10-17 12:46:41 +08:00
|
|
|
}
|
2023-11-03 11:02:19 +08:00
|
|
|
bufferedConn := N.NewBufferedConn(conn)
|
|
|
|
response, err := http.ReadResponse(bufferedConn.Reader(), request)
|
2018-11-04 21:36:20 +08:00
|
|
|
if err != nil {
|
2023-11-03 11:02:19 +08:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
if response.StatusCode != http.StatusSwitchingProtocols ||
|
|
|
|
!strings.EqualFold(response.Header.Get("Connection"), "upgrade") ||
|
|
|
|
!strings.EqualFold(response.Header.Get("Upgrade"), "websocket") {
|
|
|
|
return nil, fmt.Errorf("unexpected status: %s", response.Status)
|
|
|
|
}
|
|
|
|
|
|
|
|
if c.V2rayHttpUpgrade {
|
|
|
|
return bufferedConn, nil
|
2018-11-04 21:36:20 +08:00
|
|
|
}
|
|
|
|
|
2023-11-03 11:02:19 +08:00
|
|
|
if log.Level() == log.DEBUG { // we might not check this for performance
|
|
|
|
secAccept := response.Header.Get("Sec-Websocket-Accept")
|
|
|
|
const acceptSize = 28 // base64.StdEncoding.EncodedLen(sha1.Size)
|
|
|
|
if lenSecAccept := len(secAccept); lenSecAccept != acceptSize {
|
|
|
|
return nil, fmt.Errorf("unexpected Sec-Websocket-Accept length: %d", lenSecAccept)
|
|
|
|
}
|
|
|
|
|
|
|
|
const magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
|
|
|
|
const nonceSize = 24 // base64.StdEncoding.EncodedLen(nonceKeySize)
|
|
|
|
p := make([]byte, nonceSize+len(magic))
|
|
|
|
copy(p[:nonceSize], nonce)
|
|
|
|
copy(p[nonceSize:], magic)
|
|
|
|
sum := sha1.Sum(p)
|
|
|
|
if accept := base64.StdEncoding.EncodeToString(sum[:]); accept != secAccept {
|
|
|
|
return nil, errors.New("unexpected Sec-Websocket-Accept")
|
|
|
|
}
|
|
|
|
}
|
2023-11-02 10:31:58 +08:00
|
|
|
|
|
|
|
conn = newWebsocketConn(conn, ws.StateClientSide)
|
2023-04-17 00:23:12 +08:00
|
|
|
// websocketConn can't correct handle ReadDeadline
|
|
|
|
// so call N.NewDeadlineConn to add a safe wrapper
|
|
|
|
return N.NewDeadlineConn(conn), nil
|
2018-10-28 23:46:32 +08:00
|
|
|
}
|
2021-08-22 00:25:29 +08:00
|
|
|
|
2023-05-18 13:15:08 +08:00
|
|
|
func StreamWebsocketConn(ctx context.Context, conn net.Conn, c *WebsocketConfig) (net.Conn, error) {
|
2021-08-22 16:03:46 +08:00
|
|
|
if u, err := url.Parse(c.Path); err == nil {
|
|
|
|
if q := u.Query(); q.Get("ed") != "" {
|
|
|
|
if ed, err := strconv.Atoi(q.Get("ed")); err == nil {
|
|
|
|
c.MaxEarlyData = ed
|
|
|
|
c.EarlyDataHeaderName = "Sec-WebSocket-Protocol"
|
|
|
|
q.Del("ed")
|
|
|
|
u.RawQuery = q.Encode()
|
|
|
|
c.Path = u.String()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-08-22 00:25:29 +08:00
|
|
|
if c.MaxEarlyData > 0 {
|
|
|
|
return streamWebsocketWithEarlyDataConn(conn, c)
|
|
|
|
}
|
|
|
|
|
2023-05-18 13:15:08 +08:00
|
|
|
return streamWebsocketConn(ctx, conn, c, nil)
|
2021-08-22 00:25:29 +08:00
|
|
|
}
|
2023-10-06 17:44:36 +08:00
|
|
|
|
2023-11-02 10:31:58 +08:00
|
|
|
func newWebsocketConn(conn net.Conn, state ws.State) *websocketConn {
|
2023-10-06 17:44:36 +08:00
|
|
|
controlHandler := wsutil.ControlFrameHandler(conn, state)
|
|
|
|
return &websocketConn{
|
|
|
|
Conn: conn,
|
|
|
|
state: state,
|
|
|
|
reader: &wsutil.Reader{
|
2023-11-02 10:31:58 +08:00
|
|
|
Source: conn,
|
2023-10-06 17:44:36 +08:00
|
|
|
State: state,
|
|
|
|
SkipHeaderCheck: true,
|
|
|
|
CheckUTF8: false,
|
|
|
|
OnIntermediate: controlHandler,
|
|
|
|
},
|
|
|
|
controlHandler: controlHandler,
|
|
|
|
rawWriter: N.NewExtendedWriter(conn),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
var replacer = strings.NewReplacer("+", "-", "/", "_", "=", "")
|
|
|
|
|
|
|
|
func decodeEd(s string) ([]byte, error) {
|
|
|
|
return base64.RawURLEncoding.DecodeString(replacer.Replace(s))
|
|
|
|
}
|
|
|
|
|
2023-10-17 12:46:41 +08:00
|
|
|
func decodeXray0rtt(requestHeader http.Header) []byte {
|
2023-10-06 17:44:36 +08:00
|
|
|
// read inHeader's `Sec-WebSocket-Protocol` for Xray's 0rtt ws
|
|
|
|
if secProtocol := requestHeader.Get("Sec-WebSocket-Protocol"); len(secProtocol) > 0 {
|
2023-10-17 12:46:41 +08:00
|
|
|
if edBuf, err := decodeEd(secProtocol); err == nil { // sure could base64 decode
|
|
|
|
return edBuf
|
2023-10-06 17:44:36 +08:00
|
|
|
}
|
|
|
|
}
|
2023-10-17 12:46:41 +08:00
|
|
|
return nil
|
2023-10-06 17:44:36 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func StreamUpgradedWebsocketConn(w http.ResponseWriter, r *http.Request) (net.Conn, error) {
|
2023-10-17 12:46:41 +08:00
|
|
|
wsConn, rw, _, err := ws.UpgradeHTTP(r, w)
|
2023-10-06 17:44:36 +08:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2023-11-02 10:31:58 +08:00
|
|
|
|
|
|
|
// gobwas/ws will flush rw.Writer, so we only need warp rw.Reader
|
|
|
|
wsConn = N.WarpConnWithBioReader(wsConn, rw.Reader)
|
|
|
|
|
|
|
|
conn := newWebsocketConn(wsConn, ws.StateServerSide)
|
2023-10-17 12:46:41 +08:00
|
|
|
if edBuf := decodeXray0rtt(r.Header); len(edBuf) > 0 {
|
2023-10-07 16:45:15 +08:00
|
|
|
return N.NewDeadlineConn(&websocketWithReaderConn{conn, io.MultiReader(bytes.NewReader(edBuf), conn)}), nil
|
2023-10-06 17:44:36 +08:00
|
|
|
}
|
2023-10-07 16:45:15 +08:00
|
|
|
return N.NewDeadlineConn(conn), nil
|
2023-10-06 17:44:36 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
type websocketWithReaderConn struct {
|
|
|
|
*websocketConn
|
|
|
|
reader io.Reader
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ws *websocketWithReaderConn) Read(b []byte) (n int, err error) {
|
|
|
|
return ws.reader.Read(b)
|
|
|
|
}
|