sing-box/protocol/hysteria2/inbound.go

216 lines
7.0 KiB
Go
Raw Normal View History

2024-11-02 00:39:02 +08:00
package hysteria2
2023-08-31 20:07:32 +08:00
import (
"context"
"net"
"net/http"
"net/http/httputil"
"net/url"
"time"
2023-08-31 20:07:32 +08:00
"github.com/sagernet/sing-box/adapter"
2024-11-02 00:39:02 +08:00
"github.com/sagernet/sing-box/adapter/inbound"
"github.com/sagernet/sing-box/common/listener"
2023-08-31 20:07:32 +08:00
"github.com/sagernet/sing-box/common/tls"
C "github.com/sagernet/sing-box/constant"
"github.com/sagernet/sing-box/log"
"github.com/sagernet/sing-box/option"
"github.com/sagernet/sing-quic/hysteria"
"github.com/sagernet/sing-quic/hysteria2"
2023-08-31 20:07:32 +08:00
"github.com/sagernet/sing/common"
"github.com/sagernet/sing/common/auth"
E "github.com/sagernet/sing/common/exceptions"
M "github.com/sagernet/sing/common/metadata"
2023-08-31 20:07:32 +08:00
N "github.com/sagernet/sing/common/network"
)
2024-11-02 00:39:02 +08:00
func RegisterInbound(registry *inbound.Registry) {
inbound.Register[option.Hysteria2InboundOptions](registry, C.TypeHysteria2, NewInbound)
}
2023-08-31 20:07:32 +08:00
2024-11-02 00:39:02 +08:00
type Inbound struct {
inbound.Adapter
router adapter.Router
logger log.ContextLogger
listener *listener.Listener
tlsConfig tls.ServerConfig
service *hysteria2.Service[int]
userNameList []string
2023-08-31 20:07:32 +08:00
}
2024-11-02 00:39:02 +08:00
func NewInbound(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.Hysteria2InboundOptions) (adapter.Inbound, error) {
options.UDPFragmentDefault = true
2023-08-31 20:07:32 +08:00
if options.TLS == nil || !options.TLS.Enabled {
return nil, C.ErrTLSRequired
}
tlsConfig, err := tls.NewServer(ctx, logger, common.PtrValueOrDefault(options.TLS))
if err != nil {
return nil, err
}
var salamanderPassword string
if options.Obfs != nil {
if options.Obfs.Password == "" {
return nil, E.New("missing obfs password")
}
switch options.Obfs.Type {
case hysteria2.ObfsTypeSalamander:
salamanderPassword = options.Obfs.Password
default:
return nil, E.New("unknown obfs type: ", options.Obfs.Type)
}
}
var masqueradeHandler http.Handler
2024-11-28 22:39:19 +08:00
if options.Masquerade != nil && options.Masquerade.Type != "" {
switch options.Masquerade.Type {
case C.Hysterai2MasqueradeTypeFile:
masqueradeHandler = http.FileServer(http.Dir(options.Masquerade.FileOptions.Directory))
case C.Hysterai2MasqueradeTypeProxy:
masqueradeURL, err := url.Parse(options.Masquerade.ProxyOptions.URL)
if err != nil {
return nil, E.Cause(err, "parse masquerade URL")
}
2023-08-31 20:07:32 +08:00
masqueradeHandler = &httputil.ReverseProxy{
Rewrite: func(r *httputil.ProxyRequest) {
r.SetURL(masqueradeURL)
2024-11-28 22:39:19 +08:00
if !options.Masquerade.ProxyOptions.RewriteHost {
r.Out.Host = r.In.Host
}
2023-08-31 20:07:32 +08:00
},
ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) {
w.WriteHeader(http.StatusBadGateway)
},
}
2024-11-28 22:39:19 +08:00
case C.Hysterai2MasqueradeTypeString:
masqueradeHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if options.Masquerade.StringOptions.StatusCode != 0 {
w.WriteHeader(options.Masquerade.StringOptions.StatusCode)
}
for key, values := range options.Masquerade.StringOptions.Headers {
for _, value := range values {
w.Header().Add(key, value)
}
}
w.Write([]byte(options.Masquerade.StringOptions.Content))
})
2023-08-31 20:07:32 +08:00
default:
2024-11-28 22:39:19 +08:00
return nil, E.New("unknown masquerade type: ", options.Masquerade.Type)
2023-08-31 20:07:32 +08:00
}
}
2024-11-02 00:39:02 +08:00
inbound := &Inbound{
Adapter: inbound.NewAdapter(C.TypeHysteria2, tag),
router: router,
logger: logger,
listener: listener.New(listener.Options{
Context: ctx,
Logger: logger,
Listen: options.ListenOptions,
}),
2023-08-31 20:07:32 +08:00
tlsConfig: tlsConfig,
}
var udpTimeout time.Duration
if options.UDPTimeout != 0 {
udpTimeout = time.Duration(options.UDPTimeout)
} else {
udpTimeout = C.UDPTimeout
}
service, err := hysteria2.NewService[int](hysteria2.ServiceOptions{
Context: ctx,
Logger: logger,
2023-10-21 12:00:00 +08:00
BrutalDebug: options.BrutalDebug,
2023-09-17 00:25:53 +08:00
SendBPS: uint64(options.UpMbps * hysteria.MbpsToBps),
ReceiveBPS: uint64(options.DownMbps * hysteria.MbpsToBps),
SalamanderPassword: salamanderPassword,
TLSConfig: tlsConfig,
2023-08-31 20:07:32 +08:00
IgnoreClientBandwidth: options.IgnoreClientBandwidth,
UDPTimeout: udpTimeout,
Handler: inbound,
2023-08-31 20:07:32 +08:00
MasqueradeHandler: masqueradeHandler,
})
if err != nil {
return nil, err
}
userList := make([]int, 0, len(options.Users))
userNameList := make([]string, 0, len(options.Users))
userPasswordList := make([]string, 0, len(options.Users))
for index, user := range options.Users {
userList = append(userList, index)
userNameList = append(userNameList, user.Name)
userPasswordList = append(userPasswordList, user.Password)
}
service.UpdateUsers(userList, userPasswordList)
inbound.service = service
inbound.userNameList = userNameList
2023-08-31 20:07:32 +08:00
return inbound, nil
}
func (h *Inbound) NewConnectionEx(ctx context.Context, conn net.Conn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) {
2023-08-31 20:07:32 +08:00
ctx = log.ContextWithNewID(ctx)
var metadata adapter.InboundContext
2024-11-02 00:39:02 +08:00
metadata.Inbound = h.Tag()
metadata.InboundType = h.Type()
2024-11-23 22:34:02 +08:00
//nolint:staticcheck
2024-11-02 00:39:02 +08:00
metadata.InboundDetour = h.listener.ListenOptions().Detour
2024-11-23 22:34:02 +08:00
//nolint:staticcheck
2024-11-02 00:39:02 +08:00
metadata.InboundOptions = h.listener.ListenOptions().InboundOptions
metadata.OriginDestination = h.listener.UDPAddr()
metadata.Source = source
metadata.Destination = destination
h.logger.InfoContext(ctx, "inbound connection from ", metadata.Source)
userID, _ := auth.UserFromContext[int](ctx)
if userName := h.userNameList[userID]; userName != "" {
metadata.User = userName
2023-09-24 12:00:00 +08:00
h.logger.InfoContext(ctx, "[", userName, "] inbound connection to ", metadata.Destination)
} else {
h.logger.InfoContext(ctx, "inbound connection to ", metadata.Destination)
}
h.router.RouteConnectionEx(ctx, conn, metadata, onClose)
2023-08-31 20:07:32 +08:00
}
func (h *Inbound) NewPacketConnectionEx(ctx context.Context, conn N.PacketConn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) {
2023-08-31 20:07:32 +08:00
ctx = log.ContextWithNewID(ctx)
var metadata adapter.InboundContext
2024-11-02 00:39:02 +08:00
metadata.Inbound = h.Tag()
metadata.InboundType = h.Type()
2024-11-23 22:34:02 +08:00
//nolint:staticcheck
2024-11-02 00:39:02 +08:00
metadata.InboundDetour = h.listener.ListenOptions().Detour
2024-11-23 22:34:02 +08:00
//nolint:staticcheck
2024-11-02 00:39:02 +08:00
metadata.InboundOptions = h.listener.ListenOptions().InboundOptions
metadata.OriginDestination = h.listener.UDPAddr()
metadata.Source = source
metadata.Destination = destination
h.logger.InfoContext(ctx, "inbound packet connection from ", metadata.Source)
userID, _ := auth.UserFromContext[int](ctx)
if userName := h.userNameList[userID]; userName != "" {
metadata.User = userName
2023-09-24 12:00:00 +08:00
h.logger.InfoContext(ctx, "[", userName, "] inbound packet connection to ", metadata.Destination)
} else {
h.logger.InfoContext(ctx, "inbound packet connection to ", metadata.Destination)
}
h.router.RoutePacketConnectionEx(ctx, conn, metadata, onClose)
2023-08-31 20:07:32 +08:00
}
2024-11-21 18:10:41 +08:00
func (h *Inbound) Start(stage adapter.StartStage) error {
if stage != adapter.StartStateStart {
return nil
}
2023-08-31 20:07:32 +08:00
if h.tlsConfig != nil {
err := h.tlsConfig.Start()
if err != nil {
return err
}
}
2024-11-02 00:39:02 +08:00
packetConn, err := h.listener.ListenUDP()
2023-08-31 20:07:32 +08:00
if err != nil {
return err
}
return h.service.Start(packetConn)
2023-08-31 20:07:32 +08:00
}
2024-11-02 00:39:02 +08:00
func (h *Inbound) Close() error {
2023-08-31 20:07:32 +08:00
return common.Close(
h.listener,
2023-08-31 20:07:32 +08:00
h.tlsConfig,
common.PtrOrNil(h.service),
2023-08-31 20:07:32 +08:00
)
}