server.go 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  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. EllipticCurves: cfg.EllipticCurves,
  52. }
  53. lc := udp.ListenConfig{
  54. AcceptFilter: func(packet []byte) bool {
  55. pkts, err := recordlayer.UnpackDatagram(packet)
  56. if err != nil || len(pkts) < 1 {
  57. return false
  58. }
  59. h := &recordlayer.Header{}
  60. if err := h.Unmarshal(pkts[0]); err != nil {
  61. return false
  62. }
  63. return h.ContentType == protocol.ContentTypeHandshake
  64. },
  65. Backlog: Backlog,
  66. }
  67. listener, err := lc.Listen("udp", net.UDPAddrFromAddrPort(lAddrPort))
  68. if err != nil {
  69. cancelCtx()
  70. return nil, fmt.Errorf("server listen failed: %w", err)
  71. }
  72. srv.listener = listener
  73. go srv.listen()
  74. return srv, nil
  75. }
  76. func (srv *Server) listen() {
  77. defer srv.Close()
  78. for srv.baseCtx.Err() == nil {
  79. conn, err := srv.listener.Accept()
  80. if err != nil {
  81. log.Printf("conn accept failed: %v", err)
  82. continue
  83. }
  84. go func(conn net.Conn) {
  85. defer conn.Close()
  86. conn, err := dtls.Server(conn, srv.dtlsConfig)
  87. if err != nil {
  88. log.Printf("DTLS accept error: %v", err)
  89. return
  90. }
  91. defer conn.Close()
  92. srv.serve(conn)
  93. }(conn)
  94. }
  95. }
  96. func (srv *Server) serve(conn net.Conn) {
  97. log.Printf("[+] conn %s <=> %s", conn.LocalAddr(), conn.RemoteAddr())
  98. defer log.Printf("[-] conn %s <=> %s", conn.LocalAddr(), conn.RemoteAddr())
  99. defer conn.Close()
  100. dialCtx, cancel := context.WithTimeout(srv.baseCtx, srv.timeout)
  101. defer cancel()
  102. remoteConn, err := (&net.Dialer{}).DialContext(dialCtx, "udp", srv.rAddr)
  103. if err != nil {
  104. log.Printf("remote dial failed: %v", err)
  105. return
  106. }
  107. defer remoteConn.Close()
  108. util.PairConn(conn, remoteConn, srv.idleTimeout)
  109. }
  110. func (srv *Server) contextMaker() (context.Context, func()) {
  111. return context.WithTimeout(srv.baseCtx, srv.timeout)
  112. }
  113. func (srv *Server) Close() error {
  114. srv.cancelCtx()
  115. return srv.listener.Close()
  116. }