conn.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. package tf
  2. import (
  3. "context"
  4. "math/rand"
  5. "net"
  6. "strings"
  7. "time"
  8. N "github.com/sagernet/sing/common/network"
  9. "golang.org/x/net/publicsuffix"
  10. )
  11. type Conn struct {
  12. net.Conn
  13. tcpConn *net.TCPConn
  14. ctx context.Context
  15. firstPacketWritten bool
  16. fallbackDelay time.Duration
  17. }
  18. func NewConn(conn net.Conn, ctx context.Context, fallbackDelay time.Duration) (*Conn, error) {
  19. tcpConn, _ := N.UnwrapReader(conn).(*net.TCPConn)
  20. return &Conn{
  21. Conn: conn,
  22. tcpConn: tcpConn,
  23. ctx: ctx,
  24. fallbackDelay: fallbackDelay,
  25. }, nil
  26. }
  27. func (c *Conn) Write(b []byte) (n int, err error) {
  28. if !c.firstPacketWritten {
  29. defer func() {
  30. c.firstPacketWritten = true
  31. }()
  32. serverName := indexTLSServerName(b)
  33. if serverName != nil {
  34. if c.tcpConn != nil {
  35. err = c.tcpConn.SetNoDelay(true)
  36. if err != nil {
  37. return
  38. }
  39. }
  40. splits := strings.Split(serverName.ServerName, ".")
  41. currentIndex := serverName.Index
  42. if publicSuffix := publicsuffix.List.PublicSuffix(serverName.ServerName); publicSuffix != "" {
  43. splits = splits[:len(splits)-strings.Count(serverName.ServerName, ".")]
  44. }
  45. if len(splits) > 1 && splits[0] == "..." {
  46. currentIndex += len(splits[0]) + 1
  47. splits = splits[1:]
  48. }
  49. var splitIndexes []int
  50. for i, split := range splits {
  51. splitAt := rand.Intn(len(split))
  52. splitIndexes = append(splitIndexes, currentIndex+splitAt)
  53. currentIndex += len(split)
  54. if i != len(splits)-1 {
  55. currentIndex++
  56. }
  57. }
  58. for i := 0; i <= len(splitIndexes); i++ {
  59. var payload []byte
  60. if i == 0 {
  61. payload = b[:splitIndexes[i]]
  62. } else if i == len(splitIndexes) {
  63. payload = b[splitIndexes[i-1]:]
  64. } else {
  65. payload = b[splitIndexes[i-1]:splitIndexes[i]]
  66. }
  67. if c.tcpConn != nil && i != len(splitIndexes) {
  68. err = writeAndWaitAck(c.ctx, c.tcpConn, payload, c.fallbackDelay)
  69. if err != nil {
  70. return
  71. }
  72. } else {
  73. _, err = c.Conn.Write(payload)
  74. if err != nil {
  75. return
  76. }
  77. }
  78. }
  79. if c.tcpConn != nil {
  80. err = c.tcpConn.SetNoDelay(false)
  81. if err != nil {
  82. return
  83. }
  84. }
  85. return len(b), nil
  86. }
  87. }
  88. return c.Conn.Write(b)
  89. }
  90. func (c *Conn) ReaderReplaceable() bool {
  91. return true
  92. }
  93. func (c *Conn) WriterReplaceable() bool {
  94. return c.firstPacketWritten
  95. }
  96. func (c *Conn) Upstream() any {
  97. return c.Conn
  98. }