From 778767a125b408f9cf66e3e7b2e49a81945b9581 Mon Sep 17 00:00:00 2001 From: eric Date: Sat, 11 May 2019 23:14:38 +0800 Subject: [PATCH 01/19] fix port field parsing. fixes #1684 --- infra/conf/common.go | 8 +++++++- infra/conf/router_test.go | 14 ++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/infra/conf/common.go b/infra/conf/common.go index cc439c3d..b97a200a 100644 --- a/infra/conf/common.go +++ b/infra/conf/common.go @@ -195,8 +195,11 @@ func (list *PortList) Build() *net.PortList { // UnmarshalJSON implements encoding/json.Unmarshaler.UnmarshalJSON func (list *PortList) UnmarshalJSON(data []byte) error { var listStr string + var number uint32 if err := json.Unmarshal(data, &listStr); err != nil { - return newError("invalid port list: ", string(data)).Base(err) + if err2 := json.Unmarshal(data, &number); err2 != nil { + return newError("invalid port: ", string(data)).Base(err2) + } } rangelist := strings.Split(listStr, ",") for _, rangeStr := range rangelist { @@ -217,6 +220,9 @@ func (list *PortList) UnmarshalJSON(data []byte) error { } } } + if number != 0 { + list.Range = append(list.Range, PortRange{From: uint32(number), To: uint32(number)}) + } return nil } diff --git a/infra/conf/router_test.go b/infra/conf/router_test.go index 52676ad2..ac4284dc 100644 --- a/infra/conf/router_test.go +++ b/infra/conf/router_test.go @@ -48,6 +48,10 @@ func TestRouterConfig(t *testing.T) { "type": "field", "port": "53, 443, 1000-2000", "outboundTag": "test" + },{ + "type": "field", + "port": 123, + "outboundTag": "test" } ] }, @@ -114,6 +118,16 @@ func TestRouterConfig(t *testing.T) { Tag: "test", }, }, + { + PortList: &net.PortList{ + Range: []*net.PortRange{ + {From: 123, To: 123}, + }, + }, + TargetTag: &router.RoutingRule_Tag{ + Tag: "test", + }, + }, }, }, }, From 11dddd9864b97ed381eac59eeb788baff2f20624 Mon Sep 17 00:00:00 2001 From: Kslr Date: Fri, 17 May 2019 17:35:34 +0800 Subject: [PATCH 02/19] fly e043c4d, set cache to tmp dir --- infra/bazel/build.bzl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/infra/bazel/build.bzl b/infra/bazel/build.bzl index ceb65fd8..968d5935 100644 --- a/infra/bazel/build.bzl +++ b/infra/bazel/build.bzl @@ -29,7 +29,7 @@ def _go_command(ctx): "GOOS="+ctx.attr.os, "GOARCH="+ctx.attr.arch, "GOROOT_FINAL=/go", - "GOCACHE=@D", + "GOCACHE=${TMPDIR}/gocache" ] if ctx.attr.mips: # https://github.com/golang/go/issues/27260 From c5635f95079c71d459ec20a1024f39285466fbd5 Mon Sep 17 00:00:00 2001 From: Kslr Date: Fri, 17 May 2019 17:54:04 +0800 Subject: [PATCH 03/19] sync fly, enable tls 1.3 --- transport/internet/tls/config.go | 4 ++++ transport/internet/tls/tls13_workaround.go | 16 ++++++++++++++++ 2 files changed, 20 insertions(+) create mode 100644 transport/internet/tls/tls13_workaround.go diff --git a/transport/internet/tls/config.go b/transport/internet/tls/config.go index 1ac36940..4f8bed7e 100644 --- a/transport/internet/tls/config.go +++ b/transport/internet/tls/config.go @@ -188,6 +188,10 @@ func (c *Config) GetTLSConfig(opts ...Option) *tls.Config { if !c.AllowInsecureCiphers && len(config.CipherSuites) == 0 { config.CipherSuites = []uint16{ + tls.TLS_AES_128_GCM_SHA256, + tls.TLS_AES_256_GCM_SHA384, + tls.TLS_CHACHA20_POLY1305_SHA256, + tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, diff --git a/transport/internet/tls/tls13_workaround.go b/transport/internet/tls/tls13_workaround.go new file mode 100644 index 00000000..fbc3a8b4 --- /dev/null +++ b/transport/internet/tls/tls13_workaround.go @@ -0,0 +1,16 @@ +// +build !confonly + +package tls + +import ( + "os" + "strings" +) + +func init() { + // opt-in TLS 1.3 for Go1.12 + // TODO: remove this line when Go1.13 is released. + if !strings.Contains(os.Getenv("GODEBUG"), "tls13") { + _ = os.Setenv("GODEBUG", os.Getenv("GODEBUG")+",tls13=1") + } +} From 0563d3a4bf465fc246f0b6432230ab66f9a3b695 Mon Sep 17 00:00:00 2001 From: heapops Date: Sat, 18 May 2019 13:10:40 +0800 Subject: [PATCH 04/19] Fix ip rule with custom geoip file Signed-off-by: heapops --- infra/conf/router.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/infra/conf/router.go b/infra/conf/router.go index 5a4e2949..9c697349 100644 --- a/infra/conf/router.go +++ b/infra/conf/router.go @@ -323,7 +323,7 @@ func toCidrList(ips StringList) ([]*router.GeoIP, error) { filename := kv[0] country := kv[1] - geoip, err := loadGeoIP(strings.ToUpper(country)) + geoip, err := loadIP(filename, strings.ToUpper(country)) if err != nil { return nil, newError("failed to load IPs: ", country, " from ", filename).Base(err) } From c6f3ab48ee12a1fb2071c70179a2de8e7fa169ee Mon Sep 17 00:00:00 2001 From: Kslr Date: Sat, 18 May 2019 15:09:58 +0800 Subject: [PATCH 05/19] fixed ReadV issue for windows sync https://github.com/v2fly/v2ray-core/commit/847b289798eca6ec90b3733288a27887c7427522 --- common/buf/io.go | 7 ++++- common/buf/readv_constraint_other.go | 9 +++++++ common/buf/readv_constraint_windows.go | 37 ++++++++++++++++++++++++++ 3 files changed, 52 insertions(+), 1 deletion(-) create mode 100644 common/buf/readv_constraint_other.go create mode 100644 common/buf/readv_constraint_windows.go diff --git a/common/buf/io.go b/common/buf/io.go index 938e347b..c13a35aa 100644 --- a/common/buf/io.go +++ b/common/buf/io.go @@ -63,7 +63,12 @@ func NewReader(reader io.Reader) Reader { if err != nil { newError("failed to get sysconn").Base(err).WriteToLog() } else { - return NewReadVReader(reader, rawConn) + /* Check if ReadVReader Can be used on this reader first + Fix https://github.com/v2ray/v2ray-core/issues/1666 + */ + if ok, _ := checkReadVConstraint(rawConn); ok { + return NewReadVReader(reader, rawConn) + } } } } diff --git a/common/buf/readv_constraint_other.go b/common/buf/readv_constraint_other.go new file mode 100644 index 00000000..315ce61f --- /dev/null +++ b/common/buf/readv_constraint_other.go @@ -0,0 +1,9 @@ +// +build !windows + +package buf + +import "syscall" + +func checkReadVConstraint(conn syscall.RawConn) (bool, error) { + return true, nil +} diff --git a/common/buf/readv_constraint_windows.go b/common/buf/readv_constraint_windows.go new file mode 100644 index 00000000..d78cbaa8 --- /dev/null +++ b/common/buf/readv_constraint_windows.go @@ -0,0 +1,37 @@ +// +build windows +package buf + +import ( + "syscall" +) + +func checkReadVConstraint(conn syscall.RawConn) (bool, error) { + var isSocketReady = false + var reason error + /* + In Windows, WSARecv system call only support socket connection. + + It it required to check if the given fd is of a socket type + + Fix https://github.com/v2ray/v2ray-core/issues/1666 + + Additional Information: + https://docs.microsoft.com/en-us/windows/desktop/api/winsock2/nf-winsock2-wsarecv + https://docs.microsoft.com/en-us/windows/desktop/api/winsock/nf-winsock-getsockopt + https://docs.microsoft.com/en-us/windows/desktop/WinSock/sol-socket-socket-options + + */ + err := conn.Control(func(fd uintptr) { + var val [4]byte + var le = int32(len(val)) + err := syscall.Getsockopt(syscall.Handle(fd), syscall.SOL_SOCKET, syscall.SO_RCVBUF, &val[0], &le) + if err != nil { + isSocketReady = false + } else { + isSocketReady = true + } + reason = err + }) + + return isSocketReady, err +} From be27720c748502673a2e88e7bcfa592a0070937e Mon Sep 17 00:00:00 2001 From: Kslr Date: Sat, 18 May 2019 15:13:49 +0800 Subject: [PATCH 06/19] fix codestyle --- common/buf/io.go | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/common/buf/io.go b/common/buf/io.go index c13a35aa..cf27ba89 100644 --- a/common/buf/io.go +++ b/common/buf/io.go @@ -63,8 +63,9 @@ func NewReader(reader io.Reader) Reader { if err != nil { newError("failed to get sysconn").Base(err).WriteToLog() } else { - /* Check if ReadVReader Can be used on this reader first - Fix https://github.com/v2ray/v2ray-core/issues/1666 + /* + Check if ReadVReader Can be used on this reader first + Fix https://github.com/v2ray/v2ray-core/issues/1666 */ if ok, _ := checkReadVConstraint(rawConn); ok { return NewReadVReader(reader, rawConn) From 548910c205eafe724dbfe3d19363473ff111fc98 Mon Sep 17 00:00:00 2001 From: sunshineplan Date: Tue, 28 May 2019 14:22:43 +0800 Subject: [PATCH 07/19] Update install-release.sh --- release/install-release.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/release/install-release.sh b/release/install-release.sh index 6c5a771c..05f14a7f 100755 --- a/release/install-release.sh +++ b/release/install-release.sh @@ -430,7 +430,7 @@ main(){ getVersion RETVAL="$?" if [[ $RETVAL == 0 ]] && [[ "$FORCE" != "1" ]]; then - colorEcho ${BLUE} "Latest version ${NEW_VER} is already installed." + colorEcho ${BLUE} "Latest version ${CUR_VER} is already installed." if [[ "${ERROR_IF_UPTODATE}" == "1" ]]; then return 10 fi From 44d1c088e792988223a922497aad8ea80fb0ce8e Mon Sep 17 00:00:00 2001 From: sunshineplan Date: Tue, 28 May 2019 21:52:40 +0800 Subject: [PATCH 08/19] Update install-release.sh --- release/install-release.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/release/install-release.sh b/release/install-release.sh index 05f14a7f..01ee2aea 100755 --- a/release/install-release.sh +++ b/release/install-release.sh @@ -220,7 +220,7 @@ getVersion(){ return 3 elif [[ $RETVAL -ne 0 ]];then return 2 - elif [[ `echo $NEW_VER | cut -d. -f-2` != `echo $CUR_VER | cut -d. -f-2` ]];then + elif [[ $NEW_VER != $CUR_VER ]];then return 1 fi return 0 From eb3df1a58e871f03165a9896179ec97c87549603 Mon Sep 17 00:00:00 2001 From: Kslr Date: Mon, 3 Jun 2019 14:52:35 +0800 Subject: [PATCH 09/19] fix: json field tag syntax sync https://github.com/v2fly/v2ray-core/commit/ad4f41e1c0fd6096aa738004140ec9ca4f4db1bd --- infra/conf/dns_proxy.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/infra/conf/dns_proxy.go b/infra/conf/dns_proxy.go index e93d1ec8..4617ead5 100644 --- a/infra/conf/dns_proxy.go +++ b/infra/conf/dns_proxy.go @@ -7,9 +7,9 @@ import ( ) type DnsOutboundConfig struct { - Network Network `json:network` - Address *Address `json:address` - Port uint16 `json:port` + Network Network `json:"network"` + Address *Address `json:"address"` + Port uint16 `json:"port"` } func (c *DnsOutboundConfig) Build() (proto.Message, error) { From 16e9d39fff7417568f9e7e7df3aec60ab038c6d3 Mon Sep 17 00:00:00 2001 From: Kslr Date: Mon, 3 Jun 2019 15:15:32 +0800 Subject: [PATCH 10/19] version 4.19.1 --- core.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core.go b/core.go index 5293d5fa..dc18a3c3 100755 --- a/core.go +++ b/core.go @@ -17,7 +17,7 @@ import ( ) const ( - version = "4.19" + version = "4.19.1" build = "Custom" codename = "Po" intro = "A unified platform for anti-censorship." From 79cf94be6c746d81abdf94da7017dfa62de8fc1d Mon Sep 17 00:00:00 2001 From: boypt <1033514+boypt@users.noreply.github.com> Date: Tue, 11 Jun 2019 15:29:52 +0800 Subject: [PATCH 11/19] add: mute access/error logger seperately --- infra/conf/log.go | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/infra/conf/log.go b/infra/conf/log.go index 329849fa..016eb226 100644 --- a/infra/conf/log.go +++ b/infra/conf/log.go @@ -30,11 +30,15 @@ func (v *LogConfig) Build() *log.Config { AccessLogType: log.LogType_Console, } - if len(v.AccessLog) > 0 { + if v.AccessLog == "none" { + config.AccessLogType = log.LogType_None + } else if len(v.AccessLog) > 0 { config.AccessLogPath = v.AccessLog config.AccessLogType = log.LogType_File } - if len(v.ErrorLog) > 0 { + if v.ErrorLog == "none" { + config.ErrorLogType = log.LogType_None + } else if len(v.ErrorLog) > 0 { config.ErrorLogPath = v.ErrorLog config.ErrorLogType = log.LogType_File } From a0aa7b737446f6557424d1160389a50b06c2b1c1 Mon Sep 17 00:00:00 2001 From: lucifer9 Date: Wed, 26 Jun 2019 13:51:33 +0800 Subject: [PATCH 12/19] fix incompatible errors when building with bazel 0.26+ --- infra/bazel/zip.bzl | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/infra/bazel/zip.bzl b/infra/bazel/zip.bzl index ac6b12a3..fc3ae2f5 100644 --- a/infra/bazel/zip.bzl +++ b/infra/bazel/zip.bzl @@ -47,10 +47,10 @@ def _zip_file(ctx): if (s.startswith("/") or s.endswith("/") or d.startswith("/") or d.endswith("/")): fail("mappings should not begin or end with slash") - srcs = depset() - srcs += ctx.files.srcs - srcs += ctx.files.data - srcs += collect_runfiles(ctx.attr.data) + srcs = depset(transitive = [depset(ctx.files.srcs),depset(ctx.files.data),depset(collect_runfiles(ctx.attr.data))]) + # srcs += ctx.files.srcs + # srcs += ctx.files.data + # srcs += collect_runfiles(ctx.attr.data) mapped = _map_sources(ctx, srcs, ctx.attr.mappings) cmd = [ "#!/bin/sh", @@ -74,7 +74,7 @@ def _zip_file(ctx): for _, zip_path in mapped if "/" in zip_path ], - ) + ).to_list() ] cmd += [ 'ln -sf "${repo}/%s" "${tmp}/%s"' % (path, zip_path) @@ -86,12 +86,12 @@ def _zip_file(ctx): 'cd "${repo}"', 'rm -rf "${tmp}"', ] - script = ctx.new_file(ctx.bin_dir, "%s.sh" % ctx.label.name) - ctx.file_action(output = script, content = "\n".join(cmd), executable = True) + script = ctx.actions.declare_file("%s/%s.sh" % (ctx.bin_dir, ctx.label.name)) + ctx.actions.write(output = script, content = "\n".join(cmd), is_executable = True) inputs = [ctx.file._zipper] inputs += [dep.zip_file for dep in ctx.attr.deps] - inputs += list(srcs) - ctx.action( + inputs += list(srcs.to_list()) + ctx.actions.run( inputs = inputs, outputs = [ctx.outputs.out], executable = script, @@ -117,7 +117,7 @@ def _map_sources(ctx, srcs, mappings): mappings_indexes = range(len(mappings)) used = {i: False for i in mappings_indexes} mapped = [] - for file_ in srcs: + for file_ in srcs.to_list(): run_path = long_path(ctx, file_) zip_path = None for i in mappings_indexes: @@ -159,6 +159,6 @@ pkg_zip = rule( "deps": attr.label_list(providers = ["zip_file"]), "exclude": attr.string_list(), "mappings": attr.string_dict(), - "_zipper": attr.label(default = Label(ZIPPER), single_file = True), + "_zipper": attr.label(default = Label(ZIPPER), allow_single_file = True), }, ) From e744537b8074b6e1a40bd5e1b007b4093d7e0650 Mon Sep 17 00:00:00 2001 From: lucifer9 Date: Thu, 27 Jun 2019 14:21:40 +0800 Subject: [PATCH 13/19] add server-side http2 over tcp (h2c) support --- transport/internet/http/hub.go | 78 +++++++++++++++++++++++----------- 1 file changed, 54 insertions(+), 24 deletions(-) diff --git a/transport/internet/http/hub.go b/transport/internet/http/hub.go index 1ec53c5d..f2d9fdbf 100644 --- a/transport/internet/http/hub.go +++ b/transport/internet/http/hub.go @@ -16,6 +16,9 @@ import ( "v2ray.com/core/common/signal/done" "v2ray.com/core/transport/internet" "v2ray.com/core/transport/internet/tls" + + "golang.org/x/net/http2" + "golang.org/x/net/http2/h2c" ) type Listener struct { @@ -104,34 +107,61 @@ func Listen(ctx context.Context, address net.Address, port net.Port, streamSetti config := tls.ConfigFromStreamSettings(streamSettings) if config == nil { - return nil, newError("TLS must be enabled for http transport.").AtWarning() - } + // return nil, newError("TLS must be enabled for http transport.").AtWarning() + h2s:=&http2.Server{} - server := &http.Server{ - Addr: serial.Concat(address, ":", port), - TLSConfig: config.GetTLSConfig(tls.WithNextProto("h2")), - Handler: listener, - ReadHeaderTimeout: time.Second * 4, - } - - listener.server = server - go func() { - tcpListener, err := internet.ListenSystem(ctx, &net.TCPAddr{ - IP: address.IP(), - Port: int(port), - }, streamSettings.SocketSettings) - if err != nil { - newError("failed to listen on", address, ":", port).Base(err).WriteToLog(session.ExportIDToError(ctx)) - return + server := &http.Server{ + Addr: serial.Concat(address, ":", port), + // TLSConfig: config.GetTLSConfig(tls.WithNextProto("h2")), + Handler: h2c.NewHandler(listener,h2s), + ReadHeaderTimeout: time.Second * 4, } - err = server.ServeTLS(tcpListener, "", "") - if err != nil { - newError("stoping serving TLS").Base(err).WriteToLog(session.ExportIDToError(ctx)) - } - }() + listener.server = server + go func() { + tcpListener, err := internet.ListenSystem(ctx, &net.TCPAddr{ + IP: address.IP(), + Port: int(port), + }, streamSettings.SocketSettings) + if err != nil { + newError("failed to listen on", address, ":", port).Base(err).WriteToLog(session.ExportIDToError(ctx)) + return + } - return listener, nil + err = server.Serve(tcpListener) + if err != nil { + newError("stoping serving H2C").Base(err).WriteToLog(session.ExportIDToError(ctx)) + } + }() + + return listener, nil + } else { + server := &http.Server{ + Addr: serial.Concat(address, ":", port), + TLSConfig: config.GetTLSConfig(tls.WithNextProto("h2")), + Handler: listener, + ReadHeaderTimeout: time.Second * 4, + } + + listener.server = server + go func() { + tcpListener, err := internet.ListenSystem(ctx, &net.TCPAddr{ + IP: address.IP(), + Port: int(port), + }, streamSettings.SocketSettings) + if err != nil { + newError("failed to listen on", address, ":", port).Base(err).WriteToLog(session.ExportIDToError(ctx)) + return + } + + err = server.ServeTLS(tcpListener, "", "") + if err != nil { + newError("stoping serving TLS").Base(err).WriteToLog(session.ExportIDToError(ctx)) + } + }() + + return listener, nil + } } func init() { From 1955d72e3e5ceb8a6ca72b705c05094240e81a74 Mon Sep 17 00:00:00 2001 From: lucifer9 Date: Thu, 27 Jun 2019 14:27:47 +0800 Subject: [PATCH 14/19] fix some lint warnings. --- transport/internet/http/hub.go | 54 ++++++++++++++++------------------ 1 file changed, 26 insertions(+), 28 deletions(-) diff --git a/transport/internet/http/hub.go b/transport/internet/http/hub.go index f2d9fdbf..721e0c7a 100644 --- a/transport/internet/http/hub.go +++ b/transport/internet/http/hub.go @@ -108,12 +108,12 @@ func Listen(ctx context.Context, address net.Address, port net.Port, streamSetti config := tls.ConfigFromStreamSettings(streamSettings) if config == nil { // return nil, newError("TLS must be enabled for http transport.").AtWarning() - h2s:=&http2.Server{} + h2s := &http2.Server{} server := &http.Server{ - Addr: serial.Concat(address, ":", port), + Addr: serial.Concat(address, ":", port), // TLSConfig: config.GetTLSConfig(tls.WithNextProto("h2")), - Handler: h2c.NewHandler(listener,h2s), + Handler: h2c.NewHandler(listener, h2s), ReadHeaderTimeout: time.Second * 4, } @@ -135,33 +135,31 @@ func Listen(ctx context.Context, address net.Address, port net.Port, streamSetti }() return listener, nil - } else { - server := &http.Server{ - Addr: serial.Concat(address, ":", port), - TLSConfig: config.GetTLSConfig(tls.WithNextProto("h2")), - Handler: listener, - ReadHeaderTimeout: time.Second * 4, + } + server := &http.Server{ + Addr: serial.Concat(address, ":", port), + TLSConfig: config.GetTLSConfig(tls.WithNextProto("h2")), + Handler: listener, + ReadHeaderTimeout: time.Second * 4, + } + + listener.server = server + go func() { + tcpListener, err := internet.ListenSystem(ctx, &net.TCPAddr{ + IP: address.IP(), + Port: int(port), + }, streamSettings.SocketSettings) + if err != nil { + newError("failed to listen on", address, ":", port).Base(err).WriteToLog(session.ExportIDToError(ctx)) + return } - listener.server = server - go func() { - tcpListener, err := internet.ListenSystem(ctx, &net.TCPAddr{ - IP: address.IP(), - Port: int(port), - }, streamSettings.SocketSettings) - if err != nil { - newError("failed to listen on", address, ":", port).Base(err).WriteToLog(session.ExportIDToError(ctx)) - return - } - - err = server.ServeTLS(tcpListener, "", "") - if err != nil { - newError("stoping serving TLS").Base(err).WriteToLog(session.ExportIDToError(ctx)) - } - }() - - return listener, nil - } + err = server.ServeTLS(tcpListener, "", "") + if err != nil { + newError("stoping serving TLS").Base(err).WriteToLog(session.ExportIDToError(ctx)) + } + }() + return listener, nil } func init() { From 0401a91ef49befdd7d9dafbced973b211c97b616 Mon Sep 17 00:00:00 2001 From: Kirill Motkov Date: Fri, 14 Jun 2019 16:47:28 +0300 Subject: [PATCH 15/19] Some code improvements * Rewrite empty string checks more idiomatically. * Change strings.ToLower comparisons to strings.EqualFold. * Rewrite switch statement with only one case as if. --- app/dns/server.go | 4 ++-- app/proxyman/inbound/inbound.go | 2 +- app/proxyman/outbound/outbound.go | 2 +- app/reverse/bridge.go | 4 ++-- app/reverse/portal.go | 4 ++-- app/router/balancing.go | 2 +- common/protocol/http/headers.go | 4 ++-- common/protocol/http/sniff.go | 2 +- common/protocol/tls/sniff.go | 3 +-- common/strmatcher/domain_matcher.go | 2 +- infra/conf/api.go | 2 +- infra/conf/router.go | 2 +- infra/conf/shadowsocks.go | 4 ++-- infra/conf/transport_internet.go | 6 +++--- infra/control/cert.go | 2 +- infra/control/command.go | 2 +- infra/control/verify.go | 4 ++-- proxy/http/server.go | 10 +++++----- proxy/vmess/inbound/inbound.go | 2 +- proxy/vmess/validator.go | 2 +- transport/internet/domainsocket/config.go | 2 +- transport/internet/headers/http/config.go | 2 +- transport/internet/http/config.go | 2 +- transport/internet/tls/config.go | 2 +- transport/internet/tls/tls.go | 2 +- transport/internet/websocket/config.go | 2 +- 26 files changed, 38 insertions(+), 39 deletions(-) diff --git a/app/dns/server.go b/app/dns/server.go index e4fc34eb..48165c0b 100644 --- a/app/dns/server.go +++ b/app/dns/server.go @@ -42,7 +42,7 @@ func New(ctx context.Context, config *Config) (*Server, error) { clients: make([]Client, 0, len(config.NameServers)+len(config.NameServer)), tag: config.Tag, } - if len(server.tag) == 0 { + if server.tag == "" { server.tag = generateRandomTag() } if len(config.ClientIp) > 0 { @@ -196,7 +196,7 @@ func toNetIP(ips []net.Address) []net.IP { } func (s *Server) lookupIPInternal(domain string, option IPOption) ([]net.IP, error) { - if len(domain) == 0 { + if domain == "" { return nil, newError("empty domain name") } diff --git a/app/proxyman/inbound/inbound.go b/app/proxyman/inbound/inbound.go index e80015e1..52835694 100644 --- a/app/proxyman/inbound/inbound.go +++ b/app/proxyman/inbound/inbound.go @@ -68,7 +68,7 @@ func (m *Manager) GetHandler(ctx context.Context, tag string) (inbound.Handler, // RemoveHandler implements inbound.Manager. func (m *Manager) RemoveHandler(ctx context.Context, tag string) error { - if len(tag) == 0 { + if tag == "" { return common.ErrNoClue } diff --git a/app/proxyman/outbound/outbound.go b/app/proxyman/outbound/outbound.go index ce5cc5c7..0b489945 100644 --- a/app/proxyman/outbound/outbound.go +++ b/app/proxyman/outbound/outbound.go @@ -123,7 +123,7 @@ func (m *Manager) AddHandler(ctx context.Context, handler outbound.Handler) erro // RemoveHandler implements outbound.Manager. func (m *Manager) RemoveHandler(ctx context.Context, tag string) error { - if len(tag) == 0 { + if tag == "" { return common.ErrNoClue } m.access.Lock() diff --git a/app/reverse/bridge.go b/app/reverse/bridge.go index 3be8f7c4..50274548 100644 --- a/app/reverse/bridge.go +++ b/app/reverse/bridge.go @@ -27,10 +27,10 @@ type Bridge struct { // NewBridge creates a new Bridge instance. func NewBridge(config *BridgeConfig, dispatcher routing.Dispatcher) (*Bridge, error) { - if len(config.Tag) == 0 { + if config.Tag == "" { return nil, newError("bridge tag is empty") } - if len(config.Domain) == 0 { + if config.Domain == "" { return nil, newError("bridge domain is empty") } diff --git a/app/reverse/portal.go b/app/reverse/portal.go index 8d624cd9..ed846fe0 100644 --- a/app/reverse/portal.go +++ b/app/reverse/portal.go @@ -28,11 +28,11 @@ type Portal struct { } func NewPortal(config *PortalConfig, ohm outbound.Manager) (*Portal, error) { - if len(config.Tag) == 0 { + if config.Tag == "" { return nil, newError("portal tag is empty") } - if len(config.Domain) == 0 { + if config.Domain == "" { return nil, newError("portal domain is empty") } diff --git a/app/router/balancing.go b/app/router/balancing.go index c6debe6a..0cede392 100644 --- a/app/router/balancing.go +++ b/app/router/balancing.go @@ -39,7 +39,7 @@ func (b *Balancer) PickOutbound() (string, error) { return "", newError("no available outbounds selected") } tag := b.strategy.PickOutbound(tags) - if len(tag) == 0 { + if tag == "" { return "", newError("balancing strategy returns empty tag") } return tag, nil diff --git a/common/protocol/http/headers.go b/common/protocol/http/headers.go index db497ac4..95eb5306 100644 --- a/common/protocol/http/headers.go +++ b/common/protocol/http/headers.go @@ -11,7 +11,7 @@ import ( // ParseXForwardedFor parses X-Forwarded-For header in http headers, and return the IP list in it. func ParseXForwardedFor(header http.Header) []net.Address { xff := header.Get("X-Forwarded-For") - if len(xff) == 0 { + if xff == "" { return nil } list := strings.Split(xff, ",") @@ -38,7 +38,7 @@ func RemoveHopByHopHeaders(header http.Header) { connections := header.Get("Connection") header.Del("Connection") - if len(connections) == 0 { + if connections == "" { return } for _, h := range strings.Split(connections, ",") { diff --git a/common/protocol/http/sniff.go b/common/protocol/http/sniff.go index 79ac4ad1..9974dd27 100644 --- a/common/protocol/http/sniff.go +++ b/common/protocol/http/sniff.go @@ -44,7 +44,7 @@ var ( func beginWithHTTPMethod(b []byte) error { for _, m := range &methods { - if len(b) >= len(m) && strings.ToLower(string(b[:len(m)])) == m { + if len(b) >= len(m) && strings.EqualFold(string(b[:len(m)]), m) { return nil } diff --git a/common/protocol/tls/sniff.go b/common/protocol/tls/sniff.go index 85ca4820..a4df5c79 100644 --- a/common/protocol/tls/sniff.go +++ b/common/protocol/tls/sniff.go @@ -81,8 +81,7 @@ func ReadClientHello(data []byte, h *SniffHeader) error { return errNotClientHello } - switch extension { - case 0x00: /* extensionServerName */ + if extension == 0x00 { /* extensionServerName */ d := data[:length] if len(d) < 2 { return errNotClientHello diff --git a/common/strmatcher/domain_matcher.go b/common/strmatcher/domain_matcher.go index 750c7af9..aabbf43e 100644 --- a/common/strmatcher/domain_matcher.go +++ b/common/strmatcher/domain_matcher.go @@ -51,7 +51,7 @@ func (g *DomainMatcherGroup) addMatcher(m domainMatcher, value uint32) { } func (g *DomainMatcherGroup) Match(domain string) uint32 { - if len(domain) == 0 { + if domain == "" { return 0 } diff --git a/infra/conf/api.go b/infra/conf/api.go index 7856138d..4ddfe37b 100644 --- a/infra/conf/api.go +++ b/infra/conf/api.go @@ -16,7 +16,7 @@ type ApiConfig struct { } func (c *ApiConfig) Build() (*commander.Config, error) { - if len(c.Tag) == 0 { + if c.Tag == "" { return nil, newError("Api tag can't be empty.") } diff --git a/infra/conf/router.go b/infra/conf/router.go index 9c697349..b3870e45 100644 --- a/infra/conf/router.go +++ b/infra/conf/router.go @@ -23,7 +23,7 @@ type BalancingRule struct { } func (r *BalancingRule) Build() (*router.BalancingRule, error) { - if len(r.Tag) == 0 { + if r.Tag == "" { return nil, newError("empty balancer tag") } if len(r.Selectors) == 0 { diff --git a/infra/conf/shadowsocks.go b/infra/conf/shadowsocks.go index 7e4e6194..8f61ccf8 100644 --- a/infra/conf/shadowsocks.go +++ b/infra/conf/shadowsocks.go @@ -46,7 +46,7 @@ func (v *ShadowsocksServerConfig) Build() (proto.Message, error) { config.UdpEnabled = v.UDP config.Network = v.NetworkList.Build() - if len(v.Password) == 0 { + if v.Password == "" { return nil, newError("Shadowsocks password is not specified.") } account := &shadowsocks.Account{ @@ -103,7 +103,7 @@ func (v *ShadowsocksClientConfig) Build() (proto.Message, error) { if server.Port == 0 { return nil, newError("Invalid Shadowsocks port.") } - if len(server.Password) == 0 { + if server.Password == "" { return nil, newError("Shadowsocks password is not specified.") } account := &shadowsocks.Account{ diff --git a/infra/conf/transport_internet.go b/infra/conf/transport_internet.go index f5417f03..9000e24c 100644 --- a/infra/conf/transport_internet.go +++ b/infra/conf/transport_internet.go @@ -134,7 +134,7 @@ type WebSocketConfig struct { // Build implements Buildable. func (c *WebSocketConfig) Build() (proto.Message, error) { path := c.Path - if len(path) == 0 && len(c.Path2) > 0 { + if path == "" && c.Path2 != "" { path = c.Path2 } header := make([]*websocket.Header, 0, 32) @@ -380,7 +380,7 @@ func (c *StreamConfig) Build() (*internet.StreamConfig, error) { } config.ProtocolName = protocol } - if strings.ToLower(c.Security) == "tls" { + if strings.EqualFold(c.Security, "tls") { tlsSettings := c.TLSSettings if tlsSettings == nil { tlsSettings = &TLSConfig{} @@ -469,7 +469,7 @@ type ProxyConfig struct { // Build implements Buildable. func (v *ProxyConfig) Build() (*internet.ProxyConfig, error) { - if len(v.Tag) == 0 { + if v.Tag == "" { return nil, newError("Proxy tag is not set.") } return &internet.ProxyConfig{ diff --git a/infra/control/cert.go b/infra/control/cert.go index bcda6974..1112c73e 100644 --- a/infra/control/cert.go +++ b/infra/control/cert.go @@ -21,7 +21,7 @@ func (l *stringList) String() string { } func (l *stringList) Set(v string) error { - if len(v) == 0 { + if v == "" { return newError("empty value") } *l = append(*l, v) diff --git a/infra/control/command.go b/infra/control/command.go index 3bd3c804..a261646a 100644 --- a/infra/control/command.go +++ b/infra/control/command.go @@ -22,7 +22,7 @@ var ( func RegisterCommand(cmd Command) error { entry := strings.ToLower(cmd.Name()) - if len(entry) == 0 { + if entry == "" { return newError("empty command name") } commandRegistry[entry] = cmd diff --git a/infra/control/verify.go b/infra/control/verify.go index 5cb09e4b..3aeab578 100644 --- a/infra/control/verify.go +++ b/infra/control/verify.go @@ -128,11 +128,11 @@ func (c *VerifyCommand) Execute(args []string) error { } target := fs.Arg(0) - if len(target) == 0 { + if target == "" { return newError("empty file path.") } - if len(*sigFile) == 0 { + if *sigFile == "" { *sigFile = target + ".sig" } diff --git a/proxy/http/server.go b/proxy/http/server.go index 3ab9d311..7d7bcb54 100755 --- a/proxy/http/server.go +++ b/proxy/http/server.go @@ -120,11 +120,11 @@ Start: } defaultPort := net.Port(80) - if strings.ToLower(request.URL.Scheme) == "https" { + if strings.EqualFold(request.URL.Scheme, "https") { defaultPort = net.Port(443) } host := request.Host - if len(host) == 0 { + if host == "" { host = request.URL.Host } dest, err := http_proto.ParseHost(host, defaultPort) @@ -137,7 +137,7 @@ Start: Status: log.AccessAccepted, }) - if strings.ToUpper(request.Method) == "CONNECT" { + if strings.EqualFold(request.Method, "CONNECT") { return s.handleConnect(ctx, request, reader, conn, dest, dispatcher) } @@ -211,7 +211,7 @@ func (s *Server) handleConnect(ctx context.Context, request *http.Request, reade var errWaitAnother = newError("keep alive") func (s *Server) handlePlainHTTP(ctx context.Context, request *http.Request, writer io.Writer, dest net.Destination, dispatcher routing.Dispatcher) error { - if !s.config.AllowTransparent && len(request.URL.Host) <= 0 { + if !s.config.AllowTransparent && request.URL.Host == "" { // RFC 2068 (HTTP/1.1) requires URL to be absolute URL in HTTP proxy. response := &http.Response{ Status: "Bad Request", @@ -235,7 +235,7 @@ func (s *Server) handlePlainHTTP(ctx context.Context, request *http.Request, wri http_proto.RemoveHopByHopHeaders(request.Header) // Prevent UA from being set to golang's default ones - if len(request.Header.Get("User-Agent")) == 0 { + if request.Header.Get("User-Agent") == "" { request.Header.Set("User-Agent", "") } diff --git a/proxy/vmess/inbound/inbound.go b/proxy/vmess/inbound/inbound.go index 92415718..540d1f66 100644 --- a/proxy/vmess/inbound/inbound.go +++ b/proxy/vmess/inbound/inbound.go @@ -167,7 +167,7 @@ func (h *Handler) AddUser(ctx context.Context, user *protocol.MemoryUser) error } func (h *Handler) RemoveUser(ctx context.Context, email string) error { - if len(email) == 0 { + if email == "" { return newError("Email must not be empty.") } if !h.usersByEmail.Remove(email) { diff --git a/proxy/vmess/validator.go b/proxy/vmess/validator.go index 8a2cffe2..1690fac7 100644 --- a/proxy/vmess/validator.go +++ b/proxy/vmess/validator.go @@ -149,7 +149,7 @@ func (v *TimedUserValidator) Remove(email string) bool { email = strings.ToLower(email) idx := -1 for i, u := range v.users { - if strings.ToLower(u.user.Email) == email { + if strings.EqualFold(u.user.Email, email) { idx = i break } diff --git a/transport/internet/domainsocket/config.go b/transport/internet/domainsocket/config.go index ca80c351..09cfabb2 100644 --- a/transport/internet/domainsocket/config.go +++ b/transport/internet/domainsocket/config.go @@ -12,7 +12,7 @@ const protocolName = "domainsocket" func (c *Config) GetUnixAddr() (*net.UnixAddr, error) { path := c.Path - if len(path) == 0 { + if path == "" { return nil, newError("empty domain socket path") } if c.Abstract && path[0] != '\x00' { diff --git a/transport/internet/headers/http/config.go b/transport/internet/headers/http/config.go index 99f015bf..32a068eb 100644 --- a/transport/internet/headers/http/config.go +++ b/transport/internet/headers/http/config.go @@ -57,7 +57,7 @@ func (v *RequestConfig) GetFullVersion() string { func (v *ResponseConfig) HasHeader(header string) bool { cHeader := strings.ToLower(header) for _, tHeader := range v.Header { - if strings.ToLower(tHeader.Name) == cHeader { + if strings.EqualFold(tHeader.Name, cHeader) { return true } } diff --git a/transport/internet/http/config.go b/transport/internet/http/config.go index ae50de6a..b433e331 100644 --- a/transport/internet/http/config.go +++ b/transport/internet/http/config.go @@ -33,7 +33,7 @@ func (c *Config) getRandomHost() string { } func (c *Config) getNormalizedPath() string { - if len(c.Path) == 0 { + if c.Path == "" { return "/" } if c.Path[0] != '/' { diff --git a/transport/internet/tls/config.go b/transport/internet/tls/config.go index 4f8bed7e..1d41ed4a 100644 --- a/transport/internet/tls/config.go +++ b/transport/internet/tls/config.go @@ -236,7 +236,7 @@ type Option func(*tls.Config) // WithDestination sets the server name in TLS config. func WithDestination(dest net.Destination) Option { return func(config *tls.Config) { - if dest.Address.Family().IsDomain() && len(config.ServerName) == 0 { + if dest.Address.Family().IsDomain() && config.ServerName == "" { config.ServerName = dest.Address.Domain() } } diff --git a/transport/internet/tls/tls.go b/transport/internet/tls/tls.go index dd9a0bb8..b1523b7c 100644 --- a/transport/internet/tls/tls.go +++ b/transport/internet/tls/tls.go @@ -33,7 +33,7 @@ func (c *conn) HandshakeAddress() net.Address { return nil } state := c.Conn.ConnectionState() - if len(state.ServerName) == 0 { + if state.ServerName == "" { return nil } return net.ParseAddress(state.ServerName) diff --git a/transport/internet/websocket/config.go b/transport/internet/websocket/config.go index 34640e7e..982cf730 100644 --- a/transport/internet/websocket/config.go +++ b/transport/internet/websocket/config.go @@ -13,7 +13,7 @@ const protocolName = "websocket" func (c *Config) GetNormalizedPath() string { path := c.Path - if len(path) == 0 { + if path == "" { return "/" } if path[0] != '/' { From f59c0542c92701804b8fe1a96bb06ed168ed98a0 Mon Sep 17 00:00:00 2001 From: lucifer9 Date: Sat, 29 Jun 2019 10:21:34 +0800 Subject: [PATCH 16/19] Revert "fix some lint warnings." This reverts commit 1955d72e3e5ceb8a6ca72b705c05094240e81a74. --- transport/internet/http/hub.go | 54 ++++++++++++++++++---------------- 1 file changed, 28 insertions(+), 26 deletions(-) diff --git a/transport/internet/http/hub.go b/transport/internet/http/hub.go index 721e0c7a..f2d9fdbf 100644 --- a/transport/internet/http/hub.go +++ b/transport/internet/http/hub.go @@ -108,12 +108,12 @@ func Listen(ctx context.Context, address net.Address, port net.Port, streamSetti config := tls.ConfigFromStreamSettings(streamSettings) if config == nil { // return nil, newError("TLS must be enabled for http transport.").AtWarning() - h2s := &http2.Server{} + h2s:=&http2.Server{} server := &http.Server{ - Addr: serial.Concat(address, ":", port), + Addr: serial.Concat(address, ":", port), // TLSConfig: config.GetTLSConfig(tls.WithNextProto("h2")), - Handler: h2c.NewHandler(listener, h2s), + Handler: h2c.NewHandler(listener,h2s), ReadHeaderTimeout: time.Second * 4, } @@ -135,31 +135,33 @@ func Listen(ctx context.Context, address net.Address, port net.Port, streamSetti }() return listener, nil - } - server := &http.Server{ - Addr: serial.Concat(address, ":", port), - TLSConfig: config.GetTLSConfig(tls.WithNextProto("h2")), - Handler: listener, - ReadHeaderTimeout: time.Second * 4, - } - - listener.server = server - go func() { - tcpListener, err := internet.ListenSystem(ctx, &net.TCPAddr{ - IP: address.IP(), - Port: int(port), - }, streamSettings.SocketSettings) - if err != nil { - newError("failed to listen on", address, ":", port).Base(err).WriteToLog(session.ExportIDToError(ctx)) - return + } else { + server := &http.Server{ + Addr: serial.Concat(address, ":", port), + TLSConfig: config.GetTLSConfig(tls.WithNextProto("h2")), + Handler: listener, + ReadHeaderTimeout: time.Second * 4, } - err = server.ServeTLS(tcpListener, "", "") - if err != nil { - newError("stoping serving TLS").Base(err).WriteToLog(session.ExportIDToError(ctx)) - } - }() - return listener, nil + listener.server = server + go func() { + tcpListener, err := internet.ListenSystem(ctx, &net.TCPAddr{ + IP: address.IP(), + Port: int(port), + }, streamSettings.SocketSettings) + if err != nil { + newError("failed to listen on", address, ":", port).Base(err).WriteToLog(session.ExportIDToError(ctx)) + return + } + + err = server.ServeTLS(tcpListener, "", "") + if err != nil { + newError("stoping serving TLS").Base(err).WriteToLog(session.ExportIDToError(ctx)) + } + }() + + return listener, nil + } } func init() { From a28fabacefafd1ab49cea46546f3f11080a27cd0 Mon Sep 17 00:00:00 2001 From: lucifer9 Date: Sat, 29 Jun 2019 10:21:42 +0800 Subject: [PATCH 17/19] Revert "add server-side http2 over tcp (h2c) support" This reverts commit e744537b8074b6e1a40bd5e1b007b4093d7e0650. --- transport/internet/http/hub.go | 84 +++++++++++----------------------- 1 file changed, 27 insertions(+), 57 deletions(-) diff --git a/transport/internet/http/hub.go b/transport/internet/http/hub.go index f2d9fdbf..1ec53c5d 100644 --- a/transport/internet/http/hub.go +++ b/transport/internet/http/hub.go @@ -16,9 +16,6 @@ import ( "v2ray.com/core/common/signal/done" "v2ray.com/core/transport/internet" "v2ray.com/core/transport/internet/tls" - - "golang.org/x/net/http2" - "golang.org/x/net/http2/h2c" ) type Listener struct { @@ -107,61 +104,34 @@ func Listen(ctx context.Context, address net.Address, port net.Port, streamSetti config := tls.ConfigFromStreamSettings(streamSettings) if config == nil { - // return nil, newError("TLS must be enabled for http transport.").AtWarning() - h2s:=&http2.Server{} - - server := &http.Server{ - Addr: serial.Concat(address, ":", port), - // TLSConfig: config.GetTLSConfig(tls.WithNextProto("h2")), - Handler: h2c.NewHandler(listener,h2s), - ReadHeaderTimeout: time.Second * 4, - } - - listener.server = server - go func() { - tcpListener, err := internet.ListenSystem(ctx, &net.TCPAddr{ - IP: address.IP(), - Port: int(port), - }, streamSettings.SocketSettings) - if err != nil { - newError("failed to listen on", address, ":", port).Base(err).WriteToLog(session.ExportIDToError(ctx)) - return - } - - err = server.Serve(tcpListener) - if err != nil { - newError("stoping serving H2C").Base(err).WriteToLog(session.ExportIDToError(ctx)) - } - }() - - return listener, nil - } else { - server := &http.Server{ - Addr: serial.Concat(address, ":", port), - TLSConfig: config.GetTLSConfig(tls.WithNextProto("h2")), - Handler: listener, - ReadHeaderTimeout: time.Second * 4, - } - - listener.server = server - go func() { - tcpListener, err := internet.ListenSystem(ctx, &net.TCPAddr{ - IP: address.IP(), - Port: int(port), - }, streamSettings.SocketSettings) - if err != nil { - newError("failed to listen on", address, ":", port).Base(err).WriteToLog(session.ExportIDToError(ctx)) - return - } - - err = server.ServeTLS(tcpListener, "", "") - if err != nil { - newError("stoping serving TLS").Base(err).WriteToLog(session.ExportIDToError(ctx)) - } - }() - - return listener, nil + return nil, newError("TLS must be enabled for http transport.").AtWarning() } + + server := &http.Server{ + Addr: serial.Concat(address, ":", port), + TLSConfig: config.GetTLSConfig(tls.WithNextProto("h2")), + Handler: listener, + ReadHeaderTimeout: time.Second * 4, + } + + listener.server = server + go func() { + tcpListener, err := internet.ListenSystem(ctx, &net.TCPAddr{ + IP: address.IP(), + Port: int(port), + }, streamSettings.SocketSettings) + if err != nil { + newError("failed to listen on", address, ":", port).Base(err).WriteToLog(session.ExportIDToError(ctx)) + return + } + + err = server.ServeTLS(tcpListener, "", "") + if err != nil { + newError("stoping serving TLS").Base(err).WriteToLog(session.ExportIDToError(ctx)) + } + }() + + return listener, nil } func init() { From 4cc5558a4ebccea61af86840b821108f3ce05ae9 Mon Sep 17 00:00:00 2001 From: lucifer9 Date: Sat, 29 Jun 2019 10:22:22 +0800 Subject: [PATCH 18/19] delete some unnecessary comments --- infra/bazel/zip.bzl | 3 --- 1 file changed, 3 deletions(-) diff --git a/infra/bazel/zip.bzl b/infra/bazel/zip.bzl index fc3ae2f5..40f89b6d 100644 --- a/infra/bazel/zip.bzl +++ b/infra/bazel/zip.bzl @@ -48,9 +48,6 @@ def _zip_file(ctx): d.startswith("/") or d.endswith("/")): fail("mappings should not begin or end with slash") srcs = depset(transitive = [depset(ctx.files.srcs),depset(ctx.files.data),depset(collect_runfiles(ctx.attr.data))]) - # srcs += ctx.files.srcs - # srcs += ctx.files.data - # srcs += collect_runfiles(ctx.attr.data) mapped = _map_sources(ctx, srcs, ctx.attr.mappings) cmd = [ "#!/bin/sh", From e6bf431f93b9807c1fc2db24480fe61cce0299ad Mon Sep 17 00:00:00 2001 From: lucifer9 Date: Fri, 5 Jul 2019 11:18:00 +0800 Subject: [PATCH 19/19] add server side h2c support --- transport/internet/http/hub.go | 38 ++++++++++++++++++++++++---------- 1 file changed, 27 insertions(+), 11 deletions(-) diff --git a/transport/internet/http/hub.go b/transport/internet/http/hub.go index 1ec53c5d..32fb3090 100644 --- a/transport/internet/http/hub.go +++ b/transport/internet/http/hub.go @@ -16,6 +16,9 @@ import ( "v2ray.com/core/common/signal/done" "v2ray.com/core/transport/internet" "v2ray.com/core/transport/internet/tls" + + "golang.org/x/net/http2" + "golang.org/x/net/http2/h2c" ) type Listener struct { @@ -102,16 +105,23 @@ func Listen(ctx context.Context, address net.Address, port net.Port, streamSetti config: *httpSettings, } + var server *http.Server config := tls.ConfigFromStreamSettings(streamSettings) if config == nil { - return nil, newError("TLS must be enabled for http transport.").AtWarning() - } + h2s := &http2.Server{} - server := &http.Server{ - Addr: serial.Concat(address, ":", port), - TLSConfig: config.GetTLSConfig(tls.WithNextProto("h2")), - Handler: listener, - ReadHeaderTimeout: time.Second * 4, + server = &http.Server{ + Addr: serial.Concat(address, ":", port), + Handler: h2c.NewHandler(listener, h2s), + ReadHeaderTimeout: time.Second * 4, + } + } else { + server = &http.Server{ + Addr: serial.Concat(address, ":", port), + TLSConfig: config.GetTLSConfig(tls.WithNextProto("h2")), + Handler: listener, + ReadHeaderTimeout: time.Second * 4, + } } listener.server = server @@ -124,10 +134,16 @@ func Listen(ctx context.Context, address net.Address, port net.Port, streamSetti newError("failed to listen on", address, ":", port).Base(err).WriteToLog(session.ExportIDToError(ctx)) return } - - err = server.ServeTLS(tcpListener, "", "") - if err != nil { - newError("stoping serving TLS").Base(err).WriteToLog(session.ExportIDToError(ctx)) + if config == nil { + err = server.Serve(tcpListener) + if err != nil { + newError("stoping serving H2C").Base(err).WriteToLog(session.ExportIDToError(ctx)) + } + } else { + err = server.ServeTLS(tcpListener, "", "") + if err != nil { + newError("stoping serving TLS").Base(err).WriteToLog(session.ExportIDToError(ctx)) + } } }()