inbound.go 22 KB

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