Browse Source

Merge branch 'dev-wsimprovement'

Shelikhoo 4 years ago
parent
commit
03077a48ed

+ 20 - 0
.github/workflows/release.yml

@@ -170,6 +170,12 @@ jobs:
         with:
           path: build_artifacts
 
+      - name: Create extra package
+        run: |
+          pushd ./release/extra/
+          zip -9vr ../../build_artifacts/v2ray-extra.zip .
+          popd
+
       - name: Generate shasum
         run: |
           go get -v github.com/v2fly/V2BuildAssist/v2buildutil
@@ -205,6 +211,11 @@ jobs:
           name: Release.unsigned.dgst
           path: build_artifacts/Release.unsigned.dgst
 
+      - uses: actions/upload-artifact@v2
+        with:
+          name: v2ray-extra.zip
+          path: build_artifacts/v2ray-extra.zip
+
       - name: Upload Release.unsigned related files
         uses: svenstaro/upload-release-action@v2
         if: github.event_name == 'release'
@@ -213,3 +224,12 @@ jobs:
           file_glob: true
           file: build_artifacts/Release.unsigned*
           tag: ${{ github.ref }}
+
+      - name: Upload extra package
+        uses: svenstaro/upload-release-action@v2
+        if: github.event_name == 'release'
+        with:
+          repo_token: ${{ secrets.GITHUB_TOKEN }}
+          file_glob: true
+          file: build_artifacts/v2ray-extra.zip
+          tag: ${{ github.ref }}

+ 163 - 0
app/browserforwarder/config.pb.go

@@ -0,0 +1,163 @@
+// Code generated by protoc-gen-go. DO NOT EDIT.
+// versions:
+// 	protoc-gen-go v1.26.0
+// 	protoc        v3.15.6
+// source: app/browserforwarder/config.proto
+
+package browserforwarder
+
+import (
+	protoreflect "google.golang.org/protobuf/reflect/protoreflect"
+	protoimpl "google.golang.org/protobuf/runtime/protoimpl"
+	reflect "reflect"
+	sync "sync"
+)
+
+const (
+	// Verify that this generated code is sufficiently up-to-date.
+	_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
+	// Verify that runtime/protoimpl is sufficiently up-to-date.
+	_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
+)
+
+// Config is the settings for BrowserForwarder.
+type Config struct {
+	state         protoimpl.MessageState
+	sizeCache     protoimpl.SizeCache
+	unknownFields protoimpl.UnknownFields
+
+	ListenAddr string `protobuf:"bytes,1,opt,name=listen_addr,json=listenAddr,proto3" json:"listen_addr,omitempty"`
+	ListenPort int32  `protobuf:"varint,2,opt,name=listen_port,json=listenPort,proto3" json:"listen_port,omitempty"`
+}
+
+func (x *Config) Reset() {
+	*x = Config{}
+	if protoimpl.UnsafeEnabled {
+		mi := &file_app_browserforwarder_config_proto_msgTypes[0]
+		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+		ms.StoreMessageInfo(mi)
+	}
+}
+
+func (x *Config) String() string {
+	return protoimpl.X.MessageStringOf(x)
+}
+
+func (*Config) ProtoMessage() {}
+
+func (x *Config) ProtoReflect() protoreflect.Message {
+	mi := &file_app_browserforwarder_config_proto_msgTypes[0]
+	if protoimpl.UnsafeEnabled && x != nil {
+		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+		if ms.LoadMessageInfo() == nil {
+			ms.StoreMessageInfo(mi)
+		}
+		return ms
+	}
+	return mi.MessageOf(x)
+}
+
+// Deprecated: Use Config.ProtoReflect.Descriptor instead.
+func (*Config) Descriptor() ([]byte, []int) {
+	return file_app_browserforwarder_config_proto_rawDescGZIP(), []int{0}
+}
+
+func (x *Config) GetListenAddr() string {
+	if x != nil {
+		return x.ListenAddr
+	}
+	return ""
+}
+
+func (x *Config) GetListenPort() int32 {
+	if x != nil {
+		return x.ListenPort
+	}
+	return 0
+}
+
+var File_app_browserforwarder_config_proto protoreflect.FileDescriptor
+
+var file_app_browserforwarder_config_proto_rawDesc = []byte{
+	0x0a, 0x21, 0x61, 0x70, 0x70, 0x2f, 0x62, 0x72, 0x6f, 0x77, 0x73, 0x65, 0x72, 0x66, 0x6f, 0x72,
+	0x77, 0x61, 0x72, 0x64, 0x65, 0x72, 0x2f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x70, 0x72,
+	0x6f, 0x74, 0x6f, 0x12, 0x1f, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e,
+	0x61, 0x70, 0x70, 0x2e, 0x62, 0x72, 0x6f, 0x77, 0x73, 0x65, 0x72, 0x66, 0x6f, 0x72, 0x77, 0x61,
+	0x72, 0x64, 0x65, 0x72, 0x22, 0x4a, 0x0a, 0x06, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x1f,
+	0x0a, 0x0b, 0x6c, 0x69, 0x73, 0x74, 0x65, 0x6e, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x18, 0x01, 0x20,
+	0x01, 0x28, 0x09, 0x52, 0x0a, 0x6c, 0x69, 0x73, 0x74, 0x65, 0x6e, 0x41, 0x64, 0x64, 0x72, 0x12,
+	0x1f, 0x0a, 0x0b, 0x6c, 0x69, 0x73, 0x74, 0x65, 0x6e, 0x5f, 0x70, 0x6f, 0x72, 0x74, 0x18, 0x02,
+	0x20, 0x01, 0x28, 0x05, 0x52, 0x0a, 0x6c, 0x69, 0x73, 0x74, 0x65, 0x6e, 0x50, 0x6f, 0x72, 0x74,
+	0x42, 0x7e, 0x0a, 0x23, 0x63, 0x6f, 0x6d, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f,
+	0x72, 0x65, 0x2e, 0x61, 0x70, 0x70, 0x2e, 0x62, 0x72, 0x6f, 0x77, 0x73, 0x65, 0x72, 0x66, 0x6f,
+	0x72, 0x77, 0x61, 0x72, 0x64, 0x65, 0x72, 0x50, 0x01, 0x5a, 0x33, 0x67, 0x69, 0x74, 0x68, 0x75,
+	0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x76, 0x32, 0x66, 0x6c, 0x79, 0x2f, 0x76, 0x32, 0x72, 0x61,
+	0x79, 0x2d, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x76, 0x34, 0x2f, 0x61, 0x70, 0x70, 0x2f, 0x62, 0x72,
+	0x6f, 0x77, 0x73, 0x65, 0x72, 0x66, 0x6f, 0x72, 0x77, 0x61, 0x72, 0x64, 0x65, 0x72, 0xaa, 0x02,
+	0x1f, 0x56, 0x32, 0x52, 0x61, 0x79, 0x2e, 0x43, 0x6f, 0x72, 0x65, 0x2e, 0x41, 0x70, 0x70, 0x2e,
+	0x42, 0x72, 0x6f, 0x77, 0x73, 0x65, 0x72, 0x66, 0x6f, 0x72, 0x77, 0x61, 0x72, 0x64, 0x65, 0x72,
+	0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
+}
+
+var (
+	file_app_browserforwarder_config_proto_rawDescOnce sync.Once
+	file_app_browserforwarder_config_proto_rawDescData = file_app_browserforwarder_config_proto_rawDesc
+)
+
+func file_app_browserforwarder_config_proto_rawDescGZIP() []byte {
+	file_app_browserforwarder_config_proto_rawDescOnce.Do(func() {
+		file_app_browserforwarder_config_proto_rawDescData = protoimpl.X.CompressGZIP(file_app_browserforwarder_config_proto_rawDescData)
+	})
+	return file_app_browserforwarder_config_proto_rawDescData
+}
+
+var file_app_browserforwarder_config_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
+var file_app_browserforwarder_config_proto_goTypes = []interface{}{
+	(*Config)(nil), // 0: v2ray.core.app.browserforwarder.Config
+}
+var file_app_browserforwarder_config_proto_depIdxs = []int32{
+	0, // [0:0] is the sub-list for method output_type
+	0, // [0:0] is the sub-list for method input_type
+	0, // [0:0] is the sub-list for extension type_name
+	0, // [0:0] is the sub-list for extension extendee
+	0, // [0:0] is the sub-list for field type_name
+}
+
+func init() { file_app_browserforwarder_config_proto_init() }
+func file_app_browserforwarder_config_proto_init() {
+	if File_app_browserforwarder_config_proto != nil {
+		return
+	}
+	if !protoimpl.UnsafeEnabled {
+		file_app_browserforwarder_config_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
+			switch v := v.(*Config); i {
+			case 0:
+				return &v.state
+			case 1:
+				return &v.sizeCache
+			case 2:
+				return &v.unknownFields
+			default:
+				return nil
+			}
+		}
+	}
+	type x struct{}
+	out := protoimpl.TypeBuilder{
+		File: protoimpl.DescBuilder{
+			GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
+			RawDescriptor: file_app_browserforwarder_config_proto_rawDesc,
+			NumEnums:      0,
+			NumMessages:   1,
+			NumExtensions: 0,
+			NumServices:   0,
+		},
+		GoTypes:           file_app_browserforwarder_config_proto_goTypes,
+		DependencyIndexes: file_app_browserforwarder_config_proto_depIdxs,
+		MessageInfos:      file_app_browserforwarder_config_proto_msgTypes,
+	}.Build()
+	File_app_browserforwarder_config_proto = out.File
+	file_app_browserforwarder_config_proto_rawDesc = nil
+	file_app_browserforwarder_config_proto_goTypes = nil
+	file_app_browserforwarder_config_proto_depIdxs = nil
+}

