bind.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. package wireguard
  2. import (
  3. "context"
  4. "errors"
  5. "io"
  6. "net"
  7. "net/netip"
  8. "strconv"
  9. "sync"
  10. "github.com/sagernet/wireguard-go/conn"
  11. xnet "github.com/xtls/xray-core/common/net"
  12. "github.com/xtls/xray-core/features/dns"
  13. "github.com/xtls/xray-core/transport/internet"
  14. )
  15. type netReadInfo struct {
  16. // status
  17. waiter sync.WaitGroup
  18. // param
  19. buff []byte
  20. // result
  21. bytes int
  22. endpoint conn.Endpoint
  23. err error
  24. }
  25. type netBindClient struct {
  26. workers int
  27. dialer internet.Dialer
  28. dns dns.Client
  29. dnsOption dns.IPOption
  30. readQueue chan *netReadInfo
  31. }
  32. func (n *netBindClient) ParseEndpoint(s string) (conn.Endpoint, error) {
  33. ipStr, port, _, err := splitAddrPort(s)
  34. if err != nil {
  35. return nil, err
  36. }
  37. var addr net.IP
  38. if IsDomainName(ipStr) {
  39. ips, err := n.dns.LookupIP(ipStr, n.dnsOption)
  40. if err != nil {
  41. return nil, err
  42. } else if len(ips) == 0 {
  43. return nil, dns.ErrEmptyResponse
  44. }
  45. addr = ips[0]
  46. } else {
  47. addr = net.ParseIP(ipStr)
  48. }
  49. if addr == nil {
  50. return nil, errors.New("failed to parse ip: " + ipStr)
  51. }
  52. var ip xnet.Address
  53. if p4 := addr.To4(); len(p4) == net.IPv4len {
  54. ip = xnet.IPAddress(p4[:])
  55. } else {
  56. ip = xnet.IPAddress(addr[:])
  57. }
  58. dst := xnet.Destination{
  59. Address: ip,
  60. Port: xnet.Port(port),
  61. Network: xnet.Network_UDP,
  62. }
  63. return &netEndpoint{
  64. dst: dst,
  65. }, nil
  66. }
  67. func (bind *netBindClient) Open(uport uint16) ([]conn.ReceiveFunc, uint16, error) {
  68. bind.readQueue = make(chan *netReadInfo)
  69. fun := func(buff []byte) (cap int, ep conn.Endpoint, err error) {
  70. defer func() {
  71. if r := recover(); r != nil {
  72. cap = 0
  73. ep = nil
  74. err = errors.New("channel closed")
  75. }
  76. }()
  77. r := &netReadInfo{
  78. buff: buff,
  79. }
  80. r.waiter.Add(1)
  81. bind.readQueue <- r
  82. r.waiter.Wait() // wait read goroutine done, or we will miss the result
  83. return r.bytes, r.endpoint, r.err
  84. }
  85. workers := bind.workers
  86. if workers <= 0 {
  87. workers = 1
  88. }
  89. arr := make([]conn.ReceiveFunc, workers)
  90. for i := 0; i < workers; i++ {
  91. arr[i] = fun
  92. }
  93. return arr, uint16(uport), nil
  94. }
  95. func (bind *netBindClient) Close() error {
  96. if bind.readQueue != nil {
  97. close(bind.readQueue)
  98. }
  99. return nil
  100. }
  101. func (bind *netBindClient) connectTo(endpoint *netEndpoint) error {
  102. c, err := bind.dialer.Dial(context.Background(), endpoint.dst)
  103. if err != nil {
  104. return err
  105. }
  106. endpoint.conn = c
  107. go func(readQueue <-chan *netReadInfo, endpoint *netEndpoint) {
  108. for {
  109. v, ok := <-readQueue
  110. if !ok {
  111. return
  112. }
  113. i, err := c.Read(v.buff)
  114. v.bytes = i
  115. v.endpoint = endpoint
  116. v.err = err
  117. v.waiter.Done()
  118. if err != nil && errors.Is(err, io.EOF) {
  119. endpoint.conn = nil
  120. return
  121. }
  122. }
  123. }(bind.readQueue, endpoint)
  124. return nil
  125. }
  126. func (bind *netBindClient) Send(buff []byte, endpoint conn.Endpoint) error {
  127. var err error
  128. nend, ok := endpoint.(*netEndpoint)
  129. if !ok {
  130. return conn.ErrWrongEndpointType
  131. }
  132. if nend.conn == nil {
  133. err = bind.connectTo(nend)
  134. if err != nil {
  135. return err
  136. }
  137. }
  138. _, err = nend.conn.Write(buff)
  139. return err
  140. }
  141. func (bind *netBindClient) SetMark(mark uint32) error {
  142. return nil
  143. }
  144. type netEndpoint struct {
  145. dst xnet.Destination
  146. conn net.Conn
  147. }
  148. func (netEndpoint) ClearSrc() {}
  149. func (e netEndpoint) DstIP() netip.Addr {
  150. return toNetIpAddr(e.dst.Address)
  151. }
  152. func (e netEndpoint) SrcIP() netip.Addr {
  153. return netip.Addr{}
  154. }
  155. func (e netEndpoint) DstToBytes() []byte {
  156. var dat []byte
  157. if e.dst.Address.Family().IsIPv4() {
  158. dat = e.dst.Address.IP().To4()[:]
  159. } else {
  160. dat = e.dst.Address.IP().To16()[:]
  161. }
  162. dat = append(dat, byte(e.dst.Port), byte(e.dst.Port>>8))
  163. return dat
  164. }
  165. func (e netEndpoint) DstToString() string {
  166. return e.dst.NetAddr()
  167. }
  168. func (e netEndpoint) SrcToString() string {
  169. return ""
  170. }
  171. func toNetIpAddr(addr xnet.Address) netip.Addr {
  172. if addr.Family().IsIPv4() {
  173. ip := addr.IP()
  174. return netip.AddrFrom4([4]byte{ip[0], ip[1], ip[2], ip[3]})
  175. } else {
  176. ip := addr.IP()
  177. arr := [16]byte{}
  178. for i := 0; i < 16; i++ {
  179. arr[i] = ip[i]
  180. }
  181. return netip.AddrFrom16(arr)
  182. }
  183. }
  184. func stringsLastIndexByte(s string, b byte) int {
  185. for i := len(s) - 1; i >= 0; i-- {
  186. if s[i] == b {
  187. return i
  188. }
  189. }
  190. return -1
  191. }
  192. func splitAddrPort(s string) (ip string, port uint16, v6 bool, err error) {
  193. i := stringsLastIndexByte(s, ':')
  194. if i == -1 {
  195. return "", 0, false, errors.New("not an ip:port")
  196. }
  197. ip = s[:i]
  198. portStr := s[i+1:]
  199. if len(ip) == 0 {
  200. return "", 0, false, errors.New("no IP")
  201. }
  202. if len(portStr) == 0 {
  203. return "", 0, false, errors.New("no port")
  204. }
  205. port64, err := strconv.ParseUint(portStr, 10, 16)
  206. if err != nil {
  207. return "", 0, false, errors.New("invalid port " + strconv.Quote(portStr) + " parsing " + strconv.Quote(s))
  208. }
  209. port = uint16(port64)
  210. if ip[0] == '[' {
  211. if len(ip) < 2 || ip[len(ip)-1] != ']' {
  212. return "", 0, false, errors.New("missing ]")
  213. }
  214. ip = ip[1 : len(ip)-1]
  215. v6 = true
  216. }
  217. return ip, port, v6, nil
  218. }