inbound.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  1. package inbound
  2. //go:generate go run github.com/xtls/xray-core/common/errors/errorgen
  3. import (
  4. "context"
  5. "io"
  6. "strconv"
  7. "strings"
  8. "syscall"
  9. "time"
  10. "github.com/xtls/xray-core/common"
  11. "github.com/xtls/xray-core/common/buf"
  12. "github.com/xtls/xray-core/common/errors"
  13. "github.com/xtls/xray-core/common/log"
  14. "github.com/xtls/xray-core/common/net"
  15. "github.com/xtls/xray-core/common/platform"
  16. "github.com/xtls/xray-core/common/protocol"
  17. "github.com/xtls/xray-core/common/retry"
  18. "github.com/xtls/xray-core/common/session"
  19. "github.com/xtls/xray-core/common/signal"
  20. "github.com/xtls/xray-core/common/task"
  21. core "github.com/xtls/xray-core/core"
  22. "github.com/xtls/xray-core/features/dns"
  23. feature_inbound "github.com/xtls/xray-core/features/inbound"
  24. "github.com/xtls/xray-core/features/policy"
  25. "github.com/xtls/xray-core/features/routing"
  26. "github.com/xtls/xray-core/features/stats"
  27. "github.com/xtls/xray-core/proxy/vless"
  28. "github.com/xtls/xray-core/proxy/vless/encoding"
  29. "github.com/xtls/xray-core/transport/internet"
  30. "github.com/xtls/xray-core/transport/internet/tls"
  31. "github.com/xtls/xray-core/transport/internet/xtls"
  32. )
  33. var (
  34. xtls_show = false
  35. )
  36. func init() {
  37. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  38. var dc dns.Client
  39. if err := core.RequireFeatures(ctx, func(d dns.Client) error {
  40. dc = d
  41. return nil
  42. }); err != nil {
  43. return nil, err
  44. }
  45. return New(ctx, config.(*Config), dc)
  46. }))
  47. const defaultFlagValue = "NOT_DEFINED_AT_ALL"
  48. xtlsShow := platform.NewEnvFlag("xray.vless.xtls.show").GetValue(func() string { return defaultFlagValue })
  49. if xtlsShow == "true" {
  50. xtls_show = true
  51. }
  52. }
  53. // Handler is an inbound connection handler that handles messages in VLess protocol.
  54. type Handler struct {
  55. inboundHandlerManager feature_inbound.Manager
  56. policyManager policy.Manager
  57. validator *vless.Validator
  58. dns dns.Client
  59. fallbacks map[string]map[string]map[string]*Fallback // or nil
  60. // regexps map[string]*regexp.Regexp // or nil
  61. }
  62. // New creates a new VLess inbound handler.
  63. func New(ctx context.Context, config *Config, dc dns.Client) (*Handler, error) {
  64. v := core.MustFromContext(ctx)
  65. handler := &Handler{
  66. inboundHandlerManager: v.GetFeature(feature_inbound.ManagerType()).(feature_inbound.Manager),
  67. policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
  68. validator: new(vless.Validator),
  69. dns: dc,
  70. }
  71. for _, user := range config.Clients {
  72. u, err := user.ToMemoryUser()
  73. if err != nil {
  74. return nil, newError("failed to get VLESS user").Base(err).AtError()
  75. }
  76. if err := handler.AddUser(ctx, u); err != nil {
  77. return nil, newError("failed to initiate user").Base(err).AtError()
  78. }
  79. }
  80. if config.Fallbacks != nil {
  81. handler.fallbacks = make(map[string]map[string]map[string]*Fallback)
  82. // handler.regexps = make(map[string]*regexp.Regexp)
  83. for _, fb := range config.Fallbacks {
  84. if handler.fallbacks[fb.Name] == nil {
  85. handler.fallbacks[fb.Name] = make(map[string]map[string]*Fallback)
  86. }
  87. if handler.fallbacks[fb.Name][fb.Alpn] == nil {
  88. handler.fallbacks[fb.Name][fb.Alpn] = make(map[string]*Fallback)
  89. }
  90. handler.fallbacks[fb.Name][fb.Alpn][fb.Path] = fb
  91. /*
  92. if fb.Path != "" {
  93. if r, err := regexp.Compile(fb.Path); err != nil {
  94. return nil, newError("invalid path regexp").Base(err).AtError()
  95. } else {
  96. handler.regexps[fb.Path] = r
  97. }
  98. }
  99. */
  100. }
  101. if handler.fallbacks[""] != nil {
  102. for name, apfb := range handler.fallbacks {
  103. if name != "" {
  104. for alpn := range handler.fallbacks[""] {
  105. if apfb[alpn] == nil {
  106. apfb[alpn] = make(map[string]*Fallback)
  107. }
  108. }
  109. }
  110. }
  111. }
  112. for _, apfb := range handler.fallbacks {
  113. if apfb[""] != nil {
  114. for alpn, pfb := range apfb {
  115. if alpn != "" { // && alpn != "h2" {
  116. for path, fb := range apfb[""] {
  117. if pfb[path] == nil {
  118. pfb[path] = fb
  119. }
  120. }
  121. }
  122. }
  123. }
  124. }
  125. if handler.fallbacks[""] != nil {
  126. for name, apfb := range handler.fallbacks {
  127. if name != "" {
  128. for alpn, pfb := range handler.fallbacks[""] {
  129. for path, fb := range pfb {
  130. if apfb[alpn][path] == nil {
  131. apfb[alpn][path] = fb
  132. }
  133. }
  134. }
  135. }
  136. }
  137. }
  138. }
  139. return handler, nil
  140. }
  141. // Close implements common.Closable.Close().
  142. func (h *Handler) Close() error {
  143. return errors.Combine(common.Close(h.validator))
  144. }
  145. // AddUser implements proxy.UserManager.AddUser().
  146. func (h *Handler) AddUser(ctx context.Context, u *protocol.MemoryUser) error {
  147. return h.validator.Add(u)
  148. }
  149. // RemoveUser implements proxy.UserManager.RemoveUser().
  150. func (h *Handler) RemoveUser(ctx context.Context, e string) error {
  151. return h.validator.Del(e)
  152. }
  153. // Network implements proxy.Inbound.Network().
  154. func (*Handler) Network() []net.Network {
  155. return []net.Network{net.Network_TCP, net.Network_UNIX}
  156. }
  157. // Process implements proxy.Inbound.Process().
  158. func (h *Handler) Process(ctx context.Context, network net.Network, connection internet.Connection, dispatcher routing.Dispatcher) error {
  159. sid := session.ExportIDToError(ctx)
  160. iConn := connection
  161. statConn, ok := iConn.(*internet.StatCouterConnection)
  162. if ok {
  163. iConn = statConn.Connection
  164. }
  165. sessionPolicy := h.policyManager.ForLevel(0)
  166. if err := connection.SetReadDeadline(time.Now().Add(sessionPolicy.Timeouts.Handshake)); err != nil {
  167. return newError("unable to set read deadline").Base(err).AtWarning()
  168. }
  169. first := buf.New()
  170. defer first.Release()
  171. firstLen, _ := first.ReadFrom(connection)
  172. newError("firstLen = ", firstLen).AtInfo().WriteToLog(sid)
  173. reader := &buf.BufferedReader{
  174. Reader: buf.NewReader(connection),
  175. Buffer: buf.MultiBuffer{first},
  176. }
  177. var request *protocol.RequestHeader
  178. var requestAddons *encoding.Addons
  179. var err error
  180. napfb := h.fallbacks
  181. isfb := napfb != nil
  182. if isfb && firstLen < 18 {
  183. err = newError("fallback directly")
  184. } else {
  185. request, requestAddons, isfb, err = encoding.DecodeRequestHeader(isfb, first, reader, h.validator)
  186. }
  187. if err != nil {
  188. if isfb {
  189. if err := connection.SetReadDeadline(time.Time{}); err != nil {
  190. newError("unable to set back read deadline").Base(err).AtWarning().WriteToLog(sid)
  191. }
  192. newError("fallback starts").Base(err).AtInfo().WriteToLog(sid)
  193. name := ""
  194. alpn := ""
  195. if tlsConn, ok := iConn.(*tls.Conn); ok {
  196. cs := tlsConn.ConnectionState()
  197. name = cs.ServerName
  198. alpn = cs.NegotiatedProtocol
  199. newError("realName = " + name).AtInfo().WriteToLog(sid)
  200. newError("realAlpn = " + alpn).AtInfo().WriteToLog(sid)
  201. } else if xtlsConn, ok := iConn.(*xtls.Conn); ok {
  202. cs := xtlsConn.ConnectionState()
  203. name = cs.ServerName
  204. alpn = cs.NegotiatedProtocol
  205. newError("realName = " + name).AtInfo().WriteToLog(sid)
  206. newError("realAlpn = " + alpn).AtInfo().WriteToLog(sid)
  207. }
  208. name = strings.ToLower(name)
  209. alpn = strings.ToLower(alpn)
  210. if len(napfb) > 1 || napfb[""] == nil {
  211. if name != "" && napfb[name] == nil {
  212. match := ""
  213. for n := range napfb {
  214. if n != "" && strings.Contains(name, n) && len(n) > len(match) {
  215. match = n
  216. }
  217. }
  218. name = match
  219. }
  220. }
  221. if napfb[name] == nil {
  222. name = ""
  223. }
  224. apfb := napfb[name]
  225. if apfb == nil {
  226. return newError(`failed to find the default "name" config`).AtWarning()
  227. }
  228. if apfb[alpn] == nil {
  229. alpn = ""
  230. }
  231. pfb := apfb[alpn]
  232. if pfb == nil {
  233. return newError(`failed to find the default "alpn" config`).AtWarning()
  234. }
  235. path := ""
  236. if len(pfb) > 1 || pfb[""] == nil {
  237. /*
  238. if lines := bytes.Split(firstBytes, []byte{'\r', '\n'}); len(lines) > 1 {
  239. if s := bytes.Split(lines[0], []byte{' '}); len(s) == 3 {
  240. if len(s[0]) < 8 && len(s[1]) > 0 && len(s[2]) == 8 {
  241. newError("realPath = " + string(s[1])).AtInfo().WriteToLog(sid)
  242. for _, fb := range pfb {
  243. if fb.Path != "" && h.regexps[fb.Path].Match(s[1]) {
  244. path = fb.Path
  245. break
  246. }
  247. }
  248. }
  249. }
  250. }
  251. */
  252. if firstLen >= 18 && first.Byte(4) != '*' { // not h2c
  253. firstBytes := first.Bytes()
  254. for i := 4; i <= 8; i++ { // 5 -> 9
  255. if firstBytes[i] == '/' && firstBytes[i-1] == ' ' {
  256. search := len(firstBytes)
  257. if search > 64 {
  258. search = 64 // up to about 60
  259. }
  260. for j := i + 1; j < search; j++ {
  261. k := firstBytes[j]
  262. if k == '\r' || k == '\n' { // avoid logging \r or \n
  263. break
  264. }
  265. if k == '?' || k == ' ' {
  266. path = string(firstBytes[i:j])
  267. newError("realPath = " + path).AtInfo().WriteToLog(sid)
  268. if pfb[path] == nil {
  269. path = ""
  270. }
  271. break
  272. }
  273. }
  274. break
  275. }
  276. }
  277. }
  278. }
  279. fb := pfb[path]
  280. if fb == nil {
  281. return newError(`failed to find the default "path" config`).AtWarning()
  282. }
  283. ctx, cancel := context.WithCancel(ctx)
  284. timer := signal.CancelAfterInactivity(ctx, cancel, sessionPolicy.Timeouts.ConnectionIdle)
  285. ctx = policy.ContextWithBufferPolicy(ctx, sessionPolicy.Buffer)
  286. var conn net.Conn
  287. if err := retry.ExponentialBackoff(5, 100).On(func() error {
  288. var dialer net.Dialer
  289. conn, err = dialer.DialContext(ctx, fb.Type, fb.Dest)
  290. if err != nil {
  291. return err
  292. }
  293. return nil
  294. }); err != nil {
  295. return newError("failed to dial to " + fb.Dest).Base(err).AtWarning()
  296. }
  297. defer conn.Close()
  298. serverReader := buf.NewReader(conn)
  299. serverWriter := buf.NewWriter(conn)
  300. postRequest := func() error {
  301. defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
  302. if fb.Xver != 0 {
  303. ipType := 4
  304. remoteAddr, remotePort, err := net.SplitHostPort(connection.RemoteAddr().String())
  305. if err != nil {
  306. ipType = 0
  307. }
  308. localAddr, localPort, err := net.SplitHostPort(connection.LocalAddr().String())
  309. if err != nil {
  310. ipType = 0
  311. }
  312. if ipType == 4 {
  313. for i := 0; i < len(remoteAddr); i++ {
  314. if remoteAddr[i] == ':' {
  315. ipType = 6
  316. break
  317. }
  318. }
  319. }
  320. pro := buf.New()
  321. defer pro.Release()
  322. switch fb.Xver {
  323. case 1:
  324. if ipType == 0 {
  325. pro.Write([]byte("PROXY UNKNOWN\r\n"))
  326. break
  327. }
  328. if ipType == 4 {
  329. pro.Write([]byte("PROXY TCP4 " + remoteAddr + " " + localAddr + " " + remotePort + " " + localPort + "\r\n"))
  330. } else {
  331. pro.Write([]byte("PROXY TCP6 " + remoteAddr + " " + localAddr + " " + remotePort + " " + localPort + "\r\n"))
  332. }
  333. case 2:
  334. pro.Write([]byte("\x0D\x0A\x0D\x0A\x00\x0D\x0A\x51\x55\x49\x54\x0A")) // signature
  335. if ipType == 0 {
  336. pro.Write([]byte("\x20\x00\x00\x00")) // v2 + LOCAL + UNSPEC + UNSPEC + 0 bytes
  337. break
  338. }
  339. if ipType == 4 {
  340. pro.Write([]byte("\x21\x11\x00\x0C")) // v2 + PROXY + AF_INET + STREAM + 12 bytes
  341. pro.Write(net.ParseIP(remoteAddr).To4())
  342. pro.Write(net.ParseIP(localAddr).To4())
  343. } else {
  344. pro.Write([]byte("\x21\x21\x00\x24")) // v2 + PROXY + AF_INET6 + STREAM + 36 bytes
  345. pro.Write(net.ParseIP(remoteAddr).To16())
  346. pro.Write(net.ParseIP(localAddr).To16())
  347. }
  348. p1, _ := strconv.ParseUint(remotePort, 10, 16)
  349. p2, _ := strconv.ParseUint(localPort, 10, 16)
  350. pro.Write([]byte{byte(p1 >> 8), byte(p1), byte(p2 >> 8), byte(p2)})
  351. }
  352. if err := serverWriter.WriteMultiBuffer(buf.MultiBuffer{pro}); err != nil {
  353. return newError("failed to set PROXY protocol v", fb.Xver).Base(err).AtWarning()
  354. }
  355. }
  356. if err := buf.Copy(reader, serverWriter, buf.UpdateActivity(timer)); err != nil {
  357. return newError("failed to fallback request payload").Base(err).AtInfo()
  358. }
  359. return nil
  360. }
  361. writer := buf.NewWriter(connection)
  362. getResponse := func() error {
  363. defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
  364. if err := buf.Copy(serverReader, writer, buf.UpdateActivity(timer)); err != nil {
  365. return newError("failed to deliver response payload").Base(err).AtInfo()
  366. }
  367. return nil
  368. }
  369. if err := task.Run(ctx, task.OnSuccess(postRequest, task.Close(serverWriter)), task.OnSuccess(getResponse, task.Close(writer))); err != nil {
  370. common.Interrupt(serverReader)
  371. common.Interrupt(serverWriter)
  372. return newError("fallback ends").Base(err).AtInfo()
  373. }
  374. return nil
  375. }
  376. if errors.Cause(err) != io.EOF {
  377. log.Record(&log.AccessMessage{
  378. From: connection.RemoteAddr(),
  379. To: "",
  380. Status: log.AccessRejected,
  381. Reason: err,
  382. })
  383. err = newError("invalid request from ", connection.RemoteAddr()).Base(err).AtInfo()
  384. }
  385. return err
  386. }
  387. if err := connection.SetReadDeadline(time.Time{}); err != nil {
  388. newError("unable to set back read deadline").Base(err).AtWarning().WriteToLog(sid)
  389. }
  390. newError("received request for ", request.Destination()).AtInfo().WriteToLog(sid)
  391. inbound := session.InboundFromContext(ctx)
  392. if inbound == nil {
  393. panic("no inbound metadata")
  394. }
  395. inbound.User = request.User
  396. account := request.User.Account.(*vless.MemoryAccount)
  397. responseAddons := &encoding.Addons{
  398. // Flow: requestAddons.Flow,
  399. }
  400. var rawConn syscall.RawConn
  401. switch requestAddons.Flow {
  402. case vless.XRO, vless.XRD:
  403. if account.Flow == requestAddons.Flow {
  404. switch request.Command {
  405. case protocol.RequestCommandMux:
  406. return newError(requestAddons.Flow + " doesn't support Mux").AtWarning()
  407. case protocol.RequestCommandUDP:
  408. return newError(requestAddons.Flow + " doesn't support UDP").AtWarning()
  409. case protocol.RequestCommandTCP:
  410. if xtlsConn, ok := iConn.(*xtls.Conn); ok {
  411. xtlsConn.RPRX = true
  412. xtlsConn.SHOW = xtls_show
  413. xtlsConn.MARK = "XTLS"
  414. if requestAddons.Flow == vless.XRD {
  415. xtlsConn.DirectMode = true
  416. if sc, ok := xtlsConn.Connection.(syscall.Conn); ok {
  417. rawConn, _ = sc.SyscallConn()
  418. }
  419. }
  420. } else {
  421. return newError(`failed to use ` + requestAddons.Flow + `, maybe "security" is not "xtls"`).AtWarning()
  422. }
  423. }
  424. } else {
  425. return newError(account.ID.String() + " is not able to use " + requestAddons.Flow).AtWarning()
  426. }
  427. case "":
  428. default:
  429. return newError("unknown request flow " + requestAddons.Flow).AtWarning()
  430. }
  431. if request.Command != protocol.RequestCommandMux {
  432. ctx = log.ContextWithAccessMessage(ctx, &log.AccessMessage{
  433. From: connection.RemoteAddr(),
  434. To: request.Destination(),
  435. Status: log.AccessAccepted,
  436. Reason: "",
  437. Email: request.User.Email,
  438. })
  439. }
  440. sessionPolicy = h.policyManager.ForLevel(request.User.Level)
  441. ctx, cancel := context.WithCancel(ctx)
  442. timer := signal.CancelAfterInactivity(ctx, cancel, sessionPolicy.Timeouts.ConnectionIdle)
  443. ctx = policy.ContextWithBufferPolicy(ctx, sessionPolicy.Buffer)
  444. link, err := dispatcher.Dispatch(ctx, request.Destination())
  445. if err != nil {
  446. return newError("failed to dispatch request to ", request.Destination()).Base(err).AtWarning()
  447. }
  448. serverReader := link.Reader // .(*pipe.Reader)
  449. serverWriter := link.Writer // .(*pipe.Writer)
  450. postRequest := func() error {
  451. defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
  452. // default: clientReader := reader
  453. clientReader := encoding.DecodeBodyAddons(reader, request, requestAddons)
  454. var err error
  455. if rawConn != nil {
  456. var counter stats.Counter
  457. if statConn != nil {
  458. counter = statConn.ReadCounter
  459. }
  460. err = encoding.ReadV(clientReader, serverWriter, timer, iConn.(*xtls.Conn), rawConn, counter, nil)
  461. } else {
  462. // from clientReader.ReadMultiBuffer to serverWriter.WriteMultiBufer
  463. err = buf.Copy(clientReader, serverWriter, buf.UpdateActivity(timer))
  464. }
  465. if err != nil {
  466. return newError("failed to transfer request payload").Base(err).AtInfo()
  467. }
  468. return nil
  469. }
  470. getResponse := func() error {
  471. defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
  472. bufferWriter := buf.NewBufferedWriter(buf.NewWriter(connection))
  473. if err := encoding.EncodeResponseHeader(bufferWriter, request, responseAddons); err != nil {
  474. return newError("failed to encode response header").Base(err).AtWarning()
  475. }
  476. // default: clientWriter := bufferWriter
  477. clientWriter := encoding.EncodeBodyAddons(bufferWriter, request, responseAddons)
  478. {
  479. multiBuffer, err := serverReader.ReadMultiBuffer()
  480. if err != nil {
  481. return err // ...
  482. }
  483. if err := clientWriter.WriteMultiBuffer(multiBuffer); err != nil {
  484. return err // ...
  485. }
  486. }
  487. // Flush; bufferWriter.WriteMultiBufer now is bufferWriter.writer.WriteMultiBuffer
  488. if err := bufferWriter.SetBuffered(false); err != nil {
  489. return newError("failed to write A response payload").Base(err).AtWarning()
  490. }
  491. // from serverReader.ReadMultiBuffer to clientWriter.WriteMultiBufer
  492. if err := buf.Copy(serverReader, clientWriter, buf.UpdateActivity(timer)); err != nil {
  493. return newError("failed to transfer response payload").Base(err).AtInfo()
  494. }
  495. // Indicates the end of response payload.
  496. switch responseAddons.Flow {
  497. default:
  498. }
  499. return nil
  500. }
  501. if err := task.Run(ctx, task.OnSuccess(postRequest, task.Close(serverWriter)), getResponse); err != nil {
  502. common.Interrupt(serverReader)
  503. common.Interrupt(serverWriter)
  504. return newError("connection ends").Base(err).AtInfo()
  505. }
  506. return nil
  507. }