1
0

server.go 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  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. }
  31. func New(cfg *Config) (*Server, error) {
  32. cfg = cfg.populateDefaults()
  33. baseCtx, cancelCtx := context.WithCancel(cfg.BaseContext)
  34. srv := &Server{
  35. rAddr: cfg.RemoteAddress,
  36. timeout: cfg.Timeout,
  37. psk: cfg.PSKCallback,
  38. idleTimeout: cfg.IdleTimeout,
  39. baseCtx: baseCtx,
  40. cancelCtx: cancelCtx,
  41. staleMode: cfg.StaleMode,
  42. }
  43. lAddrPort, err := netip.ParseAddrPort(cfg.BindAddress)
  44. if err != nil {
  45. cancelCtx()
  46. return nil, fmt.Errorf("can't parse bind address: %w", err)
  47. }
  48. srv.dtlsConfig = &dtls.Config{
  49. ExtendedMasterSecret: dtls.RequireExtendedMasterSecret,
  50. ConnectContextMaker: srv.contextMaker,
  51. PSK: srv.psk,
  52. MTU: cfg.MTU,
  53. InsecureSkipVerifyHello: cfg.SkipHelloVerify,
  54. CipherSuites: cfg.CipherSuites,
  55. EllipticCurves: cfg.EllipticCurves,
  56. }
  57. lc := udp.ListenConfig{
  58. AcceptFilter: func(packet []byte) bool {
  59. pkts, err := recordlayer.UnpackDatagram(packet)
  60. if err != nil || len(pkts) < 1 {
  61. return false
  62. }
  63. h := &recordlayer.Header{}
  64. if err := h.Unmarshal(pkts[0]); err != nil {
  65. return false
  66. }
  67. return h.ContentType == protocol.ContentTypeHandshake
  68. },
  69. Backlog: Backlog,
  70. }
  71. listener, err := lc.Listen("udp", net.UDPAddrFromAddrPort(lAddrPort))
  72. if err != nil {
  73. cancelCtx()
  74. return nil, fmt.Errorf("server listen failed: %w", err)
  75. }
  76. srv.listener = listener
  77. go srv.listen()
  78. return srv, nil
  79. }
  80. func (srv *Server) listen() {
  81. defer srv.Close()
  82. for srv.baseCtx.Err() == nil {
  83. conn, err := srv.listener.Accept()
  84. if err != nil {
  85. log.Printf("conn accept failed: %v", err)
  86. continue
  87. }
  88. srv.workerWG.Add(1)
  89. go func(conn net.Conn) {
  90. defer srv.workerWG.Done()
  91. defer conn.Close()
  92. conn, err := dtls.Server(conn, srv.dtlsConfig)
  93. if err != nil {
  94. log.Printf("DTLS accept error: %v", err)
  95. return
  96. }
  97. defer conn.Close()
  98. srv.serve(conn)
  99. }(conn)
  100. }
  101. }
  102. func (srv *Server) serve(conn net.Conn) {
  103. log.Printf("[+] conn %s <=> %s", conn.LocalAddr(), conn.RemoteAddr())
  104. defer log.Printf("[-] conn %s <=> %s", conn.LocalAddr(), conn.RemoteAddr())
  105. defer conn.Close()
  106. dialCtx, cancel := context.WithTimeout(srv.baseCtx, srv.timeout)
  107. defer cancel()
  108. remoteConn, err := (&net.Dialer{}).DialContext(dialCtx, "udp", srv.rAddr)
  109. if err != nil {
  110. log.Printf("remote dial failed: %v", err)
  111. return
  112. }
  113. defer remoteConn.Close()
  114. util.PairConn(srv.baseCtx, conn, remoteConn, srv.idleTimeout, srv.staleMode)
  115. }
  116. func (srv *Server) contextMaker() (context.Context, func()) {
  117. return context.WithTimeout(srv.baseCtx, srv.timeout)
  118. }
  119. func (srv *Server) Close() error {
  120. srv.cancelCtx()
  121. err := srv.listener.Close()
  122. srv.workerWG.Wait()
  123. return err
  124. }