+ 14 - 0
app/browserforwarder/config.proto

@@ -0,0 +1,14 @@
+syntax = "proto3";
+
+package v2ray.core.app.browserforwarder;
+
+option csharp_namespace = "V2Ray.Core.App.Browserforwarder";
+option go_package = "github.com/v2fly/v2ray-core/v4/app/browserforwarder";
+option java_package = "com.v2ray.core.app.browserforwarder";
+option java_multiple_files = true;
+
+// Config is the settings for BrowserForwarder.
+message Config {
+  string listen_addr = 1;
+  int32 listen_port = 2;
+}

+ 9 - 0
app/browserforwarder/errors.generated.go

@@ -0,0 +1,9 @@
+package browserforwarder
+
+import "github.com/v2fly/v2ray-core/v4/common/errors"
+
+type errPathObjHolder struct{}
+
+func newError(values ...interface{}) *errors.Error {
+	return errors.New(values...).WithPathObj(errPathObjHolder{})
+}

+ 100 - 0
app/browserforwarder/forwarder.go

@@ -0,0 +1,100 @@
+// +build !confonly
+
+package browserforwarder
+
+import (
+	"bytes"
+	"context"
+	"io"
+	"net/http"
+	"time"
+
+	"github.com/v2fly/BrowserBridge/handler"
+
+	"github.com/v2fly/v2ray-core/v4/common"
+	"github.com/v2fly/v2ray-core/v4/common/net"
+	"github.com/v2fly/v2ray-core/v4/common/platform/securedload"
+	"github.com/v2fly/v2ray-core/v4/features/ext"
+	"github.com/v2fly/v2ray-core/v4/transport/internet"
+)
+
+//go:generate go run github.com/v2fly/v2ray-core/v4/common/errors/errorgen
+
+type Forwarder struct {
+	ctx context.Context
+
+	forwarder  *handler.HTTPHandle
+	httpserver *http.Server
+
+	config *Config
+}
+
+func (f *Forwarder) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
+	requestPath := request.URL.Path[1:]
+
+	switch requestPath {
+	case "":
+		fallthrough
+	case "index.js":
+		BridgeResource(writer, request, requestPath)
+	case "link":
+		f.forwarder.ServeBridge(writer, request)
+	}
+}
+
+func (f *Forwarder) DialWebsocket(url string, header http.Header) (io.ReadWriteCloser, error) {
+	return f.forwarder.Dial(url)
+}
+
+func (f *Forwarder) Type() interface{} {
+	return ext.BrowserForwarderType()
+}
+
+func (f *Forwarder) Start() error {
+	f.forwarder = handler.NewHttpHandle()
+	f.httpserver = &http.Server{Handler: f}
+	address := net.ParseAddress(f.config.ListenAddr)
+	listener, err := internet.ListenSystem(f.ctx, &net.TCPAddr{IP: address.IP(), Port: int(f.config.ListenPort)}, nil)
+	if err != nil {
+		return newError("forwarder cannot listen on the port").Base(err)
+	}
+	go func() {
+		err = f.httpserver.Serve(listener)
+		if err != nil {
+			newError("cannot serve http forward server").Base(err).WriteToLog()
+		}
+	}()
+	return nil
+}
+
+func (f *Forwarder) Close() error {
+	if f.httpserver != nil {
+		return f.httpserver.Close()
+	}
+	return nil
+}
+
+func BridgeResource(rw http.ResponseWriter, r *http.Request, path string) {
+	content := path
+	if content == "" {
+		content = "index.html"
+	}
+	data, err := securedload.GetAssetSecured("browserforwarder/" + content)
+	if err != nil {
+		err = newError("cannot load necessary resources").Base(err)
+		http.Error(rw, err.Error(), http.StatusForbidden)
+		return
+	}
+
+	http.ServeContent(rw, r, path, time.Now(), bytes.NewReader(data))
+}
+
+func NewForwarder(ctx context.Context, cfg *Config) *Forwarder {
+	return &Forwarder{config: cfg, ctx: ctx}
+}
+
+func init() {
+	common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, cfg interface{}) (interface{}, error) {
+		return NewForwarder(ctx, cfg.(*Config)), nil
+	}))
+}

