sing-box/inbound/default_tcp.go

77 lines
2.4 KiB
Go
Raw Normal View History

2022-08-29 11:43:13 +00:00
package inbound
import (
"context"
"net"
"github.com/sagernet/sing-box/adapter"
"github.com/sagernet/sing-box/common/proxyproto"
"github.com/sagernet/sing-box/log"
E "github.com/sagernet/sing/common/exceptions"
M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network"
2023-02-07 10:06:25 +00:00
"github.com/sagernet/tfo-go"
2022-08-29 11:43:13 +00:00
)
func (a *myInboundAdapter) ListenTCP() (net.Listener, error) {
var err error
2023-03-19 12:46:22 +00:00
bindAddr := M.SocksaddrFrom(a.listenOptions.Listen.Build(), a.listenOptions.ListenPort)
2022-08-29 11:43:13 +00:00
var tcpListener net.Listener
if !a.listenOptions.TCPFastOpen {
tcpListener, err = net.ListenTCP(M.NetworkFromNetAddr(N.NetworkTCP, bindAddr.Addr), bindAddr.TCPAddr())
} else {
tcpListener, err = tfo.ListenTCP(M.NetworkFromNetAddr(N.NetworkTCP, bindAddr.Addr), bindAddr.TCPAddr())
}
if err == nil {
a.logger.Info("tcp server started at ", tcpListener.Addr())
}
if a.listenOptions.ProxyProtocol {
a.logger.Debug("proxy protocol enabled")
2022-09-07 15:01:57 +00:00
tcpListener = &proxyproto.Listener{Listener: tcpListener, AcceptNoHeader: a.listenOptions.ProxyProtocolAcceptNoHeader}
2022-08-29 11:43:13 +00:00
}
a.tcpListener = tcpListener
return tcpListener, err
}
func (a *myInboundAdapter) loopTCPIn() {
tcpListener := a.tcpListener
for {
conn, err := tcpListener.Accept()
if err != nil {
2023-03-01 16:18:35 +00:00
//goland:noinspection GoDeprecation
//nolint:staticcheck
if netError, isNetError := err.(net.Error); isNetError && netError.Temporary() {
a.logger.Error(err)
continue
}
if a.inShutdown.Load() && E.IsClosed(err) {
2022-09-06 15:16:25 +00:00
return
}
2023-03-01 16:18:35 +00:00
a.tcpListener.Close()
a.logger.Error("serve error: ", err)
2022-09-06 15:16:25 +00:00
continue
2022-08-29 11:43:13 +00:00
}
go a.injectTCP(conn, adapter.InboundContext{})
}
}
func (a *myInboundAdapter) injectTCP(conn net.Conn, metadata adapter.InboundContext) {
ctx := log.ContextWithNewID(a.ctx)
metadata = a.createMetadata(conn, metadata)
a.logger.InfoContext(ctx, "inbound connection from ", metadata.Source)
hErr := a.connHandler.NewConnection(ctx, conn, metadata)
if hErr != nil {
conn.Close()
a.NewError(ctx, E.Cause(hErr, "process connection from ", metadata.Source))
}
}
func (a *myInboundAdapter) routeTCP(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) {
a.logger.InfoContext(ctx, "inbound connection from ", metadata.Source)
hErr := a.newConnection(ctx, conn, metadata)
if hErr != nil {
conn.Close()
a.NewError(ctx, E.Cause(hErr, "process connection from ", metadata.Source))
}
}