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
|
|
|
)
|
|
|
|
|
2023-08-29 13:43:42 +08:00
|
|
|
func NewServer(ctx context.Context, logger log.Logger, options option.InboundTLSOptions) (ServerConfig, error) {
|
2022-11-13 11:24:37 +08:00
|
|
|
if !options.Enabled {
|
|
|
|
return nil, nil
|
|
|
|
}
|
2023-08-29 13:43:42 +08:00
|
|
|
if options.ECH != nil && options.ECH.Enabled {
|
|
|
|
return NewECHServer(ctx, logger, options)
|
|
|
|
} else if options.Reality != nil && options.Reality.Enabled {
|
|
|
|
return NewRealityServer(ctx, logger, options)
|
2023-02-25 16:24:08 +08:00
|
|
|
} else {
|
2023-08-29 13:43:42 +08:00
|
|
|
return NewSTDServer(ctx, logger, options)
|
2023-02-25 16:24:08 +08:00
|
|
|
}
|
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
|
|
|
}
|