+ 9 - 0
common/platform/securedload/embedded.go

@@ -0,0 +1,9 @@
+package securedload
+
+const allowedHashes = `SHA256 (!#project==v2fly) = ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
+SHA256 (!#version==embedded) = ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
+SHA256 (subscriptions/subscriptionsDefinition.v2flyTemplate) = 3f165dba7de0d7c506fbdff3275ea64b76f307df435316a3ea0914ee957793ab
+SHA256 (browserforwarder/index.html) = 34f2c573724256421ade769bda18eeac85172bf0aaed00d7b90e41e843a2caef
+SHA256 (browserforwarder/index.js) = 7de6de0bb7a1c8838f20fcba6bd9b02e1199d116b053836ad622184588d9a37e
+
+`

+ 48 - 0
common/platform/securedload/embeddedhash.go

@@ -0,0 +1,48 @@
+package securedload
+
+import (
+	"bytes"
+	"crypto/sha256"
+	"encoding/hex"
+	"strings"
+
+	"github.com/v2fly/VSign/insmgr"
+	"github.com/v2fly/VSign/signerVerify"
+
+	"github.com/v2fly/v2ray-core/v4/common/platform"
+	"github.com/v2fly/v2ray-core/v4/common/platform/filesystem"
+)
+
+type EmbeddedHashProtectedLoader struct {
+	checkedFile map[string]string
+}
+
+func (e EmbeddedHashProtectedLoader) VerifyAndLoad(filename string) ([]byte, error) {
+	filecontent, err := filesystem.ReadFile(platform.GetAssetLocation(filename))
+	if err != nil {
+		return nil, newError("Cannot find file", filename).Base(err)
+	}
+	fileHash := sha256.Sum256(filecontent)
+	fileHashAsString := hex.EncodeToString(fileHash[:])
+	if filenameverified, ok := e.checkedFile[fileHashAsString]; ok {
+		for _, filenameVerifiedIndividual := range strings.Split(filenameverified, ";") {
+			if strings.HasSuffix(filenameVerifiedIndividual, filename) {
+				return filecontent, nil
+			}
+		}
+	}
+	return nil, newError("Unrecognized file at ", filename, " can not be loaded for execution")
+}
+
+func NewEmbeddedHashProtectedLoader() *EmbeddedHashProtectedLoader {
+	instructions := insmgr.ReadAllIns(bytes.NewReader([]byte(allowedHashes)))
+	checkedFile, _, ok := signerVerify.CheckAsClient(instructions, "v2fly", true)
+	if !ok {
+		panic("Embedded Hash data is invalid")
+	}
+	return &EmbeddedHashProtectedLoader{checkedFile: checkedFile}
+}
+
+func init() {
+	RegisterProtectedLoader("embedded", NewEmbeddedHashProtectedLoader())
+}

+ 9 - 0
common/platform/securedload/errors.generated.go

@@ -0,0 +1,9 @@
+package securedload
+
+import "github.com/v2fly/v2ray-core/v4/common/errors"
+
+type errPathObjHolder struct{}
+
+func newError(values ...interface{}) *errors.Error {
+	return errors.New(values...).WithPathObj(errPathObjHolder{})
+}

+ 17 - 0
common/platform/securedload/file.go

@@ -0,0 +1,17 @@
+package securedload
+
+import "path/filepath"
+
+func GetAssetSecured(name string) ([]byte, error) {
+	name = filepath.FromSlash(name)
+
+	var err error
+	for k, v := range knownProtectedLoader {
+		loadedData, errLoad := v.VerifyAndLoad(name)
+		if errLoad == nil {
+			return loadedData, nil
+		}
+		err = newError(k, " is not loading executable file").Base(errLoad)
+	}
+	return nil, err
+}

+ 3 - 0
common/platform/securedload/securedload.go

@@ -0,0 +1,3 @@
+package securedload
+
+//go:generate go run github.com/v2fly/v2ray-core/v4/common/errors/errorgen

+ 14 - 0
common/platform/securedload/verify.go

@@ -0,0 +1,14 @@
+package securedload
+
+type ProtectedLoader interface {
+	VerifyAndLoad(filename string) ([]byte, error)
+}
+
+var knownProtectedLoader map[string]ProtectedLoader
+
+func RegisterProtectedLoader(name string, sv ProtectedLoader) {
+	if knownProtectedLoader == nil {
+		knownProtectedLoader = map[string]ProtectedLoader{}
+	}
+	knownProtectedLoader[name] = sv
+}

+ 14 - 0
features/ext/browser.go

@@ -0,0 +1,14 @@
+package ext
+
+import (
+	"io"
+	"net/http"
+)
+
+type BrowserForwarder interface {
+	DialWebsocket(url string, header http.Header) (io.ReadWriteCloser, error)
+}
+
+func BrowserForwarderType() interface{} {
+	return (*BrowserForwarder)(nil)
+}

+ 4 - 3
go.mod

