inbound.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693
  1. package inbound
  2. import (
  3. "bytes"
  4. "context"
  5. gotls "crypto/tls"
  6. "encoding/base64"
  7. "io"
  8. "reflect"
  9. "strconv"
  10. "strings"
  11. "time"
  12. "unsafe"
  13. "github.com/xtls/xray-core/app/reverse"
  14. "github.com/xtls/xray-core/common"
  15. "github.com/xtls/xray-core/common/buf"
  16. "github.com/xtls/xray-core/common/errors"
  17. "github.com/xtls/xray-core/common/log"
  18. "github.com/xtls/xray-core/common/mux"
  19. "github.com/xtls/xray-core/common/net"
  20. "github.com/xtls/xray-core/common/protocol"
  21. "github.com/xtls/xray-core/common/retry"
  22. "github.com/xtls/xray-core/common/serial"
  23. "github.com/xtls/xray-core/common/session"
  24. "github.com/xtls/xray-core/common/signal"
  25. "github.com/xtls/xray-core/common/task"
  26. "github.com/xtls/xray-core/core"
  27. "github.com/xtls/xray-core/features/dns"
  28. feature_inbound "github.com/xtls/xray-core/features/inbound"
  29. "github.com/xtls/xray-core/features/outbound"
  30. "github.com/xtls/xray-core/features/policy"
  31. "github.com/xtls/xray-core/features/routing"
  32. "github.com/xtls/xray-core/proxy"
  33. "github.com/xtls/xray-core/proxy/vless"
  34. "github.com/xtls/xray-core/proxy/vless/encoding"
  35. "github.com/xtls/xray-core/proxy/vless/encryption"
  36. "github.com/xtls/xray-core/transport"
  37. "github.com/xtls/xray-core/transport/internet/reality"
  38. "github.com/xtls/xray-core/transport/internet/stat"
  39. "github.com/xtls/xray-core/transport/internet/tls"
  40. )
  41. func init() {
  42. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  43. var dc dns.Client
  44. if err := core.RequireFeatures(ctx, func(d dns.Client) error {
  45. dc = d
  46. return nil
  47. }); err != nil {
  48. return nil, err
  49. }
  50. c := config.(*Config)
  51. validator := new(vless.MemoryValidator)
  52. for _, user := range c.Clients {
  53. u, err := user.ToMemoryUser()
  54. if err != nil {
  55. return nil, errors.New("failed to get VLESS user").Base(err).AtError()
  56. }
  57. if err := validator.Add(u); err != nil {
  58. return nil, errors.New("failed to initiate user").Base(err).AtError()
  59. }
  60. }
  61. return New(ctx, c, dc, validator)
  62. }))
  63. }
  64. // Handler is an inbound connection handler that handles messages in VLess protocol.
  65. type Handler struct {
  66. inboundHandlerManager feature_inbound.Manager
  67. policyManager policy.Manager
  68. validator vless.Validator
  69. decryption *encryption.ServerInstance
  70. outboundHandlerManager outbound.Manager
  71. wrapLink func(ctx context.Context, link *transport.Link) *transport.Link
  72. ctx context.Context
  73. fallbacks map[string]map[string]map[string]*Fallback // or nil
  74. // regexps map[string]*regexp.Regexp // or nil
  75. }
  76. // New creates a new VLess inbound handler.
  77. func New(ctx context.Context, config *Config, dc dns.Client, validator vless.Validator) (*Handler, error) {
  78. v := core.MustFromContext(ctx)
  79. var wrapLinkFunc func(ctx context.Context, link *transport.Link) *transport.Link
  80. if dispatcher, ok := v.GetFeature(routing.DispatcherType()).(routing.WrapLinkDispatcher); ok {
  81. wrapLinkFunc = dispatcher.WrapLink
  82. }
  83. handler := &Handler{
  84. inboundHandlerManager: v.GetFeature(feature_inbound.ManagerType()).(feature_inbound.Manager),
  85. policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
  86. validator: validator,
  87. outboundHandlerManager: v.GetFeature(outbound.ManagerType()).(outbound.Manager),
  88. wrapLink: wrapLinkFunc,
  89. ctx: ctx,
  90. }
  91. if config.Decryption != "" && config.Decryption != "none" {
  92. s := strings.Split(config.Decryption, ".")
  93. var nfsSKeysBytes [][]byte
  94. for _, r := range s {
  95. b, _ := base64.RawURLEncoding.DecodeString(r)
  96. nfsSKeysBytes = append(nfsSKeysBytes, b)
  97. }
  98. handler.decryption = &encryption.ServerInstance{}
  99. if err := handler.decryption.Init(nfsSKeysBytes, config.XorMode, config.SecondsFrom, config.SecondsTo, config.Padding); err != nil {
  100. return nil, errors.New("failed to use decryption").Base(err).AtError()
  101. }
  102. }
  103. if config.Fallbacks != nil {
  104. handler.fallbacks = make(map[string]map[string]map[string]*Fallback)
  105. // handler.regexps = make(map[string]*regexp.Regexp)
  106. for _, fb := range config.Fallbacks {
  107. if handler.fallbacks[fb.Name] == nil {
  108. handler.fallbacks[fb.Name] = make(map[string]map[string]*Fallback)
  109. }
  110. if handler.fallbacks[fb.Name][fb.Alpn] == nil {
  111. handler.fallbacks[fb.Name][fb.Alpn] = make(map[string]*Fallback)
  112. }
  113. handler.fallbacks[fb.Name][fb.Alpn][fb.Path] = fb
  114. /*
  115. if fb.Path != "" {
  116. if r, err := regexp.Compile(fb.Path); err != nil {
  117. return nil, errors.New("invalid path regexp").Base(err).AtError()
  118. } else {
  119. handler.regexps[fb.Path] = r
  120. }
  121. }
  122. */
  123. }
  124. if handler.fallbacks[""] != nil {
  125. for name, apfb := range handler.fallbacks {
  126. if name != "" {
  127. for alpn := range handler.fallbacks[""] {
  128. if apfb[alpn] == nil {
  129. apfb[alpn] = make(map[string]*Fallback)
  130. }
  131. }
  132. }
  133. }
  134. }
  135. for _, apfb := range handler.fallbacks {
  136. if apfb[""] != nil {
  137. for alpn, pfb := range apfb {
  138. if alpn != "" { // && alpn != "h2" {
  139. for path, fb := range apfb[""] {
  140. if pfb[path] == nil {
  141. pfb[path] = fb
  142. }
  143. }
  144. }
  145. }
  146. }
  147. }
  148. if handler.fallbacks[""] != nil {
  149. for name, apfb := range handler.fallbacks {
  150. if name != "" {
  151. for alpn, pfb := range handler.fallbacks[""] {
  152. for path, fb := range pfb {
  153. if apfb[alpn][path] == nil {
  154. apfb[alpn][path] = fb
  155. }
  156. }
  157. }
  158. }
  159. }
  160. }
  161. }
  162. return handler, nil
  163. }
  164. func isMuxAndNotXUDP(request *protocol.RequestHeader, first *buf.Buffer) bool {
  165. if request.Command != protocol.RequestCommandMux {
  166. return false
  167. }
  168. if first.Len() < 7 {
  169. return true
  170. }
  171. firstBytes := first.Bytes()
  172. return !(firstBytes[2] == 0 && // ID high
  173. firstBytes[3] == 0 && // ID low
  174. firstBytes[6] == 2) // Network type: UDP
  175. }
  176. func (h *Handler) GetReverse(a *vless.MemoryAccount) (*Reverse, error) {
  177. u := h.validator.Get(a.ID.UUID())
  178. if u == nil {
  179. return nil, errors.New("reverse: user " + a.ID.String() + " doesn't exist anymore")
  180. }
  181. a = u.Account.(*vless.MemoryAccount)
  182. if a.Reverse == nil || a.Reverse.Tag == "" {
  183. return nil, errors.New("reverse: user " + a.ID.String() + " is not allowed to create reverse proxy")
  184. }
  185. r := h.outboundHandlerManager.GetHandler(a.Reverse.Tag)
  186. if r == nil {
  187. picker, _ := reverse.NewStaticMuxPicker()
  188. r = &Reverse{tag: a.Reverse.Tag, picker: picker, client: &mux.ClientManager{Picker: picker}}
  189. for len(h.outboundHandlerManager.ListHandlers(h.ctx)) == 0 {
  190. time.Sleep(time.Second) // prevents this outbound from becoming the default outbound
  191. }
  192. if err := h.outboundHandlerManager.AddHandler(h.ctx, r); err != nil {
  193. return nil, err
  194. }
  195. }
  196. if r, ok := r.(*Reverse); ok {
  197. return r, nil
  198. }
  199. return nil, errors.New("reverse: outbound " + a.Reverse.Tag + " is not type Reverse")
  200. }
  201. func (h *Handler) RemoveReverse(u *protocol.MemoryUser) {
  202. if u != nil {
  203. a := u.Account.(*vless.MemoryAccount)
  204. if a.Reverse != nil && a.Reverse.Tag != "" {
  205. h.outboundHandlerManager.RemoveHandler(h.ctx, a.Reverse.Tag)
  206. }
  207. }
  208. }
  209. // Close implements common.Closable.Close().
  210. func (h *Handler) Close() error {
  211. if h.decryption != nil {
  212. h.decryption.Close()
  213. }
  214. for _, u := range h.validator.GetAll() {
  215. h.RemoveReverse(u)
  216. }
  217. return errors.Combine(common.Close(h.validator))
  218. }
  219. // AddUser implements proxy.UserManager.AddUser().
  220. func (h *Handler) AddUser(ctx context.Context, u *protocol.MemoryUser) error {
  221. return h.validator.Add(u)
  222. }
  223. // RemoveUser implements proxy.UserManager.RemoveUser().
  224. func (h *Handler) RemoveUser(ctx context.Context, e string) error {
  225. h.RemoveReverse(h.validator.GetByEmail(e))
  226. return h.validator.Del(e)
  227. }
  228. // GetUser implements proxy.UserManager.GetUser().
  229. func (h *Handler) GetUser(ctx context.Context, email string) *protocol.MemoryUser {
  230. return h.validator.GetByEmail(email)
  231. }
  232. // GetUsers implements proxy.UserManager.GetUsers().
  233. func (h *Handler) GetUsers(ctx context.Context) []*protocol.MemoryUser {
  234. return h.validator.GetAll()
  235. }
  236. // GetUsersCount implements proxy.UserManager.GetUsersCount().
  237. func (h *Handler) GetUsersCount(context.Context) int64 {
  238. return h.validator.GetCount()
  239. }
  240. // Network implements proxy.Inbound.Network().
  241. func (*Handler) Network() []net.Network {
  242. return []net.Network{net.Network_TCP, net.Network_UNIX}
  243. }
  244. // Process implements proxy.Inbound.Process().
  245. func (h *Handler) Process(ctx context.Context, network net.Network, connection stat.Connection, dispatcher routing.Dispatcher) error {
  246. iConn := connection
  247. if statConn, ok := iConn.(*stat.CounterConnection); ok {
  248. iConn = statConn.Connection
  249. }
  250. if h.decryption != nil {
  251. var err error
  252. if connection, err = h.decryption.Handshake(connection, nil); err != nil {
  253. return errors.New("ML-KEM-768 handshake failed").Base(err).AtInfo()
  254. }
  255. }
  256. sessionPolicy := h.policyManager.ForLevel(0)
  257. if err := connection.SetReadDeadline(time.Now().Add(sessionPolicy.Timeouts.Handshake)); err != nil {
  258. return errors.New("unable to set read deadline").Base(err).AtWarning()
  259. }
  260. first := buf.FromBytes(make([]byte, buf.Size))
  261. first.Clear()
  262. firstLen, errR := first.ReadFrom(connection)
  263. if errR != nil {
  264. return errR
  265. }
  266. errors.LogInfo(ctx, "firstLen = ", firstLen)
  267. reader := &buf.BufferedReader{
  268. Reader: buf.NewReader(connection),
  269. Buffer: buf.MultiBuffer{first},
  270. }
  271. var userSentID []byte // not MemoryAccount.ID
  272. var request *protocol.RequestHeader
  273. var requestAddons *encoding.Addons
  274. var err error
  275. napfb := h.fallbacks
  276. isfb := napfb != nil
  277. if isfb && firstLen < 18 {
  278. err = errors.New("fallback directly")
  279. } else {
  280. userSentID, request, requestAddons, isfb, err = encoding.DecodeRequestHeader(isfb, first, reader, h.validator)
  281. }
  282. if err != nil {
  283. if isfb {
  284. if err := connection.SetReadDeadline(time.Time{}); err != nil {
  285. errors.LogWarningInner(ctx, err, "unable to set back read deadline")
  286. }
  287. errors.LogInfoInner(ctx, err, "fallback starts")
  288. name := ""
  289. alpn := ""
  290. if tlsConn, ok := iConn.(*tls.Conn); ok {
  291. cs := tlsConn.ConnectionState()
  292. name = cs.ServerName
  293. alpn = cs.NegotiatedProtocol
  294. errors.LogInfo(ctx, "realName = "+name)
  295. errors.LogInfo(ctx, "realAlpn = "+alpn)
  296. } else if realityConn, ok := iConn.(*reality.Conn); ok {
  297. cs := realityConn.ConnectionState()
  298. name = cs.ServerName
  299. alpn = cs.NegotiatedProtocol
  300. errors.LogInfo(ctx, "realName = "+name)
  301. errors.LogInfo(ctx, "realAlpn = "+alpn)
  302. }
  303. name = strings.ToLower(name)
  304. alpn = strings.ToLower(alpn)
  305. if len(napfb) > 1 || napfb[""] == nil {
  306. if name != "" && napfb[name] == nil {
  307. match := ""
  308. for n := range napfb {
  309. if n != "" && strings.Contains(name, n) && len(n) > len(match) {
  310. match = n
  311. }
  312. }
  313. name = match
  314. }
  315. }
  316. if napfb[name] == nil {
  317. name = ""
  318. }
  319. apfb := napfb[name]
  320. if apfb == nil {
  321. return errors.New(`failed to find the default "name" config`).AtWarning()
  322. }
  323. if apfb[alpn] == nil {
  324. alpn = ""
  325. }
  326. pfb := apfb[alpn]
  327. if pfb == nil {
  328. return errors.New(`failed to find the default "alpn" config`).AtWarning()
  329. }
  330. path := ""
  331. if len(pfb) > 1 || pfb[""] == nil {
  332. /*
  333. if lines := bytes.Split(firstBytes, []byte{'\r', '\n'}); len(lines) > 1 {
  334. if s := bytes.Split(lines[0], []byte{' '}); len(s) == 3 {
  335. if len(s[0]) < 8 && len(s[1]) > 0 && len(s[2]) == 8 {
  336. errors.New("realPath = " + string(s[1])).AtInfo().WriteToLog(sid)
  337. for _, fb := range pfb {
  338. if fb.Path != "" && h.regexps[fb.Path].Match(s[1]) {
  339. path = fb.Path
  340. break
  341. }
  342. }
  343. }
  344. }
  345. }
  346. */
  347. if firstLen >= 18 && first.Byte(4) != '*' { // not h2c
  348. firstBytes := first.Bytes()
  349. for i := 4; i <= 8; i++ { // 5 -> 9
  350. if firstBytes[i] == '/' && firstBytes[i-1] == ' ' {
  351. search := len(firstBytes)
  352. if search > 64 {
  353. search = 64 // up to about 60
  354. }
  355. for j := i + 1; j < search; j++ {
  356. k := firstBytes[j]
  357. if k == '\r' || k == '\n' { // avoid logging \r or \n
  358. break
  359. }
  360. if k == '?' || k == ' ' {
  361. path = string(firstBytes[i:j])
  362. errors.LogInfo(ctx, "realPath = "+path)
  363. if pfb[path] == nil {
  364. path = ""
  365. }
  366. break
  367. }
  368. }
  369. break
  370. }
  371. }
  372. }
  373. }
  374. fb := pfb[path]
  375. if fb == nil {
  376. return errors.New(`failed to find the default "path" config`).AtWarning()
  377. }
  378. ctx, cancel := context.WithCancel(ctx)
  379. timer := signal.CancelAfterInactivity(ctx, cancel, sessionPolicy.Timeouts.ConnectionIdle)
  380. ctx = policy.ContextWithBufferPolicy(ctx, sessionPolicy.Buffer)
  381. var conn net.Conn
  382. if err := retry.ExponentialBackoff(5, 100).On(func() error {
  383. var dialer net.Dialer
  384. conn, err = dialer.DialContext(ctx, fb.Type, fb.Dest)
  385. if err != nil {
  386. return err
  387. }
  388. return nil
  389. }); err != nil {
  390. return errors.New("failed to dial to " + fb.Dest).Base(err).AtWarning()
  391. }
  392. defer conn.Close()
  393. serverReader := buf.NewReader(conn)
  394. serverWriter := buf.NewWriter(conn)
  395. postRequest := func() error {
  396. defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
  397. if fb.Xver != 0 {
  398. ipType := 4
  399. remoteAddr, remotePort, err := net.SplitHostPort(connection.RemoteAddr().String())
  400. if err != nil {
  401. ipType = 0
  402. }
  403. localAddr, localPort, err := net.SplitHostPort(connection.LocalAddr().String())
  404. if err != nil {
  405. ipType = 0
  406. }
  407. if ipType == 4 {
  408. for i := 0; i < len(remoteAddr); i++ {
  409. if remoteAddr[i] == ':' {
  410. ipType = 6
  411. break
  412. }
  413. }
  414. }
  415. pro := buf.New()
  416. defer pro.Release()
  417. switch fb.Xver {
  418. case 1:
  419. if ipType == 0 {
  420. pro.Write([]byte("PROXY UNKNOWN\r\n"))
  421. break
  422. }
  423. if ipType == 4 {
  424. pro.Write([]byte("PROXY TCP4 " + remoteAddr + " " + localAddr + " " + remotePort + " " + localPort + "\r\n"))
  425. } else {
  426. pro.Write([]byte("PROXY TCP6 " + remoteAddr + " " + localAddr + " " + remotePort + " " + localPort + "\r\n"))
  427. }
  428. case 2:
  429. pro.Write([]byte("\x0D\x0A\x0D\x0A\x00\x0D\x0A\x51\x55\x49\x54\x0A")) // signature
  430. if ipType == 0 {
  431. pro.Write([]byte("\x20\x00\x00\x00")) // v2 + LOCAL + UNSPEC + UNSPEC + 0 bytes
  432. break
  433. }
  434. if ipType == 4 {
  435. pro.Write([]byte("\x21\x11\x00\x0C")) // v2 + PROXY + AF_INET + STREAM + 12 bytes
  436. pro.Write(net.ParseIP(remoteAddr).To4())
  437. pro.Write(net.ParseIP(localAddr).To4())
  438. } else {
  439. pro.Write([]byte("\x21\x21\x00\x24")) // v2 + PROXY + AF_INET6 + STREAM + 36 bytes
  440. pro.Write(net.ParseIP(remoteAddr).To16())
  441. pro.Write(net.ParseIP(localAddr).To16())
  442. }
  443. p1, _ := strconv.ParseUint(remotePort, 10, 16)
  444. p2, _ := strconv.ParseUint(localPort, 10, 16)
  445. pro.Write([]byte{byte(p1 >> 8), byte(p1), byte(p2 >> 8), byte(p2)})
  446. }
  447. if err := serverWriter.WriteMultiBuffer(buf.MultiBuffer{pro}); err != nil {
  448. return errors.New("failed to set PROXY protocol v", fb.Xver).Base(err).AtWarning()
  449. }
  450. }
  451. if err := buf.Copy(reader, serverWriter, buf.UpdateActivity(timer)); err != nil {
  452. return errors.New("failed to fallback request payload").Base(err).AtInfo()
  453. }
  454. return nil
  455. }
  456. writer := buf.NewWriter(connection)
  457. getResponse := func() error {
  458. defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
  459. if err := buf.Copy(serverReader, writer, buf.UpdateActivity(timer)); err != nil {
  460. return errors.New("failed to deliver response payload").Base(err).AtInfo()
  461. }
  462. return nil
  463. }
  464. if err := task.Run(ctx, task.OnSuccess(postRequest, task.Close(serverWriter)), task.OnSuccess(getResponse, task.Close(writer))); err != nil {
  465. common.Interrupt(serverReader)
  466. common.Interrupt(serverWriter)
  467. return errors.New("fallback ends").Base(err).AtInfo()
  468. }
  469. return nil
  470. }
  471. if errors.Cause(err) != io.EOF {
  472. log.Record(&log.AccessMessage{
  473. From: connection.RemoteAddr(),
  474. To: "",
  475. Status: log.AccessRejected,
  476. Reason: err,
  477. })
  478. err = errors.New("invalid request from ", connection.RemoteAddr()).Base(err).AtInfo()
  479. }
  480. return err
  481. }
  482. if err := connection.SetReadDeadline(time.Time{}); err != nil {
  483. errors.LogWarningInner(ctx, err, "unable to set back read deadline")
  484. }
  485. errors.LogInfo(ctx, "received request for ", request.Destination())
  486. inbound := session.InboundFromContext(ctx)
  487. if inbound == nil {
  488. panic("no inbound metadata")
  489. }
  490. inbound.Name = "vless"
  491. inbound.User = request.User
  492. inbound.VlessRoute = net.PortFromBytes(userSentID[6:8])
  493. account := request.User.Account.(*vless.MemoryAccount)
  494. responseAddons := &encoding.Addons{
  495. // Flow: requestAddons.Flow,
  496. }
  497. var input *bytes.Reader
  498. var rawInput *bytes.Buffer
  499. switch requestAddons.Flow {
  500. case vless.XRV:
  501. if account.Flow == requestAddons.Flow {
  502. inbound.CanSpliceCopy = 2
  503. switch request.Command {
  504. case protocol.RequestCommandUDP:
  505. return errors.New(requestAddons.Flow + " doesn't support UDP").AtWarning()
  506. case protocol.RequestCommandMux, protocol.RequestCommandRvs:
  507. inbound.CanSpliceCopy = 3
  508. fallthrough // we will break Mux connections that contain TCP requests
  509. case protocol.RequestCommandTCP:
  510. var t reflect.Type
  511. var p uintptr
  512. if commonConn, ok := connection.(*encryption.CommonConn); ok {
  513. if _, ok := commonConn.Conn.(*encryption.XorConn); ok || !proxy.IsRAWTransportWithoutSecurity(iConn) {
  514. inbound.CanSpliceCopy = 3 // full-random xorConn / non-RAW transport / another securityConn should not be penetrated
  515. }
  516. t = reflect.TypeOf(commonConn).Elem()
  517. p = uintptr(unsafe.Pointer(commonConn))
  518. } else if tlsConn, ok := iConn.(*tls.Conn); ok {
  519. if tlsConn.ConnectionState().Version != gotls.VersionTLS13 {
  520. return errors.New(`failed to use `+requestAddons.Flow+`, found outer tls version `, tlsConn.ConnectionState().Version).AtWarning()
  521. }
  522. t = reflect.TypeOf(tlsConn.Conn).Elem()
  523. p = uintptr(unsafe.Pointer(tlsConn.Conn))
  524. } else if realityConn, ok := iConn.(*reality.Conn); ok {
  525. t = reflect.TypeOf(realityConn.Conn).Elem()
  526. p = uintptr(unsafe.Pointer(realityConn.Conn))
  527. } else {
  528. return errors.New("XTLS only supports TLS and REALITY directly for now.").AtWarning()
  529. }
  530. i, _ := t.FieldByName("input")
  531. r, _ := t.FieldByName("rawInput")
  532. input = (*bytes.Reader)(unsafe.Pointer(p + i.Offset))
  533. rawInput = (*bytes.Buffer)(unsafe.Pointer(p + r.Offset))
  534. }
  535. } else {
  536. return errors.New("account " + account.ID.String() + " is not able to use the flow " + requestAddons.Flow).AtWarning()
  537. }
  538. case "":
  539. inbound.CanSpliceCopy = 3
  540. if account.Flow == vless.XRV && (request.Command == protocol.RequestCommandTCP || isMuxAndNotXUDP(request, first)) {
  541. return errors.New("account " + account.ID.String() + " is rejected since the client flow is empty. Note that the pure TLS proxy has certain TLS in TLS characters.").AtWarning()
  542. }
  543. default:
  544. return errors.New("unknown request flow " + requestAddons.Flow).AtWarning()
  545. }
  546. if request.Command != protocol.RequestCommandMux {
  547. ctx = log.ContextWithAccessMessage(ctx, &log.AccessMessage{
  548. From: connection.RemoteAddr(),
  549. To: request.Destination(),
  550. Status: log.AccessAccepted,
  551. Reason: "",
  552. Email: request.User.Email,
  553. })
  554. } else if account.Flow == vless.XRV {
  555. ctx = session.ContextWithAllowedNetwork(ctx, net.Network_UDP)
  556. }
  557. trafficState := proxy.NewTrafficState(userSentID)
  558. clientReader := encoding.DecodeBodyAddons(reader, request, requestAddons)
  559. if requestAddons.Flow == vless.XRV {
  560. clientReader = proxy.NewVisionReader(clientReader, trafficState, true, ctx, connection, input, rawInput, nil)
  561. }
  562. bufferWriter := buf.NewBufferedWriter(buf.NewWriter(connection))
  563. if err := encoding.EncodeResponseHeader(bufferWriter, request, responseAddons); err != nil {
  564. return errors.New("failed to encode response header").Base(err).AtWarning()
  565. }
  566. clientWriter := encoding.EncodeBodyAddons(bufferWriter, request, requestAddons, trafficState, false, ctx, connection, nil)
  567. bufferWriter.SetFlushNext()
  568. if request.Command == protocol.RequestCommandRvs {
  569. r, err := h.GetReverse(account)
  570. if err != nil {
  571. return err
  572. }
  573. if h.wrapLink == nil {
  574. return errors.New("VLESS reverse must have a dispatcher that implemented routing.WrapLinkDispatcher")
  575. }
  576. return r.NewMux(ctx, h.wrapLink(ctx, &transport.Link{Reader: clientReader, Writer: clientWriter}))
  577. }
  578. if err := dispatcher.DispatchLink(ctx, request.Destination(), &transport.Link{
  579. Reader: clientReader,
  580. Writer: clientWriter},
  581. ); err != nil {
  582. return errors.New("failed to dispatch request").Base(err)
  583. }
  584. return nil
  585. }
  586. type Reverse struct {
  587. tag string
  588. picker *reverse.StaticMuxPicker
  589. client *mux.ClientManager
  590. }
  591. func (r *Reverse) Tag() string {
  592. return r.tag
  593. }
  594. func (r *Reverse) NewMux(ctx context.Context, link *transport.Link) error {
  595. muxClient, err := mux.NewClientWorker(*link, mux.ClientStrategy{})
  596. if err != nil {
  597. return errors.New("failed to create mux client worker").Base(err).AtWarning()
  598. }
  599. worker, err := reverse.NewPortalWorker(muxClient)
  600. if err != nil {
  601. return errors.New("failed to create portal worker").Base(err).AtWarning()
  602. }
  603. r.picker.AddWorker(worker)
  604. select {
  605. case <-ctx.Done():
  606. case <-muxClient.WaitClosed():
  607. }
  608. return nil
  609. }
  610. func (r *Reverse) Dispatch(ctx context.Context, link *transport.Link) {
  611. outbounds := session.OutboundsFromContext(ctx)
  612. ob := outbounds[len(outbounds)-1]
  613. if ob != nil {
  614. if ob.Target.Network == net.Network_UDP && ob.OriginalTarget.Address != nil && ob.OriginalTarget.Address != ob.Target.Address {
  615. link.Reader = &buf.EndpointOverrideReader{Reader: link.Reader, Dest: ob.Target.Address, OriginalDest: ob.OriginalTarget.Address}
  616. link.Writer = &buf.EndpointOverrideWriter{Writer: link.Writer, Dest: ob.Target.Address, OriginalDest: ob.OriginalTarget.Address}
  617. }
  618. r.client.Dispatch(session.ContextWithIsReverseMux(ctx, true), link)
  619. }
  620. }
  621. func (r *Reverse) Start() error {
  622. return nil
  623. }
  624. func (r *Reverse) Close() error {
  625. return nil
  626. }
  627. func (r *Reverse) SenderSettings() *serial.TypedMessage {
  628. return nil
  629. }
  630. func (r *Reverse) ProxySettings() *serial.TypedMessage {
  631. return nil
  632. }