server.go 3.4 KB

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