sing-box/transport/v2rayquic/server.go

97 lines
2.2 KiB
Go
Raw Normal View History

2022-08-22 21:20:05 +08:00
package v2rayquic
import (
"context"
"net"
"os"
"github.com/sagernet/quic-go"
"github.com/sagernet/sing-box/adapter"
2022-09-09 18:45:10 +08:00
"github.com/sagernet/sing-box/common/tls"
2022-08-22 21:20:05 +08:00
C "github.com/sagernet/sing-box/constant"
"github.com/sagernet/sing-box/option"
"github.com/sagernet/sing-box/transport/hysteria"
"github.com/sagernet/sing/common"
M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network"
)
var _ adapter.V2RayServerTransport = (*Server)(nil)
type Server struct {
ctx context.Context
2022-09-09 18:45:10 +08:00
tlsConfig *tls.STDConfig
2022-08-22 21:20:05 +08:00
quicConfig *quic.Config
handler adapter.V2RayServerTransportHandler
2022-08-22 21:20:05 +08:00
udpListener net.PacketConn
2023-06-15 10:10:42 +08:00
quicListener *quic.Listener
2022-08-22 21:20:05 +08:00
}
func NewServer(ctx context.Context, options option.V2RayQUICOptions, tlsConfig tls.ServerConfig, handler adapter.V2RayServerTransportHandler) (adapter.V2RayServerTransport, error) {
2022-08-22 21:20:05 +08:00
quicConfig := &quic.Config{
DisablePathMTUDiscovery: !C.IsLinux && !C.IsWindows,
}
2022-09-09 18:45:10 +08:00
stdConfig, err := tlsConfig.Config()
if err != nil {
return nil, err
}
if len(stdConfig.NextProtos) == 0 {
stdConfig.NextProtos = []string{"h2", "http/1.1"}
2022-08-22 21:20:05 +08:00
}
server := &Server{
ctx: ctx,
tlsConfig: stdConfig,
quicConfig: quicConfig,
handler: handler,
2022-08-22 21:20:05 +08:00
}
2022-09-09 18:45:10 +08:00
return server, nil
2022-08-22 21:20:05 +08:00
}
func (s *Server) Network() []string {
return []string{N.NetworkUDP}
}
func (s *Server) Serve(listener net.Listener) error {
return os.ErrInvalid
}
func (s *Server) ServePacket(listener net.PacketConn) error {
quicListener, err := quic.Listen(listener, s.tlsConfig, s.quicConfig)
if err != nil {
return err
}
s.udpListener = listener
s.quicListener = quicListener
go s.acceptLoop()
return nil
}
func (s *Server) acceptLoop() {
for {
conn, err := s.quicListener.Accept(s.ctx)
if err != nil {
return
}
go func() {
hErr := s.streamAcceptLoop(conn)
if hErr != nil {
2023-07-11 14:03:55 +08:00
s.handler.NewError(conn.Context(), hErr)
2022-08-22 21:20:05 +08:00
}
}()
}
}
func (s *Server) streamAcceptLoop(conn quic.Connection) error {
for {
stream, err := conn.AcceptStream(s.ctx)
if err != nil {
return err
}
go s.handler.NewConnection(conn.Context(), &hysteria.StreamWrapper{Conn: conn, Stream: stream}, M.Metadata{})
}
}
func (s *Server) Close() error {
2023-07-07 12:43:22 +08:00
return common.Close(s.udpListener, common.PtrOrNil(s.quicListener))
2022-08-22 21:20:05 +08:00
}