@@ -12,12 +12,13 @@ require (
 	github.com/pires/go-proxyproto v0.5.0
 	github.com/seiflotfy/cuckoofilter v0.0.0-20201222105146-bc6005554a0c
 	github.com/stretchr/testify v1.7.0
+	github.com/v2fly/BrowserBridge v0.0.0-20210327130545-c01e4317fadd
 	github.com/v2fly/VSign v0.0.0-20201108000810-e2adc24bf848
 	go.starlark.net v0.0.0-20210312235212-74c10e2c17dc
-	golang.org/x/crypto v0.0.0-20210317152858-513c2a44f670
-	golang.org/x/net v0.0.0-20210316092652-d523dce5a7f4
+	golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2
+	golang.org/x/net v0.0.0-20210326220855-61e056675ecf
 	golang.org/x/sync v0.0.0-20210220032951-036812b2e83c
-	golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4
+	golang.org/x/sys v0.0.0-20210326220804-49726bf1d181
 	google.golang.org/grpc v1.36.1
 	google.golang.org/protobuf v1.26.0
 	h12.io/socks v1.0.2

+ 15 - 7
go.sum

@@ -79,6 +79,8 @@ github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+
 github.com/googleapis/gax-go v2.0.0+incompatible/go.mod h1:SFVmujtThgffbyetf+mdk2eWhX2bMyUtNHzFKcPA9HY=
 github.com/googleapis/gax-go/v2 v2.0.3/go.mod h1:LLvjysVCY1JZeum8Z6l8qUty8fiNwE08qbEPm1M08qg=
 github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY=
+github.com/gopherjs/gopherjs v0.0.0-20210202160940-bed99a852dfe/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY=
+github.com/gopherjs/websocket v0.0.0-20191103002815-9a42957e2b3a/go.mod h1:jd+zY81Fx2lC4bfw58+Rflg1srqmedQjbBUejKOjYNY=
 github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc=
 github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
 github.com/gregjones/httpcache v0.0.0-20180305231024-9cad4c3443a7/go.mod h1:FecbI9+v66THATjSRHfNgh1IVFe/9kFxbXtjV0ctIMA=
@@ -98,6 +100,8 @@ github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
 github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
 github.com/lucas-clemente/quic-go v0.20.0 h1:FSU3YN5VnLafHR27Ejs1r1CYMS7XMyIVDzRewkDLNBw=
 github.com/lucas-clemente/quic-go v0.20.0/go.mod h1:fZq/HUDIM+mW6X6wtzORjC0E/WDBMKe5Hf9bgjISwLk=
+github.com/lunixbochs/struc v0.0.0-20200707160740-784aaebc1d40 h1:EnfXoSqDfSNJv0VBNqY/88RNnhSGYkrHaO0mmFGbVsc=
+github.com/lunixbochs/struc v0.0.0-20200707160740-784aaebc1d40/go.mod h1:vy1vK6wD6j7xX6O6hXe621WabdtNkou2h7uRtTfRMyg=
 github.com/lunixbochs/vtclean v1.0.0/go.mod h1:pHhQNgMf3btfWnGBVipUOjRYhoOsdGqdm/+2c2E2WMI=
 github.com/mailru/easyjson v0.0.0-20190312143242-1de009706dbe/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc=
 github.com/marten-seemann/qpack v0.2.1/go.mod h1:F7Gl5L1jIgN1D11ucXefiuJS9UMVP2opoCp2jDKb7wc=
@@ -170,10 +174,14 @@ github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/
 github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
 github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
 github.com/tarm/serial v0.0.0-20180830185346-98f6abe2eb07/go.mod h1:kDXzergiv9cbyO7IOYJZWg1U88JhDg3PB6klq9Hg2pA=
+github.com/v2fly/BrowserBridge v0.0.0-20210327130545-c01e4317fadd h1:fQ4O/lTTwSPHbIDhnT/npwHTgJ/5RQWQaQG01VbIYcc=
+github.com/v2fly/BrowserBridge v0.0.0-20210327130545-c01e4317fadd/go.mod h1:skmBSeT/GvVqal/eylE9E16x9RC29xFXCbxDLVmatOk=
 github.com/v2fly/VSign v0.0.0-20201108000810-e2adc24bf848 h1:p1UzXK6VAutXFFQMnre66h7g1BjRKUnLv0HfmmRoz7w=
 github.com/v2fly/VSign v0.0.0-20201108000810-e2adc24bf848/go.mod h1:p80Bv154ZtrGpXMN15slDCqc9UGmfBuUzheDFBYaW/M=
 github.com/viant/assertly v0.4.8/go.mod h1:aGifi++jvCrUaklKEKT0BU95igDNaqkvz+49uaYMPRU=
 github.com/viant/toolbox v0.24.0/go.mod h1:OxMCG57V0PXuIP2HNQrtJf2CjqdmbrOx5EkMILuUhzM=
+github.com/xtaci/smux v1.5.15 h1:6hMiXswcleXj5oNfcJc+DXS8Vj36XX2LaX98udog6Kc=
+github.com/xtaci/smux v1.5.15/go.mod h1:OMlQbT5vcgl2gb49mFkYo6SMf+zP3rcjcwQz7ZU7IGY=
 go.opencensus.io v0.18.0/go.mod h1:vKdFvxhtzZ9onBp9VKHK8z/sRpBMnKAsufL7wlDrCOA=
 go.starlark.net v0.0.0-20210312235212-74c10e2c17dc h1:pVkptfeOTFfx+zXZo7HEHN3d5LmhatBFvHdm/f2QnpY=
 go.starlark.net v0.0.0-20210312235212-74c10e2c17dc/go.mod h1:t3mmBBPzAVvK0L0n1drDmrQsJ8FoIx4INCqVMTr/Zo0=
@@ -185,8 +193,8 @@ golang.org/x/crypto v0.0.0-20190313024323-a1f597ede03a/go.mod h1:djNgcEr1/C05ACk
 golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
 golang.org/x/crypto v0.0.0-20200221231518-2aa609cf4a9d/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
 golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
-golang.org/x/crypto v0.0.0-20210317152858-513c2a44f670 h1:gzMM0EjIYiRmJI3+jBdFuoynZlpxa2JQZsolKu09BXo=
-golang.org/x/crypto v0.0.0-20210317152858-513c2a44f670/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4=
+golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2 h1:It14KIkyBFYkHkwZ7k45minvA9aorojkyjGk9KJ5B/w=
+golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4=
 golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
 golang.org/x/lint v0.0.0-20180702182130-06c8688daad7/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
 golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
@@ -207,8 +215,8 @@ golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLL
 golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
 golang.org/x/net v0.0.0-20200707034311-ab3426394381/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
 golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
-golang.org/x/net v0.0.0-20210316092652-d523dce5a7f4 h1:b0LrWgu8+q7z4J+0Y3Umo5q1dL7NXBkKBWkaVkAq17E=
-golang.org/x/net v0.0.0-20210316092652-d523dce5a7f4/go.mod h1:RBQZq4jEuRlivfhVLdyRGr576XBO4/greRjx4P4O3yc=
+golang.org/x/net v0.0.0-20210326220855-61e056675ecf h1:WUcCxqQqDT0aXO4VnQbfMvp4zh7m1Gb2clVuHUAGGRE=
+golang.org/x/net v0.0.0-20210326220855-61e056675ecf/go.mod h1:uSPa2vr4CLtc/ILN5odXGNXS6mhrKVzTaCXzk9m6W3k=
 golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
 golang.org/x/oauth2 v0.0.0-20181017192945-9dcd33a902f4/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
 golang.org/x/oauth2 v0.0.0-20181203162652-d668ce993890/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
@@ -238,9 +246,9 @@ golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7w
 golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
 golang.org/x/sys v0.0.0-20201231184435-2d18734c6014/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
 golang.org/x/sys v0.0.0-20210303074136-134d130e1a04/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
-golang.org/x/sys v0.0.0-20210315160823-c6e025ad8005/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
-golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4 h1:EZ2mChiOa8udjfp6rRmswTbtZN/QzUQp4ptM4rnjHvc=
-golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20210324051608-47abb6519492/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20210326220804-49726bf1d181 h1:64ChN/hjER/taL4YJuA+gpLfIMT+/NFherRZixbxOhg=
+golang.org/x/sys v0.0.0-20210326220804-49726bf1d181/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
 golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
 golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
 golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=

+ 19 - 0
infra/conf/browser_forwarder.go

@@ -0,0 +1,19 @@
+package conf
+
+import (
+	"github.com/golang/protobuf/proto"
+
+	"github.com/v2fly/v2ray-core/v4/app/browserforwarder"
+)
+
+type BrowserForwarderConfig struct {
+	ListenAddr string `json:"listenAddr"`
+	ListenPort int32  `json:"listenPort"`
+}
+
+func (b BrowserForwarderConfig) Build() (proto.Message, error) {
+	return &browserforwarder.Config{
+		ListenAddr: b.ListenAddr,
+		ListenPort: b.ListenPort,
+	}, nil
+}

+ 10 - 6
infra/conf/transport_internet.go

@@ -135,10 +135,12 @@ func (c *TCPConfig) Build() (proto.Message, error) {
 }
 
 type WebSocketConfig struct {
-	Path                string            `json:"path"`
-	Path2               string            `json:"Path"` // The key was misspelled. For backward compatibility, we have to keep track the old key.
-	Headers             map[string]string `json:"headers"`
-	AcceptProxyProtocol bool              `json:"acceptProxyProtocol"`
+	Path                 string            `json:"path"`
+	Path2                string            `json:"Path"` // The key was misspelled. For backward compatibility, we have to keep track the old key.
+	Headers              map[string]string `json:"headers"`
+	AcceptProxyProtocol  bool              `json:"acceptProxyProtocol"`
+	MaxEarlyData         int32             `json:"maxEarlyData"`
+	UseBrowserForwarding bool              `json:"useBrowserForwarding"`
 }
 
 // Build implements Buildable.
@@ -155,8 +157,10 @@ func (c *WebSocketConfig) Build() (proto.Message, error) {
 		})
 	}
 	config := &websocket.Config{
-		Path:   path,
-		Header: header,
+		Path:                 path,
+		Header:               header,
+		MaxEarlyData:         c.MaxEarlyData,
+		UseBrowserForwarding: c.UseBrowserForwarding,
 	}
 	if c.AcceptProxyProtocol {
 		config.AcceptProxyProtocol = c.AcceptProxyProtocol

+ 20 - 11
infra/conf/v2ray.go

@@ -341,17 +341,18 @@ type Config struct {
 	// and should not be used.
 	OutboundDetours []OutboundDetourConfig `json:"outboundDetour"`
 
-	LogConfig       *LogConfig             `json:"log"`
-	RouterConfig    *RouterConfig          `json:"routing"`
-	DNSConfig       *DNSConfig             `json:"dns"`
-	InboundConfigs  []InboundDetourConfig  `json:"inbounds"`
-	OutboundConfigs []OutboundDetourConfig `json:"outbounds"`
-	Transport       *TransportConfig       `json:"transport"`
-	Policy          *PolicyConfig          `json:"policy"`
-	API             *APIConfig             `json:"api"`
-	Stats           *StatsConfig           `json:"stats"`
-	Reverse         *ReverseConfig         `json:"reverse"`
-	FakeDNS         *FakeDNSConfig         `json:"fakeDns"`
+	LogConfig        *LogConfig              `json:"log"`
+	RouterConfig     *RouterConfig           `json:"routing"`
+	DNSConfig        *DNSConfig              `json:"dns"`
+	InboundConfigs   []InboundDetourConfig   `json:"inbounds"`
+	OutboundConfigs  []OutboundDetourConfig  `json:"outbounds"`
+	Transport        *TransportConfig        `json:"transport"`
+	Policy           *PolicyConfig           `json:"policy"`
+	API              *APIConfig              `json:"api"`
+	Stats            *StatsConfig            `json:"stats"`
+	Reverse          *ReverseConfig          `json:"reverse"`
+	FakeDNS          *FakeDNSConfig          `json:"fakeDns"`
+	BrowserForwarder *BrowserForwarderConfig `json:"browserForwarder"`
 }
 
 func (c *Config) findInboundTag(tag string) int {
@@ -558,6 +559,14 @@ func (c *Config) Build() (*core.Config, error) {
 		config.App = append(config.App, serial.ToTypedMessage(r))
 	}
 
+	if c.BrowserForwarder != nil {
+		r, err := c.BrowserForwarder.Build()
+		if err != nil {
+			return nil, err
+		}
+		config.App = append(config.App, serial.ToTypedMessage(r))
+	}
+
 	var inbounds []InboundDetourConfig
 
 	if c.InboundConfig != nil {

+ 11 - 0
release/extra/browserforwarder/index.html

@@ -0,0 +1,11 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+    <meta charset="UTF-8">
+    <title>Bridge</title>
+</head>
+<body>
+See debug console for detail
+<script src="index.js"></script>
+</body>
+</html>

File diff suppressed because it is too large
+ 5078 - 0
release/extra/browserforwarder/index.js


+ 37 - 15
transport/internet/websocket/config.pb.go

@@ -81,9 +81,11 @@ type Config struct {
 	unknownFields protoimpl.UnknownFields
 
 	// URL path to the WebSocket service. Empty value means root(/).
-	Path                string    `protobuf:"bytes,2,opt,name=path,proto3" json:"path,omitempty"`
-	Header              []*Header `protobuf:"bytes,3,rep,name=header,proto3" json:"header,omitempty"`
-	AcceptProxyProtocol bool      `protobuf:"varint,4,opt,name=accept_proxy_protocol,json=acceptProxyProtocol,proto3" json:"accept_proxy_protocol,omitempty"`
+	Path                 string    `protobuf:"bytes,2,opt,name=path,proto3" json:"path,omitempty"`
+	Header               []*Header `protobuf:"bytes,3,rep,name=header,proto3" json:"header,omitempty"`
+	AcceptProxyProtocol  bool      `protobuf:"varint,4,opt,name=accept_proxy_protocol,json=acceptProxyProtocol,proto3" json:"accept_proxy_protocol,omitempty"`
+	MaxEarlyData         int32     `protobuf:"varint,5,opt,name=max_early_data,json=maxEarlyData,proto3" json:"max_early_data,omitempty"`
+	UseBrowserForwarding bool      `protobuf:"varint,6,opt,name=use_browser_forwarding,json=useBrowserForwarding,proto3" json:"use_browser_forwarding,omitempty"`
 }
 
 func (x *Config) Reset() {
@@ -139,6 +141,20 @@ func (x *Config) GetAcceptProxyProtocol() bool {
 	return false
 }
 
+func (x *Config) GetMaxEarlyData() int32 {
+	if x != nil {
+		return x.MaxEarlyData
+	}
+	return 0
+}
+
+func (x *Config) GetUseBrowserForwarding() bool {
+	if x != nil {
+		return x.UseBrowserForwarding
+	}
+	return false
+}
+
 var File_transport_internet_websocket_config_proto protoreflect.FileDescriptor
 
 var file_transport_internet_websocket_config_proto_rawDesc = []byte{
@@ -150,7 +166,7 @@ var file_transport_internet_websocket_config_proto_rawDesc = []byte{
 	0x63, 0x6b, 0x65, 0x74, 0x22, 0x30, 0x0a, 0x06, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x12, 0x10,
 	0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79,
 	0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52,
-	0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x22, 0x9f, 0x01, 0x0a, 0x06, 0x43, 0x6f, 0x6e, 0x66, 0x69,
+	0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x22, 0xfb, 0x01, 0x0a, 0x06, 0x43, 0x6f, 0x6e, 0x66, 0x69,
 	0x67, 0x12, 0x12, 0x0a, 0x04, 0x70, 0x61, 0x74, 0x68, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52,
 	0x04, 0x70, 0x61, 0x74, 0x68, 0x12, 0x47, 0x0a, 0x06, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x18,
 	0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2f, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f,
@@ -160,17 +176,23 @@ var file_transport_internet_websocket_config_proto_rawDesc = []byte{
 	0x0a, 0x15, 0x61, 0x63, 0x63, 0x65, 0x70, 0x74, 0x5f, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x5f, 0x70,
 	0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x18, 0x04, 0x20, 0x01, 0x28, 0x08, 0x52, 0x13, 0x61,
 	0x63, 0x63, 0x65, 0x70, 0x74, 0x50, 0x72, 0x6f, 0x78, 0x79, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63,
-	0x6f, 0x6c, 0x4a, 0x04, 0x08, 0x01, 0x10, 0x02, 0x42, 0x96, 0x01, 0x0a, 0x2b, 0x63, 0x6f, 0x6d,
-	0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x74, 0x72, 0x61, 0x6e,
-	0x73, 0x70, 0x6f, 0x72, 0x74, 0x2e, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x65, 0x74, 0x2e, 0x77,
-	0x65, 0x62, 0x73, 0x6f, 0x63, 0x6b, 0x65, 0x74, 0x50, 0x01, 0x5a, 0x3b, 0x67, 0x69, 0x74, 0x68,
-	0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x76, 0x32, 0x66, 0x6c, 0x79, 0x2f, 0x76, 0x32, 0x72,
-	0x61, 0x79, 0x2d, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x76, 0x34, 0x2f, 0x74, 0x72, 0x61, 0x6e, 0x73,
-	0x70, 0x6f, 0x72, 0x74, 0x2f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x65, 0x74, 0x2f, 0x77, 0x65,
-	0x62, 0x73, 0x6f, 0x63, 0x6b, 0x65, 0x74, 0xaa, 0x02, 0x27, 0x56, 0x32, 0x52, 0x61, 0x79, 0x2e,
-	0x43, 0x6f, 0x72, 0x65, 0x2e, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x2e, 0x49,
-	0x6e, 0x74, 0x65, 0x72, 0x6e, 0x65, 0x74, 0x2e, 0x57, 0x65, 0x62, 0x73, 0x6f, 0x63, 0x6b, 0x65,
-	0x74, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
+	0x6f, 0x6c, 0x12, 0x24, 0x0a, 0x0e, 0x6d, 0x61, 0x78, 0x5f, 0x65, 0x61, 0x72, 0x6c, 0x79, 0x5f,
+	0x64, 0x61, 0x74, 0x61, 0x18, 0x05, 0x20, 0x01, 0x28, 0x05, 0x52, 0x0c, 0x6d, 0x61, 0x78, 0x45,
+	0x61, 0x72, 0x6c, 0x79, 0x44, 0x61, 0x74, 0x61, 0x12, 0x34, 0x0a, 0x16, 0x75, 0x73, 0x65, 0x5f,
+	0x62, 0x72, 0x6f, 0x77, 0x73, 0x65, 0x72, 0x5f, 0x66, 0x6f, 0x72, 0x77, 0x61, 0x72, 0x64, 0x69,
+	0x6e, 0x67, 0x18, 0x06, 0x20, 0x01, 0x28, 0x08, 0x52, 0x14, 0x75, 0x73, 0x65, 0x42, 0x72, 0x6f,
+	0x77, 0x73, 0x65, 0x72, 0x46, 0x6f, 0x72, 0x77, 0x61, 0x72, 0x64, 0x69, 0x6e, 0x67, 0x4a, 0x04,
+	0x08, 0x01, 0x10, 0x02, 0x42, 0x96, 0x01, 0x0a, 0x2b, 0x63, 0x6f, 0x6d, 0x2e, 0x76, 0x32, 0x72,
+	0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72,
+	0x74, 0x2e, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x65, 0x74, 0x2e, 0x77, 0x65, 0x62, 0x73, 0x6f,
+	0x63, 0x6b, 0x65, 0x74, 0x50, 0x01, 0x5a, 0x3b, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63,
+	0x6f, 0x6d, 0x2f, 0x76, 0x32, 0x66, 0x6c, 0x79, 0x2f, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2d, 0x63,
+	0x6f, 0x72, 0x65, 0x2f, 0x76, 0x34, 0x2f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74,
+	0x2f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x65, 0x74, 0x2f, 0x77, 0x65, 0x62, 0x73, 0x6f, 0x63,
+	0x6b, 0x65, 0x74, 0xaa, 0x02, 0x27, 0x56, 0x32, 0x52, 0x61, 0x79, 0x2e, 0x43, 0x6f, 0x72, 0x65,
+	0x2e, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x2e, 0x49, 0x6e, 0x74, 0x65, 0x72,
+	0x6e, 0x65, 0x74, 0x2e, 0x57, 0x65, 0x62, 0x73, 0x6f, 0x63, 0x6b, 0x65, 0x74, 0x62, 0x06, 0x70,
+	0x72, 0x6f, 0x74, 0x6f, 0x33,
 }
 
 var (

+ 4 - 0
transport/internet/websocket/config.proto

@@ -20,4 +20,8 @@ message Config {
   repeated Header header = 3;
 
   bool accept_proxy_protocol = 4;
+
+  int32 max_early_data = 5;
+
+  bool use_browser_forwarding = 6;
 }

+ 92 - 0
transport/internet/websocket/connection.go

@@ -3,6 +3,7 @@
 package websocket
 
 import (
+	"context"
 	"io"
 	"net"
 	"time"
@@ -23,6 +24,15 @@ type connection struct {
 	conn       *websocket.Conn
 	reader     io.Reader
 	remoteAddr net.Addr
+
+	shouldWait        bool
+	delayedDialFinish context.Context
+	finishedDial      context.CancelFunc
+	dialer            DelayedDialer
+}
+
+type DelayedDialer interface {
+	Dial(earlyData []byte) (*websocket.Conn, error)
 }
 
 func newConnection(conn *websocket.Conn, remoteAddr net.Addr) *connection {
@@ -32,6 +42,41 @@ func newConnection(conn *websocket.Conn, remoteAddr net.Addr) *connection {
 	}
 }
 
+func newConnectionWithEarlyData(conn *websocket.Conn, remoteAddr net.Addr, earlyData io.Reader) *connection {
+	return &connection{
+		conn:       conn,
+		remoteAddr: remoteAddr,
+		reader:     earlyData,
+	}
+}
+
+func newConnectionWithDelayedDial(dialer DelayedDialer) *connection {
+	delayedDialContext, CancellFunc := context.WithCancel(context.Background())
+	return &connection{
+		shouldWait:        true,
+		delayedDialFinish: delayedDialContext,
+		finishedDial:      CancellFunc,
+		dialer:            dialer,
+	}
+}
+
+func newRelayedConnectionWithDelayedDial(dialer DelayedDialerForwarded) *connectionForwarder {
+	delayedDialContext, CancellFunc := context.WithCancel(context.Background())
+	return &connectionForwarder{
+		shouldWait:        true,
+		delayedDialFinish: delayedDialContext,
+		finishedDial:      CancellFunc,
+		dialer:            dialer,
+	}
+}
+
+func newRelayedConnection(conn io.ReadWriteCloser) *connectionForwarder {
+	return &connectionForwarder{
+		ReadWriteCloser: conn,
+		shouldWait:      false,
+	}
+}
+
 // Read implements net.Conn.Read()
 func (c *connection) Read(b []byte) (int, error) {
 	for {
@@ -50,6 +95,12 @@ func (c *connection) Read(b []byte) (int, error) {
 }
 
 func (c *connection) getReader() (io.Reader, error) {
+	if c.shouldWait {
+		<-c.delayedDialFinish.Done()
+		if c.conn == nil {
+			return nil, newError("unable to read delayed dial websocket connection as it do not exist")
+		}
+	}
 	if c.reader != nil {
 		return c.reader, nil
 	}
@@ -64,6 +115,17 @@ func (c *connection) getReader() (io.Reader, error) {
 
 // Write implements io.Writer.
 func (c *connection) Write(b []byte) (int, error) {
+	if c.shouldWait {
+		var err error
+		c.conn, err = c.dialer.Dial(b)
+		c.finishedDial()
+		if err != nil {
+			return 0, newError("Unable to proceed with delayed write").Base(err)
+		}
+		c.remoteAddr = c.conn.RemoteAddr()
+		c.shouldWait = false
+		return len(b), nil
+	}
 	if err := c.conn.WriteMessage(websocket.BinaryMessage, b); err != nil {
 		return 0, err
 	}
@@ -78,6 +140,12 @@ func (c *connection) WriteMultiBuffer(mb buf.MultiBuffer) error {
 }
 
 func (c *connection) Close() error {
+	if c.shouldWait {
+		<-c.delayedDialFinish.Done()
+		if c.conn == nil {
+			return newError("unable to close delayed dial websocket connection as it do not exist")
+		}
+	}
 	var errors []interface{}
 	if err := c.conn.WriteControl(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""), time.Now().Add(time.Second*5)); err != nil {
 		errors = append(errors, err)
@@ -92,6 +160,16 @@ func (c *connection) Close() error {
 }
 
 func (c *connection) LocalAddr() net.Addr {
+	if c.shouldWait {
+		<-c.delayedDialFinish.Done()
+		if c.conn == nil {
+			newError("websocket transport is not materialized when LocalAddr() is called").AtWarning().WriteToLog()
+			return &net.UnixAddr{
+				Name: "@placeholder",
+				Net:  "unix",
+			}
+		}
+	}
 	return c.conn.LocalAddr()
 }
 
@@ -107,9 +185,23 @@ func (c *connection) SetDeadline(t time.Time) error {
 }
 
 func (c *connection) SetReadDeadline(t time.Time) error {
+	if c.shouldWait {
+		<-c.delayedDialFinish.Done()
+		if c.conn == nil {
+			newError("websocket transport is not materialized when SetReadDeadline() is called").AtWarning().WriteToLog()
+			return nil
+		}
+	}
 	return c.conn.SetReadDeadline(t)
 }
 
 func (c *connection) SetWriteDeadline(t time.Time) error {
+	if c.shouldWait {
+		<-c.delayedDialFinish.Done()
+		if c.conn == nil {
+			newError("websocket transport is not materialized when SetWriteDeadline() is called").AtWarning().WriteToLog()
+			return nil
+		}
+	}
 	return c.conn.SetWriteDeadline(t)
 }

+ 81 - 0
transport/internet/websocket/connforwarder.go

@@ -0,0 +1,81 @@
+package websocket
+
+import (
+	"context"
+	"io"
+	"net"
+	"time"
+)
+
+type connectionForwarder struct {
+	io.ReadWriteCloser
+
+	shouldWait        bool
+	delayedDialFinish context.Context
+	finishedDial      context.CancelFunc
+	dialer            DelayedDialerForwarded
+}
+
+func (c *connectionForwarder) Read(p []byte) (n int, err error) {
+	if c.shouldWait {
+		<-c.delayedDialFinish.Done()
+		if c.ReadWriteCloser == nil {
+			return 0, newError("unable to read delayed dial websocket connection as it do not exist")
+		}
+	}
+	return c.ReadWriteCloser.Read(p)
+}
+
+func (c *connectionForwarder) Write(p []byte) (n int, err error) {
+	if c.shouldWait {
+		var err error
+		c.ReadWriteCloser, err = c.dialer.Dial(p)
+		c.finishedDial()
+		if err != nil {
+			return 0, newError("Unable to proceed with delayed write").Base(err)
+		}
+		c.shouldWait = false
+		return len(p), nil
+	}
+	return c.ReadWriteCloser.Write(p)
+}
+
+func (c *connectionForwarder) Close() error {
+	if c.shouldWait {
+		<-c.delayedDialFinish.Done()
+		if c.ReadWriteCloser == nil {
+			return newError("unable to close delayed dial websocket connection as it do not exist")
+		}
+	}
+	return c.ReadWriteCloser.Close()
+}
+
+func (c connectionForwarder) LocalAddr() net.Addr {
+	return &net.UnixAddr{
+		Name: "not available",
+		Net:  "",
+	}
+}
+
+func (c connectionForwarder) RemoteAddr() net.Addr {
+	return &net.UnixAddr{
+		Name: "not available",
+		Net:  "",
+	}
+}
+
+func (c connectionForwarder) SetDeadline(t time.Time) error {
+	return nil
+}
+
+func (c connectionForwarder) SetReadDeadline(t time.Time) error {
+	return nil
+}
+
+func (c connectionForwarder) SetWriteDeadline(t time.Time) error {
+	return nil
+}
+
+type DelayedDialerForwarded interface {
+	Dial(earlyData []byte) (io.ReadWriteCloser, error)
+}

+ 107 - 0
transport/internet/websocket/dialer.go

@@ -3,9 +3,15 @@
 package websocket
 
 import (
+	"bytes"
 	"context"
+	"encoding/base64"
+	"io"
 	"time"
 
+	core "github.com/v2fly/v2ray-core/v4"
+	"github.com/v2fly/v2ray-core/v4/features/ext"
+
 	"github.com/gorilla/websocket"
 
 	"github.com/v2fly/v2ray-core/v4/common"
@@ -55,6 +61,36 @@ func dialWebsocket(ctx context.Context, dest net.Destination, streamSettings *in
 	}
 	uri := protocol + "://" + host + wsSettings.GetNormalizedPath()
 
+	if wsSettings.UseBrowserForwarding {
+		var forwarder ext.BrowserForwarder
+		err := core.RequireFeatures(ctx, func(Forwarder ext.BrowserForwarder) {
+			forwarder = Forwarder
+		})
+		if err != nil {
+			return nil, newError("cannot find browser forwarder service").Base(err)
+		}
+		if wsSettings.MaxEarlyData != 0 {
+			return newRelayedConnectionWithDelayedDial(&dialerWithEarlyDataRelayed{
+				forwarder: forwarder,
+				uriBase:   uri,
+				config:    wsSettings,
+			}), nil
+		}
+		conn, err := forwarder.DialWebsocket(uri, nil)
+		if err != nil {
+			return nil, newError("cannot dial with browser forwarder service").Base(err)
+		}
+		return newRelayedConnection(conn), nil
+	}
+
+	if wsSettings.MaxEarlyData != 0 {
+		return newConnectionWithDelayedDial(&dialerWithEarlyData{
+			dialer:  dialer,
+			uriBase: uri,
+			config:  wsSettings,
+		}), nil
+	}
+
 	conn, resp, err := dialer.Dial(uri, wsSettings.GetRequestHeader())
 	if err != nil {
 		var reason string
@@ -66,3 +102,74 @@ func dialWebsocket(ctx context.Context, dest net.Destination, streamSettings *in
 
 	return newConnection(conn, conn.RemoteAddr()), nil
 }
+
+type dialerWithEarlyData struct {
+	dialer  *websocket.Dialer
+	uriBase string
+	config  *Config
+}
+
+func (d dialerWithEarlyData) Dial(earlyData []byte) (*websocket.Conn, error) {
+	earlyDataBuf := bytes.NewBuffer(nil)
+	base64EarlyDataEncoder := base64.NewEncoder(base64.RawURLEncoding, earlyDataBuf)
+
+	earlydata := bytes.NewReader(earlyData)
+	limitedEarlyDatareader := io.LimitReader(earlydata, int64(d.config.MaxEarlyData))
+	n, encerr := io.Copy(base64EarlyDataEncoder, limitedEarlyDatareader)
+	if encerr != nil {
+		return nil, newError("websocket delayed dialer cannot encode early data").Base(encerr)
+	}
+
+	if errc := base64EarlyDataEncoder.Close(); errc != nil {
+		return nil, newError("websocket delayed dialer cannot encode early data tail").Base(errc)
+	}
+
+	conn, resp, err := d.dialer.Dial(d.uriBase+earlyDataBuf.String(), d.config.GetRequestHeader())
+	if err != nil {
+		var reason string
+		if resp != nil {
+			reason = resp.Status
+		}
+		return nil, newError("failed to dial to (", d.uriBase, ") with early data: ", reason).Base(err)
+	}
+	if n != int64(len(earlyData)) {
+		if errWrite := conn.WriteMessage(websocket.BinaryMessage, earlyData[n:]); errWrite != nil {
+			return nil, newError("failed to dial to (", d.uriBase, ") with early data as write of remainder early data failed: ").Base(err)
+		}
+	}
+	return conn, nil
+}
+
+type dialerWithEarlyDataRelayed struct {
+	forwarder ext.BrowserForwarder
+	uriBase   string
+	config    *Config
+}
+
+func (d dialerWithEarlyDataRelayed) Dial(earlyData []byte) (io.ReadWriteCloser, error) {
+	earlyDataBuf := bytes.NewBuffer(nil)
+	base64EarlyDataEncoder := base64.NewEncoder(base64.RawURLEncoding, earlyDataBuf)
+
+	earlydata := bytes.NewReader(earlyData)
+	limitedEarlyDatareader := io.LimitReader(earlydata, int64(d.config.MaxEarlyData))
+	n, encerr := io.Copy(base64EarlyDataEncoder, limitedEarlyDatareader)
+	if encerr != nil {
+		return nil, newError("websocket delayed dialer cannot encode early data").Base(encerr)
+	}
+
+	if errc := base64EarlyDataEncoder.Close(); errc != nil {
+		return nil, newError("websocket delayed dialer cannot encode early data tail").Base(errc)
+	}
+
+	conn, err := d.forwarder.DialWebsocket(d.uriBase+earlyDataBuf.String(), d.config.GetRequestHeader())
+	if err != nil {
+		var reason string
+		return nil, newError("failed to dial to (", d.uriBase, ") with early data: ", reason).Base(err)
+	}
+	if n != int64(len(earlyData)) {
+		if _, errWrite := conn.Write(earlyData[n:]); errWrite != nil {
+			return nil, newError("failed to dial to (", d.uriBase, ") with early data as write of remainder early data failed: ").Base(err)
+		}
+	}
+	return conn, nil
+}

Some files were not shown because too many files changed in this diff