server.go 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  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. CipherSuites: []dtls.CipherSuiteID{
  46. dtls.TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256,
  47. dtls.TLS_PSK_WITH_AES_128_CCM,
  48. dtls.TLS_PSK_WITH_AES_128_CCM_8,
  49. dtls.TLS_PSK_WITH_AES_256_CCM_8,
  50. dtls.TLS_PSK_WITH_AES_128_GCM_SHA256,
  51. dtls.TLS_PSK_WITH_AES_128_CBC_SHA256,
  52. },
  53. ExtendedMasterSecret: dtls.RequireExtendedMasterSecret,
  54. ConnectContextMaker: srv.contextMaker,
  55. PSK: srv.psk,
  56. MTU: cfg.MTU,
  57. InsecureSkipVerifyHello: cfg.SkipHelloVerify,
  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. go func(conn net.Conn) {
  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(conn, remoteConn, srv.idleTimeout)
  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. return srv.listener.Close()
  122. }