server.go 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. package server
  2. import (
  3. "context"
  4. "fmt"
  5. "log"
  6. "net"
  7. "net/netip"
  8. "time"
  9. "github.com/Snawoot/dtlspipe/util"
  10. "github.com/pion/dtls/v2"
  11. "github.com/pion/dtls/v2/pkg/protocol"
  12. "github.com/pion/dtls/v2/pkg/protocol/recordlayer"
  13. "github.com/pion/transport/v2/udp"
  14. )
  15. const (
  16. Backlog = 1024
  17. )
  18. type Server struct {
  19. listener net.Listener
  20. dtlsConfig *dtls.Config
  21. rAddr string
  22. psk func([]byte) ([]byte, error)
  23. timeout time.Duration
  24. idleTimeout time.Duration
  25. baseCtx context.Context
  26. cancelCtx func()
  27. }
  28. func New(cfg *Config) (*Server, error) {
  29. cfg = cfg.populateDefaults()
  30. baseCtx, cancelCtx := context.WithCancel(cfg.BaseContext)
  31. srv := &Server{
  32. rAddr: cfg.RemoteAddress,
  33. timeout: cfg.Timeout,
  34. psk: cfg.PSKCallback,
  35. idleTimeout: cfg.IdleTimeout,
  36. baseCtx: baseCtx,
  37. cancelCtx: cancelCtx,
  38. }
  39. lAddrPort, err := netip.ParseAddrPort(cfg.BindAddress)
  40. if err != nil {
  41. cancelCtx()
  42. return nil, fmt.Errorf("can't parse bind address: %w", err)
  43. }
  44. srv.dtlsConfig = &dtls.Config{
  45. ExtendedMasterSecret: dtls.RequireExtendedMasterSecret,
  46. ConnectContextMaker: srv.contextMaker,
  47. PSK: srv.psk,
  48. MTU: cfg.MTU,
  49. InsecureSkipVerifyHello: cfg.SkipHelloVerify,
  50. CipherSuites: cfg.CipherSuites,
  51. }
  52. lc := udp.ListenConfig{
  53. AcceptFilter: func(packet []byte) bool {
  54. pkts, err := recordlayer.UnpackDatagram(packet)
  55. if err != nil || len(pkts) < 1 {
  56. return false
  57. }
  58. h := &recordlayer.Header{}
  59. if err := h.Unmarshal(pkts[0]); err != nil {
  60. return false
  61. }
  62. return h.ContentType == protocol.ContentTypeHandshake
  63. },
  64. Backlog: Backlog,
  65. }
  66. listener, err := lc.Listen("udp", net.UDPAddrFromAddrPort(lAddrPort))
  67. if err != nil {
  68. cancelCtx()
  69. return nil, fmt.Errorf("server listen failed: %w", err)
  70. }
  71. srv.listener = listener
  72. go srv.listen()
  73. return srv, nil
  74. }
  75. func (srv *Server) listen() {
  76. defer srv.Close()
  77. for srv.baseCtx.Err() == nil {
  78. conn, err := srv.listener.Accept()
  79. if err != nil {
  80. log.Printf("conn accept failed: %v", err)
  81. continue
  82. }
  83. go func(conn net.Conn) {
  84. defer conn.Close()
  85. conn, err := dtls.Server(conn, srv.dtlsConfig)
  86. if err != nil {
  87. log.Printf("DTLS accept error: %v", err)
  88. return
  89. }
  90. defer conn.Close()
  91. srv.serve(conn)
  92. }(conn)
  93. }
  94. }
  95. func (srv *Server) serve(conn net.Conn) {
  96. log.Printf("[+] conn %s <=> %s", conn.LocalAddr(), conn.RemoteAddr())
  97. defer log.Printf("[-] conn %s <=> %s", conn.LocalAddr(), conn.RemoteAddr())
  98. defer conn.Close()
  99. dialCtx, cancel := context.WithTimeout(srv.baseCtx, srv.timeout)
  100. defer cancel()
  101. remoteConn, err := (&net.Dialer{}).DialContext(dialCtx, "udp", srv.rAddr)
  102. if err != nil {
  103. log.Printf("remote dial failed: %v", err)
  104. return
  105. }
  106. defer remoteConn.Close()
  107. util.PairConn(conn, remoteConn, srv.idleTimeout)
  108. }
  109. func (srv *Server) contextMaker() (context.Context, func()) {
  110. return context.WithTimeout(srv.baseCtx, srv.timeout)
  111. }
  112. func (srv *Server) Close() error {
  113. srv.cancelCtx()
  114. return srv.listener.Close()
  115. }