client.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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/log"
  26. "github.com/xtls/xray-core/common/net"
  27. "github.com/xtls/xray-core/common/protocol"
  28. "github.com/xtls/xray-core/common/session"
  29. "github.com/xtls/xray-core/common/signal"
  30. "github.com/xtls/xray-core/common/task"
  31. "github.com/xtls/xray-core/core"
  32. "github.com/xtls/xray-core/features/dns"
  33. "github.com/xtls/xray-core/features/policy"
  34. "github.com/xtls/xray-core/transport"
  35. "github.com/xtls/xray-core/transport/internet"
  36. )
  37. // Handler is an outbound connection that silently swallow the entire payload.
  38. type Handler struct {
  39. conf *DeviceConfig
  40. net Tunnel
  41. bind *netBindClient
  42. policyManager policy.Manager
  43. dns dns.Client
  44. // cached configuration
  45. endpoints []netip.Addr
  46. hasIPv4, hasIPv6 bool
  47. wgLock sync.Mutex
  48. }
  49. // New creates a new wireguard handler.
  50. func New(ctx context.Context, conf *DeviceConfig) (*Handler, error) {
  51. v := core.MustFromContext(ctx)
  52. endpoints, hasIPv4, hasIPv6, err := parseEndpoints(conf)
  53. if err != nil {
  54. return nil, err
  55. }
  56. d := v.GetFeature(dns.ClientType()).(dns.Client)
  57. return &Handler{
  58. conf: conf,
  59. policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
  60. dns: d,
  61. endpoints: endpoints,
  62. hasIPv4: hasIPv4,
  63. hasIPv6: hasIPv6,
  64. }, nil
  65. }
  66. func (h *Handler) processWireGuard(dialer internet.Dialer) (err error) {
  67. h.wgLock.Lock()
  68. defer h.wgLock.Unlock()
  69. if h.bind != nil && h.bind.dialer == dialer && h.net != nil {
  70. return nil
  71. }
  72. log.Record(&log.GeneralMessage{
  73. Severity: log.Severity_Info,
  74. Content: "switching dialer",
  75. })
  76. if h.net != nil {
  77. _ = h.net.Close()
  78. h.net = nil
  79. }
  80. if h.bind != nil {
  81. _ = h.bind.Close()
  82. h.bind = nil
  83. }
  84. // bind := conn.NewStdNetBind() // TODO: conn.Bind wrapper for dialer
  85. bind := &netBindClient{
  86. netBind: netBind{
  87. dns: h.dns,
  88. dnsOption: dns.IPOption{
  89. IPv4Enable: h.hasIPv4,
  90. IPv6Enable: h.hasIPv6,
  91. },
  92. workers: int(h.conf.NumWorkers),
  93. },
  94. dialer: dialer,
  95. reserved: h.conf.Reserved,
  96. }
  97. defer func() {
  98. if err != nil {
  99. _ = bind.Close()
  100. }
  101. }()
  102. h.net, err = h.makeVirtualTun(bind)
  103. if err != nil {
  104. return newError("failed to create virtual tun interface").Base(err)
  105. }
  106. h.bind = bind
  107. return nil
  108. }
  109. // Process implements OutboundHandler.Dispatch().
  110. func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error {
  111. outbounds := session.OutboundsFromContext(ctx)
  112. ob := outbounds[len(outbounds) - 1]
  113. if !ob.Target.IsValid() {
  114. return newError("target not specified")
  115. }
  116. ob.Name = "wireguard"
  117. ob.CanSpliceCopy = 3
  118. if err := h.processWireGuard(dialer); err != nil {
  119. return err
  120. }
  121. // Destination of the inner request.
  122. destination := ob.Target
  123. command := protocol.RequestCommandTCP
  124. if destination.Network == net.Network_UDP {
  125. command = protocol.RequestCommandUDP
  126. }
  127. // resolve dns
  128. addr := destination.Address
  129. if addr.Family().IsDomain() {
  130. ips, err := h.dns.LookupIP(addr.Domain(), dns.IPOption{
  131. IPv4Enable: h.hasIPv4 && h.conf.preferIP4(),
  132. IPv6Enable: h.hasIPv6 && h.conf.preferIP6(),
  133. })
  134. { // Resolve fallback
  135. if (len(ips) == 0 || err != nil) && h.conf.hasFallback() {
  136. ips, err = h.dns.LookupIP(addr.Domain(), dns.IPOption{
  137. IPv4Enable: h.hasIPv4 && h.conf.fallbackIP4(),
  138. IPv6Enable: h.hasIPv6 && h.conf.fallbackIP6(),
  139. })
  140. }
  141. }
  142. if err != nil {
  143. return newError("failed to lookup DNS").Base(err)
  144. } else if len(ips) == 0 {
  145. return dns.ErrEmptyResponse
  146. }
  147. addr = net.IPAddress(ips[dice.Roll(len(ips))])
  148. }
  149. var newCtx context.Context
  150. var newCancel context.CancelFunc
  151. if session.TimeoutOnlyFromContext(ctx) {
  152. newCtx, newCancel = context.WithCancel(context.Background())
  153. }
  154. p := h.policyManager.ForLevel(0)
  155. ctx, cancel := context.WithCancel(ctx)
  156. timer := signal.CancelAfterInactivity(ctx, func() {
  157. cancel()
  158. if newCancel != nil {
  159. newCancel()
  160. }
  161. }, p.Timeouts.ConnectionIdle)
  162. addrPort := netip.AddrPortFrom(toNetIpAddr(addr), destination.Port.Value())
  163. var requestFunc func() error
  164. var responseFunc func() error
  165. if command == protocol.RequestCommandTCP {
  166. conn, err := h.net.DialContextTCPAddrPort(ctx, addrPort)
  167. if err != nil {
  168. return newError("failed to create TCP connection").Base(err)
  169. }
  170. defer conn.Close()
  171. requestFunc = func() error {
  172. defer timer.SetTimeout(p.Timeouts.DownlinkOnly)
  173. return buf.Copy(link.Reader, buf.NewWriter(conn), buf.UpdateActivity(timer))
  174. }
  175. responseFunc = func() error {
  176. defer timer.SetTimeout(p.Timeouts.UplinkOnly)
  177. return buf.Copy(buf.NewReader(conn), link.Writer, buf.UpdateActivity(timer))
  178. }
  179. } else if command == protocol.RequestCommandUDP {
  180. conn, err := h.net.DialUDPAddrPort(netip.AddrPort{}, addrPort)
  181. if err != nil {
  182. return newError("failed to create UDP 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. }
  194. if newCtx != nil {
  195. ctx = newCtx
  196. }
  197. responseDonePost := task.OnSuccess(responseFunc, task.Close(link.Writer))
  198. if err := task.Run(ctx, requestFunc, responseDonePost); err != nil {
  199. common.Interrupt(link.Reader)
  200. common.Interrupt(link.Writer)
  201. return newError("connection ends").Base(err)
  202. }
  203. return nil
  204. }
  205. // creates a tun interface on netstack given a configuration
  206. func (h *Handler) makeVirtualTun(bind *netBindClient) (Tunnel, error) {
  207. t, err := h.conf.createTun()(h.endpoints, int(h.conf.Mtu), nil)
  208. if err != nil {
  209. return nil, err
  210. }
  211. bind.dnsOption.IPv4Enable = h.hasIPv4
  212. bind.dnsOption.IPv6Enable = h.hasIPv6
  213. if err = t.BuildDevice(h.createIPCRequest(bind, h.conf), bind); err != nil {
  214. _ = t.Close()
  215. return nil, err
  216. }
  217. return t, nil
  218. }
  219. // serialize the config into an IPC request
  220. func (h *Handler) createIPCRequest(bind *netBindClient, conf *DeviceConfig) string {
  221. var request strings.Builder
  222. request.WriteString(fmt.Sprintf("private_key=%s\n", conf.SecretKey))
  223. if !conf.IsClient {
  224. // placeholder, we'll handle actual port listening on Xray
  225. request.WriteString("listen_port=1337\n")
  226. }
  227. for _, peer := range conf.Peers {
  228. if peer.PublicKey != "" {
  229. request.WriteString(fmt.Sprintf("public_key=%s\n", peer.PublicKey))
  230. }
  231. if peer.PreSharedKey != "" {
  232. request.WriteString(fmt.Sprintf("preshared_key=%s\n", peer.PreSharedKey))
  233. }
  234. address, port, err := net.SplitHostPort(peer.Endpoint)
  235. if err != nil {
  236. newError("failed to split endpoint ", peer.Endpoint, " into address and port").AtError().WriteToLog()
  237. }
  238. addr := net.ParseAddress(address)
  239. if addr.Family().IsDomain() {
  240. dialerIp := bind.dialer.DestIpAddress()
  241. if dialerIp != nil {
  242. addr = net.ParseAddress(dialerIp.String())
  243. newError("createIPCRequest use dialer dest ip: ", addr).WriteToLog()
  244. } else {
  245. ips, err := h.dns.LookupIP(addr.Domain(), dns.IPOption{
  246. IPv4Enable: h.hasIPv4 && h.conf.preferIP4(),
  247. IPv6Enable: h.hasIPv6 && h.conf.preferIP6(),
  248. })
  249. { // Resolve fallback
  250. if (len(ips) == 0 || err != nil) && h.conf.hasFallback() {
  251. ips, err = h.dns.LookupIP(addr.Domain(), dns.IPOption{
  252. IPv4Enable: h.hasIPv4 && h.conf.fallbackIP4(),
  253. IPv6Enable: h.hasIPv6 && h.conf.fallbackIP6(),
  254. })
  255. }
  256. }
  257. if err != nil {
  258. newError("createIPCRequest failed to lookup DNS").Base(err).WriteToLog()
  259. } else if len(ips) == 0 {
  260. newError("createIPCRequest empty lookup DNS").WriteToLog()
  261. } else {
  262. addr = net.IPAddress(ips[dice.Roll(len(ips))])
  263. }
  264. }
  265. }
  266. if peer.Endpoint != "" {
  267. request.WriteString(fmt.Sprintf("endpoint=%s:%s\n", addr, port))
  268. }
  269. for _, ip := range peer.AllowedIps {
  270. request.WriteString(fmt.Sprintf("allowed_ip=%s\n", ip))
  271. }
  272. if peer.KeepAlive != 0 {
  273. request.WriteString(fmt.Sprintf("persistent_keepalive_interval=%d\n", peer.KeepAlive))
  274. }
  275. }
  276. return request.String()[:request.Len()]
  277. }