client.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. /*
  2. Some of codes are copied from https://github.com/octeep/wireproxy, license below.
  3. Copyright (c) 2022 Wind T.F. Wong <[email protected]>
  4. Permission to use, copy, modify, and distribute this software for any
  5. purpose with or without fee is hereby granted, provided that the above
  6. copyright notice and this permission notice appear in all copies.
  7. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  8. WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  9. MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  10. ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  11. WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  12. ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  13. OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  14. */
  15. package wireguard
  16. import (
  17. "context"
  18. "fmt"
  19. "net/netip"
  20. "strings"
  21. "sync"
  22. "github.com/xtls/xray-core/common"
  23. "github.com/xtls/xray-core/common/buf"
  24. "github.com/xtls/xray-core/common/dice"
  25. "github.com/xtls/xray-core/common/errors"
  26. "github.com/xtls/xray-core/common/log"
  27. "github.com/xtls/xray-core/common/net"
  28. "github.com/xtls/xray-core/common/protocol"
  29. "github.com/xtls/xray-core/common/session"
  30. "github.com/xtls/xray-core/common/signal"
  31. "github.com/xtls/xray-core/common/task"
  32. "github.com/xtls/xray-core/core"
  33. "github.com/xtls/xray-core/features/dns"
  34. "github.com/xtls/xray-core/features/policy"
  35. "github.com/xtls/xray-core/transport"
  36. "github.com/xtls/xray-core/transport/internet"
  37. )
  38. // Handler is an outbound connection that silently swallow the entire payload.
  39. type Handler struct {
  40. conf *DeviceConfig
  41. net Tunnel
  42. bind *netBindClient
  43. policyManager policy.Manager
  44. dns dns.Client
  45. // cached configuration
  46. endpoints []netip.Addr
  47. hasIPv4, hasIPv6 bool
  48. wgLock sync.Mutex
  49. }
  50. // New creates a new wireguard handler.
  51. func New(ctx context.Context, conf *DeviceConfig) (*Handler, error) {
  52. v := core.MustFromContext(ctx)
  53. endpoints, hasIPv4, hasIPv6, err := parseEndpoints(conf)
  54. if err != nil {
  55. return nil, err
  56. }
  57. d := v.GetFeature(dns.ClientType()).(dns.Client)
  58. return &Handler{
  59. conf: conf,
  60. policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
  61. dns: d,
  62. endpoints: endpoints,
  63. hasIPv4: hasIPv4,
  64. hasIPv6: hasIPv6,
  65. }, nil
  66. }
  67. func (h *Handler) Close() (err error) {
  68. go func() {
  69. h.wgLock.Lock()
  70. defer h.wgLock.Unlock()
  71. if h.net != nil {
  72. _ = h.net.Close()
  73. h.net = nil
  74. }
  75. }()
  76. return nil
  77. }
  78. func (h *Handler) processWireGuard(ctx context.Context, dialer internet.Dialer) (err error) {
  79. h.wgLock.Lock()
  80. defer h.wgLock.Unlock()
  81. if h.bind != nil && h.bind.dialer == dialer && h.net != nil {
  82. return nil
  83. }
  84. log.Record(&log.GeneralMessage{
  85. Severity: log.Severity_Info,
  86. Content: "switching dialer",
  87. })
  88. if h.net != nil {
  89. _ = h.net.Close()
  90. h.net = nil
  91. }
  92. if h.bind != nil {
  93. _ = h.bind.Close()
  94. h.bind = nil
  95. }
  96. // bind := conn.NewStdNetBind() // TODO: conn.Bind wrapper for dialer
  97. h.bind = &netBindClient{
  98. netBind: netBind{
  99. dns: h.dns,
  100. dnsOption: dns.IPOption{
  101. IPv4Enable: h.hasIPv4,
  102. IPv6Enable: h.hasIPv6,
  103. },
  104. workers: int(h.conf.NumWorkers),
  105. readQueue: make(chan *netReadInfo),
  106. },
  107. ctx: ctx,
  108. dialer: dialer,
  109. reserved: h.conf.Reserved,
  110. }
  111. defer func() {
  112. if err != nil {
  113. h.bind.Close()
  114. h.bind = nil
  115. }
  116. }()
  117. h.net, err = h.makeVirtualTun()
  118. if err != nil {
  119. return errors.New("failed to create virtual tun interface").Base(err)
  120. }
  121. return nil
  122. }
  123. // Process implements OutboundHandler.Dispatch().
  124. func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error {
  125. outbounds := session.OutboundsFromContext(ctx)
  126. ob := outbounds[len(outbounds)-1]
  127. if !ob.Target.IsValid() {
  128. return errors.New("target not specified")
  129. }
  130. ob.Name = "wireguard"
  131. ob.CanSpliceCopy = 3
  132. if err := h.processWireGuard(ctx, dialer); err != nil {
  133. return err
  134. }
  135. // Destination of the inner request.
  136. destination := ob.Target
  137. command := protocol.RequestCommandTCP
  138. if destination.Network == net.Network_UDP {
  139. command = protocol.RequestCommandUDP
  140. }
  141. // resolve dns
  142. addr := destination.Address
  143. if addr.Family().IsDomain() {
  144. ips, _, err := h.dns.LookupIP(addr.Domain(), dns.IPOption{
  145. IPv4Enable: h.hasIPv4 && h.conf.preferIP4(),
  146. IPv6Enable: h.hasIPv6 && h.conf.preferIP6(),
  147. })
  148. { // Resolve fallback
  149. if (len(ips) == 0 || err != nil) && h.conf.hasFallback() {
  150. ips, _, err = h.dns.LookupIP(addr.Domain(), dns.IPOption{
  151. IPv4Enable: h.hasIPv4 && h.conf.fallbackIP4(),
  152. IPv6Enable: h.hasIPv6 && h.conf.fallbackIP6(),
  153. })
  154. }
  155. }
  156. if err != nil {
  157. return errors.New("failed to lookup DNS").Base(err)
  158. } else if len(ips) == 0 {
  159. return dns.ErrEmptyResponse
  160. }
  161. addr = net.IPAddress(ips[dice.Roll(len(ips))])
  162. }
  163. var newCtx context.Context
  164. var newCancel context.CancelFunc
  165. if session.TimeoutOnlyFromContext(ctx) {
  166. newCtx, newCancel = context.WithCancel(context.Background())
  167. }
  168. p := h.policyManager.ForLevel(0)
  169. ctx, cancel := context.WithCancel(ctx)
  170. timer := signal.CancelAfterInactivity(ctx, func() {
  171. cancel()
  172. if newCancel != nil {
  173. newCancel()
  174. }
  175. }, p.Timeouts.ConnectionIdle)
  176. addrPort := netip.AddrPortFrom(toNetIpAddr(addr), destination.Port.Value())
  177. var requestFunc func() error
  178. var responseFunc func() error
  179. if command == protocol.RequestCommandTCP {
  180. conn, err := h.net.DialContextTCPAddrPort(ctx, addrPort)
  181. if err != nil {
  182. return errors.New("failed to create TCP connection").Base(err)
  183. }
  184. defer conn.Close()
  185. requestFunc = func() error {
  186. defer timer.SetTimeout(p.Timeouts.DownlinkOnly)
  187. return buf.Copy(link.Reader, buf.NewWriter(conn), buf.UpdateActivity(timer))
  188. }
  189. responseFunc = func() error {
  190. defer timer.SetTimeout(p.Timeouts.UplinkOnly)
  191. return buf.Copy(buf.NewReader(conn), link.Writer, buf.UpdateActivity(timer))
  192. }
  193. } else if command == protocol.RequestCommandUDP {
  194. conn, err := h.net.DialUDPAddrPort(netip.AddrPort{}, addrPort)
  195. if err != nil {
  196. return errors.New("failed to create UDP connection").Base(err)
  197. }
  198. defer conn.Close()
  199. conn = &udpConnClient{
  200. Conn: conn,
  201. dest: destination,
  202. }
  203. requestFunc = func() error {
  204. defer timer.SetTimeout(p.Timeouts.DownlinkOnly)
  205. return buf.Copy(link.Reader, buf.NewWriter(conn), buf.UpdateActivity(timer))
  206. }
  207. responseFunc = func() error {
  208. defer timer.SetTimeout(p.Timeouts.UplinkOnly)
  209. return buf.Copy(buf.NewReader(conn), link.Writer, buf.UpdateActivity(timer))
  210. }
  211. }
  212. if newCtx != nil {
  213. ctx = newCtx
  214. }
  215. responseDonePost := task.OnSuccess(responseFunc, task.Close(link.Writer))
  216. if err := task.Run(ctx, requestFunc, responseDonePost); err != nil {
  217. common.Interrupt(link.Reader)
  218. common.Interrupt(link.Writer)
  219. return errors.New("connection ends").Base(err)
  220. }
  221. return nil
  222. }
  223. // creates a tun interface on netstack given a configuration
  224. func (h *Handler) makeVirtualTun() (Tunnel, error) {
  225. t, err := h.conf.createTun()(h.endpoints, int(h.conf.Mtu), nil)
  226. if err != nil {
  227. return nil, err
  228. }
  229. h.bind.dnsOption.IPv4Enable = h.hasIPv4
  230. h.bind.dnsOption.IPv6Enable = h.hasIPv6
  231. if err = t.BuildDevice(h.createIPCRequest(), h.bind); err != nil {
  232. _ = t.Close()
  233. return nil, err
  234. }
  235. return t, nil
  236. }
  237. // serialize the config into an IPC request
  238. func (h *Handler) createIPCRequest() string {
  239. var request strings.Builder
  240. request.WriteString(fmt.Sprintf("private_key=%s\n", h.conf.SecretKey))
  241. if !h.conf.IsClient {
  242. // placeholder, we'll handle actual port listening on Xray
  243. request.WriteString("listen_port=1337\n")
  244. }
  245. for _, peer := range h.conf.Peers {
  246. if peer.PublicKey != "" {
  247. request.WriteString(fmt.Sprintf("public_key=%s\n", peer.PublicKey))
  248. }
  249. if peer.PreSharedKey != "" {
  250. request.WriteString(fmt.Sprintf("preshared_key=%s\n", peer.PreSharedKey))
  251. }
  252. address, port, err := net.SplitHostPort(peer.Endpoint)
  253. if err != nil {
  254. errors.LogError(h.bind.ctx, "failed to split endpoint ", peer.Endpoint, " into address and port")
  255. }
  256. addr := net.ParseAddress(address)
  257. if addr.Family().IsDomain() {
  258. dialerIp := h.bind.dialer.DestIpAddress()
  259. if dialerIp != nil {
  260. addr = net.ParseAddress(dialerIp.String())
  261. errors.LogInfo(h.bind.ctx, "createIPCRequest use dialer dest ip: ", addr)
  262. } else {
  263. ips, _, err := h.dns.LookupIP(addr.Domain(), dns.IPOption{
  264. IPv4Enable: h.conf.preferIP4(),
  265. IPv6Enable: h.conf.preferIP6(),
  266. })
  267. { // Resolve fallback
  268. if (len(ips) == 0 || err != nil) && h.conf.hasFallback() {
  269. ips, _, err = h.dns.LookupIP(addr.Domain(), dns.IPOption{
  270. IPv4Enable: h.conf.fallbackIP4(),
  271. IPv6Enable: h.conf.fallbackIP6(),
  272. })
  273. }
  274. }
  275. if err != nil {
  276. errors.LogInfoInner(h.bind.ctx, err, "createIPCRequest failed to lookup DNS")
  277. } else if len(ips) == 0 {
  278. errors.LogInfo(h.bind.ctx, "createIPCRequest empty lookup DNS")
  279. } else {
  280. addr = net.IPAddress(ips[dice.Roll(len(ips))])
  281. }
  282. }
  283. }
  284. if peer.Endpoint != "" {
  285. request.WriteString(fmt.Sprintf("endpoint=%s:%s\n", addr, port))
  286. }
  287. for _, ip := range peer.AllowedIps {
  288. request.WriteString(fmt.Sprintf("allowed_ip=%s\n", ip))
  289. }
  290. if peer.KeepAlive != 0 {
  291. request.WriteString(fmt.Sprintf("persistent_keepalive_interval=%d\n", peer.KeepAlive))
  292. }
  293. }
  294. return request.String()[:request.Len()]
  295. }
  296. type udpConnClient struct {
  297. net.Conn
  298. dest net.Destination
  299. }
  300. func (c *udpConnClient) ReadMultiBuffer() (buf.MultiBuffer, error) {
  301. b := buf.New()
  302. b.Resize(0, buf.Size)
  303. n, addr, err := c.Conn.(net.PacketConn).ReadFrom(b.Bytes())
  304. if err != nil {
  305. b.Release()
  306. return nil, err
  307. }
  308. if addr == nil { // should never hit
  309. addr = c.dest.RawNetAddr()
  310. }
  311. b.Resize(0, int32(n))
  312. b.UDP = &net.Destination{
  313. Address: net.IPAddress(addr.(*net.UDPAddr).IP),
  314. Port: net.Port(addr.(*net.UDPAddr).Port),
  315. Network: net.Network_UDP,
  316. }
  317. return buf.MultiBuffer{b}, nil
  318. }
  319. func (c *udpConnClient) Write(p []byte) (int, error) {
  320. return c.Conn.(net.PacketConn).WriteTo(p, c.dest.RawNetAddr())
  321. }