2022-09-10 10:27:00 +08:00
package tls
import (
"context"
2022-09-30 11:27:18 +08:00
"net"
2023-12-20 20:00:00 +08:00
"os"
2022-09-10 10:27:00 +08:00
2023-12-20 20:00:00 +08:00
"github.com/sagernet/sing-box/common/badtls"
2022-09-30 11:27:18 +08:00
C "github.com/sagernet/sing-box/constant"
2022-09-10 10:27:00 +08:00
"github.com/sagernet/sing-box/log"
"github.com/sagernet/sing-box/option"
2023-02-28 11:30:46 +08:00
aTLS "github.com/sagernet/sing/common/tls"
2022-09-10 10:27:00 +08:00
)
2025-09-08 19:35:17 +08:00
type ServerOptions struct {
Context context . Context
Logger log . ContextLogger
Options option . InboundTLSOptions
KTLSCompatible bool
}
2025-09-07 21:03:32 +08:00
func NewServer ( ctx context . Context , logger log . ContextLogger , options option . InboundTLSOptions ) ( ServerConfig , error ) {
2025-09-08 19:35:17 +08:00
return NewServerWithOptions ( ServerOptions {
Context : ctx ,
Logger : logger ,
Options : options ,
})
}
func NewServerWithOptions ( options ServerOptions ) ( ServerConfig , error ) {
if ! options . Options . Enabled {
2022-11-13 11:24:37 +08:00
return nil , nil
}
2025-09-08 19:35:17 +08:00
if ! options . KTLSCompatible {
if options . Options . KernelTx {
options . Logger . Warn ( "enabling kTLS TX in current scenarios will definitely reduce performance, please checkout https://sing-box.sagernet.org/configuration/shared/tls/#kernel_tx" )
}
}
if options . Options . KernelRx {
options . Logger . Warn ( "enabling kTLS RX will definitely reduce performance, please checkout https://sing-box.sagernet.org/configuration/shared/tls/#kernel_rx" )
}
if options . Options . Reality != nil && options . Options . Reality . Enabled {
return NewRealityServer ( options . Context , options . Logger , options . Options )
2023-02-25 16:24:08 +08:00
}
2025-09-08 19:35:17 +08:00
return NewSTDServer ( options . Context , options . Logger , options . Options )
2022-09-10 10:27:00 +08:00
}
2022-09-30 11:27:18 +08:00
func ServerHandshake ( ctx context . Context , conn net . Conn , config ServerConfig ) ( Conn , error ) {
ctx , cancel := context . WithTimeout ( ctx , C . TCPTimeout )
defer cancel ()
2023-12-20 20:00:00 +08:00
tlsConn , err := aTLS . ServerHandshake ( ctx , conn , config )
if err != nil {
return nil , err
}
readWaitConn , err := badtls . NewReadWaitConn ( tlsConn )
if err == nil {
return readWaitConn , nil
} else if err != os . ErrInvalid {
return nil , err
}
return tlsConn , nil
2022-09-30 11:27:18 +08:00
}