client.go 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. package client
  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/transport/v2/udp"
  13. )
  14. const (
  15. MaxPktBuf = 65536
  16. Backlog = 1024
  17. )
  18. type Client struct {
  19. listener net.Listener
  20. dtlsConfig *dtls.Config
  21. remoteDialFn func(context.Context, string) (net.Conn, error)
  22. psk func([]byte) ([]byte, error)
  23. timeout time.Duration
  24. idleTimeout time.Duration
  25. baseCtx context.Context
  26. cancelCtx func()
  27. staleMode util.StaleMode
  28. workerWG sync.WaitGroup
  29. timeLimitFunc func() time.Duration
  30. allowFunc func(net.Addr, net.Addr) bool
  31. }
  32. func New(cfg *Config) (*Client, error) {
  33. cfg = cfg.populateDefaults()
  34. baseCtx, cancelCtx := context.WithCancel(cfg.BaseContext)
  35. client := &Client{
  36. remoteDialFn: cfg.RemoteDialFunc,
  37. timeout: cfg.Timeout,
  38. psk: cfg.PSKCallback,
  39. idleTimeout: cfg.IdleTimeout,
  40. baseCtx: baseCtx,
  41. cancelCtx: cancelCtx,
  42. staleMode: cfg.StaleMode,
  43. timeLimitFunc: cfg.TimeLimitFunc,
  44. allowFunc: cfg.AllowFunc,
  45. }
  46. lAddrPort, err := netip.ParseAddrPort(cfg.BindAddress)
  47. if err != nil {
  48. cancelCtx()
  49. return nil, fmt.Errorf("can't parse bind address: %w", err)
  50. }
  51. client.dtlsConfig = &dtls.Config{
  52. ExtendedMasterSecret: dtls.RequireExtendedMasterSecret,
  53. ConnectContextMaker: client.contextMaker,
  54. PSK: client.psk,
  55. PSKIdentityHint: []byte(cfg.PSKIdentity),
  56. MTU: cfg.MTU,
  57. CipherSuites: cfg.CipherSuites,
  58. EllipticCurves: cfg.EllipticCurves,
  59. }
  60. lc := udp.ListenConfig{
  61. Backlog: Backlog,
  62. }
  63. listener, err := lc.Listen("udp", net.UDPAddrFromAddrPort(lAddrPort))
  64. if err != nil {
  65. cancelCtx()
  66. return nil, fmt.Errorf("client listen failed: %w", err)
  67. }
  68. client.listener = listener
  69. go client.listen()
  70. return client, nil
  71. }
  72. func (client *Client) listen() {
  73. defer client.Close()
  74. for client.baseCtx.Err() == nil {
  75. conn, err := client.listener.Accept()
  76. if err != nil {
  77. log.Printf("conn accept failed: %v", err)
  78. continue
  79. }
  80. if !client.allowFunc(conn.LocalAddr(), conn.RemoteAddr()) {
  81. continue
  82. }
  83. client.workerWG.Add(1)
  84. go func(conn net.Conn) {
  85. defer client.workerWG.Done()
  86. defer conn.Close()
  87. client.serve(conn)
  88. }(conn)
  89. }
  90. }
  91. func (client *Client) serve(conn net.Conn) {
  92. log.Printf("[+] conn %s <=> %s", conn.LocalAddr(), conn.RemoteAddr())
  93. defer log.Printf("[-] conn %s <=> %s", conn.LocalAddr(), conn.RemoteAddr())
  94. defer conn.Close()
  95. ctx := client.baseCtx
  96. tl := client.timeLimitFunc()
  97. if tl != 0 {
  98. newCtx, cancel := context.WithTimeout(ctx, tl)
  99. defer cancel()
  100. ctx = newCtx
  101. }
  102. dialCtx, cancel := context.WithTimeout(ctx, client.timeout)
  103. defer cancel()
  104. remoteConn, err := client.remoteDialFn(dialCtx, "udp")
  105. if err != nil {
  106. log.Printf("remote dial failed: %v", err)
  107. return
  108. }
  109. defer remoteConn.Close()
  110. remoteConn, err = dtls.ClientWithContext(dialCtx, remoteConn, client.dtlsConfig)
  111. if err != nil {
  112. log.Printf("DTLS handshake with remote server failed: %v", err)
  113. return
  114. }
  115. util.PairConn(ctx, conn, remoteConn, client.idleTimeout, client.staleMode)
  116. }
  117. func (client *Client) contextMaker() (context.Context, func()) {
  118. return context.WithTimeout(client.baseCtx, client.timeout)
  119. }
  120. func (client *Client) Close() error {
  121. client.cancelCtx()
  122. err := client.listener.Close()
  123. client.workerWG.Wait()
  124. return err
  125. }