route.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803
  1. package route
  2. import (
  3. "context"
  4. "errors"
  5. "net"
  6. "net/netip"
  7. "strings"
  8. "time"
  9. "github.com/sagernet/sing-box/adapter"
  10. "github.com/sagernet/sing-box/common/sniff"
  11. C "github.com/sagernet/sing-box/constant"
  12. R "github.com/sagernet/sing-box/route/rule"
  13. "github.com/sagernet/sing-mux"
  14. "github.com/sagernet/sing-tun"
  15. "github.com/sagernet/sing-tun/ping"
  16. "github.com/sagernet/sing-vmess"
  17. "github.com/sagernet/sing/common"
  18. "github.com/sagernet/sing/common/buf"
  19. "github.com/sagernet/sing/common/bufio"
  20. "github.com/sagernet/sing/common/bufio/deadline"
  21. E "github.com/sagernet/sing/common/exceptions"
  22. F "github.com/sagernet/sing/common/format"
  23. M "github.com/sagernet/sing/common/metadata"
  24. N "github.com/sagernet/sing/common/network"
  25. "github.com/sagernet/sing/common/uot"
  26. "golang.org/x/exp/slices"
  27. )
  28. // Deprecated: use RouteConnectionEx instead.
  29. func (r *Router) RouteConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error {
  30. done := make(chan interface{})
  31. err := r.routeConnection(ctx, conn, metadata, N.OnceClose(func(it error) {
  32. close(done)
  33. }))
  34. if err != nil {
  35. return err
  36. }
  37. select {
  38. case <-done:
  39. case <-r.ctx.Done():
  40. }
  41. return nil
  42. }
  43. func (r *Router) RouteConnectionEx(ctx context.Context, conn net.Conn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) {
  44. err := r.routeConnection(ctx, conn, metadata, onClose)
  45. if err != nil {
  46. N.CloseOnHandshakeFailure(conn, onClose, err)
  47. if E.IsClosedOrCanceled(err) || R.IsRejected(err) {
  48. r.logger.DebugContext(ctx, "connection closed: ", err)
  49. } else {
  50. r.logger.ErrorContext(ctx, err)
  51. }
  52. }
  53. }
  54. func (r *Router) routeConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) error {
  55. //nolint:staticcheck
  56. if metadata.InboundDetour != "" {
  57. if metadata.LastInbound == metadata.InboundDetour {
  58. return E.New("routing loop on detour: ", metadata.InboundDetour)
  59. }
  60. detour, loaded := r.inbound.Get(metadata.InboundDetour)
  61. if !loaded {
  62. return E.New("inbound detour not found: ", metadata.InboundDetour)
  63. }
  64. injectable, isInjectable := detour.(adapter.TCPInjectableInbound)
  65. if !isInjectable {
  66. return E.New("inbound detour is not TCP injectable: ", metadata.InboundDetour)
  67. }
  68. metadata.LastInbound = metadata.Inbound
  69. metadata.Inbound = metadata.InboundDetour
  70. metadata.InboundDetour = ""
  71. injectable.NewConnectionEx(ctx, conn, metadata, onClose)
  72. return nil
  73. }
  74. metadata.Network = N.NetworkTCP
  75. switch metadata.Destination.Fqdn {
  76. case mux.Destination.Fqdn:
  77. return E.New("global multiplex is deprecated since sing-box v1.7.0, enable multiplex in Inbound fields instead.")
  78. case vmess.MuxDestination.Fqdn:
  79. return E.New("global multiplex (v2ray legacy) not supported since sing-box v1.7.0.")
  80. case uot.MagicAddress:
  81. return E.New("global UoT not supported since sing-box v1.7.0.")
  82. case uot.LegacyMagicAddress:
  83. return E.New("global UoT (legacy) not supported since sing-box v1.7.0.")
  84. }
  85. if deadline.NeedAdditionalReadDeadline(conn) {
  86. conn = deadline.NewConn(conn)
  87. }
  88. selectedRule, _, buffers, _, err := r.matchRule(ctx, &metadata, false, false, conn, nil)
  89. if err != nil {
  90. return err
  91. }
  92. var selectedOutbound adapter.Outbound
  93. if selectedRule != nil {
  94. switch action := selectedRule.Action().(type) {
  95. case *R.RuleActionRoute:
  96. var loaded bool
  97. selectedOutbound, loaded = r.outbound.Outbound(action.Outbound)
  98. if !loaded {
  99. buf.ReleaseMulti(buffers)
  100. return E.New("outbound not found: ", action.Outbound)
  101. }
  102. if !common.Contains(selectedOutbound.Network(), N.NetworkTCP) {
  103. buf.ReleaseMulti(buffers)
  104. return E.New("TCP is not supported by outbound: ", selectedOutbound.Tag())
  105. }
  106. case *R.RuleActionBypass:
  107. if action.Outbound == "" {
  108. break
  109. }
  110. var loaded bool
  111. selectedOutbound, loaded = r.outbound.Outbound(action.Outbound)
  112. if !loaded {
  113. buf.ReleaseMulti(buffers)
  114. return E.New("outbound not found: ", action.Outbound)
  115. }
  116. if !common.Contains(selectedOutbound.Network(), N.NetworkTCP) {
  117. buf.ReleaseMulti(buffers)
  118. return E.New("TCP is not supported by outbound: ", selectedOutbound.Tag())
  119. }
  120. case *R.RuleActionReject:
  121. buf.ReleaseMulti(buffers)
  122. if action.Method == C.RuleActionRejectMethodReply {
  123. return E.New("reject method `reply` is not supported for TCP connections")
  124. }
  125. return action.Error(ctx)
  126. case *R.RuleActionHijackDNS:
  127. for _, buffer := range buffers {
  128. conn = bufio.NewCachedConn(conn, buffer)
  129. }
  130. N.CloseOnHandshakeFailure(conn, onClose, r.hijackDNSStream(ctx, conn, metadata))
  131. return nil
  132. }
  133. }
  134. if selectedRule == nil {
  135. defaultOutbound := r.outbound.Default()
  136. if !common.Contains(defaultOutbound.Network(), N.NetworkTCP) {
  137. buf.ReleaseMulti(buffers)
  138. return E.New("TCP is not supported by default outbound: ", defaultOutbound.Tag())
  139. }
  140. selectedOutbound = defaultOutbound
  141. }
  142. for _, buffer := range buffers {
  143. conn = bufio.NewCachedConn(conn, buffer)
  144. }
  145. for _, tracker := range r.trackers {
  146. conn = tracker.RoutedConnection(ctx, conn, metadata, selectedRule, selectedOutbound)
  147. }
  148. if outboundHandler, isHandler := selectedOutbound.(adapter.ConnectionHandlerEx); isHandler {
  149. outboundHandler.NewConnectionEx(ctx, conn, metadata, onClose)
  150. } else {
  151. r.connection.NewConnection(ctx, selectedOutbound, conn, metadata, onClose)
  152. }
  153. return nil
  154. }
  155. func (r *Router) RoutePacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error {
  156. done := make(chan interface{})
  157. err := r.routePacketConnection(ctx, conn, metadata, N.OnceClose(func(it error) {
  158. close(done)
  159. }))
  160. if err != nil {
  161. conn.Close()
  162. if E.IsClosedOrCanceled(err) || R.IsRejected(err) {
  163. r.logger.DebugContext(ctx, "connection closed: ", err)
  164. } else {
  165. r.logger.ErrorContext(ctx, err)
  166. }
  167. }
  168. select {
  169. case <-done:
  170. case <-r.ctx.Done():
  171. }
  172. return nil
  173. }
  174. func (r *Router) RoutePacketConnectionEx(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) {
  175. err := r.routePacketConnection(ctx, conn, metadata, onClose)
  176. if err != nil {
  177. N.CloseOnHandshakeFailure(conn, onClose, err)
  178. if E.IsClosedOrCanceled(err) || R.IsRejected(err) {
  179. r.logger.DebugContext(ctx, "connection closed: ", err)
  180. } else {
  181. r.logger.ErrorContext(ctx, err)
  182. }
  183. }
  184. }
  185. func (r *Router) routePacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) error {
  186. //nolint:staticcheck
  187. if metadata.InboundDetour != "" {
  188. if metadata.LastInbound == metadata.InboundDetour {
  189. return E.New("routing loop on detour: ", metadata.InboundDetour)
  190. }
  191. detour, loaded := r.inbound.Get(metadata.InboundDetour)
  192. if !loaded {
  193. return E.New("inbound detour not found: ", metadata.InboundDetour)
  194. }
  195. injectable, isInjectable := detour.(adapter.UDPInjectableInbound)
  196. if !isInjectable {
  197. return E.New("inbound detour is not UDP injectable: ", metadata.InboundDetour)
  198. }
  199. metadata.LastInbound = metadata.Inbound
  200. metadata.Inbound = metadata.InboundDetour
  201. metadata.InboundDetour = ""
  202. injectable.NewPacketConnectionEx(ctx, conn, metadata, onClose)
  203. return nil
  204. }
  205. // TODO: move to UoT
  206. metadata.Network = N.NetworkUDP
  207. // Currently we don't have deadline usages for UDP connections
  208. /*if deadline.NeedAdditionalReadDeadline(conn) {
  209. conn = deadline.NewPacketConn(bufio.NewNetPacketConn(conn))
  210. }*/
  211. selectedRule, _, _, packetBuffers, err := r.matchRule(ctx, &metadata, false, false, nil, conn)
  212. if err != nil {
  213. return err
  214. }
  215. var selectedOutbound adapter.Outbound
  216. var selectReturn bool
  217. if selectedRule != nil {
  218. switch action := selectedRule.Action().(type) {
  219. case *R.RuleActionRoute:
  220. var loaded bool
  221. selectedOutbound, loaded = r.outbound.Outbound(action.Outbound)
  222. if !loaded {
  223. N.ReleaseMultiPacketBuffer(packetBuffers)
  224. return E.New("outbound not found: ", action.Outbound)
  225. }
  226. if !common.Contains(selectedOutbound.Network(), N.NetworkUDP) {
  227. N.ReleaseMultiPacketBuffer(packetBuffers)
  228. return E.New("UDP is not supported by outbound: ", selectedOutbound.Tag())
  229. }
  230. case *R.RuleActionBypass:
  231. if action.Outbound == "" {
  232. break
  233. }
  234. var loaded bool
  235. selectedOutbound, loaded = r.outbound.Outbound(action.Outbound)
  236. if !loaded {
  237. N.ReleaseMultiPacketBuffer(packetBuffers)
  238. return E.New("outbound not found: ", action.Outbound)
  239. }
  240. if !common.Contains(selectedOutbound.Network(), N.NetworkUDP) {
  241. N.ReleaseMultiPacketBuffer(packetBuffers)
  242. return E.New("UDP is not supported by outbound: ", selectedOutbound.Tag())
  243. }
  244. case *R.RuleActionReject:
  245. N.ReleaseMultiPacketBuffer(packetBuffers)
  246. if action.Method == C.RuleActionRejectMethodReply {
  247. return E.New("reject method `reply` is not supported for UDP connections")
  248. }
  249. return action.Error(ctx)
  250. case *R.RuleActionHijackDNS:
  251. return r.hijackDNSPacket(ctx, conn, packetBuffers, metadata, onClose)
  252. }
  253. }
  254. if selectedRule == nil || selectReturn {
  255. defaultOutbound := r.outbound.Default()
  256. if !common.Contains(defaultOutbound.Network(), N.NetworkUDP) {
  257. N.ReleaseMultiPacketBuffer(packetBuffers)
  258. return E.New("UDP is not supported by outbound: ", defaultOutbound.Tag())
  259. }
  260. selectedOutbound = defaultOutbound
  261. }
  262. for _, buffer := range packetBuffers {
  263. conn = bufio.NewCachedPacketConn(conn, buffer.Buffer, buffer.Destination)
  264. N.PutPacketBuffer(buffer)
  265. }
  266. for _, tracker := range r.trackers {
  267. conn = tracker.RoutedPacketConnection(ctx, conn, metadata, selectedRule, selectedOutbound)
  268. }
  269. if metadata.FakeIP {
  270. conn = bufio.NewNATPacketConn(bufio.NewNetPacketConn(conn), metadata.OriginDestination, metadata.Destination)
  271. }
  272. if outboundHandler, isHandler := selectedOutbound.(adapter.PacketConnectionHandlerEx); isHandler {
  273. outboundHandler.NewPacketConnectionEx(ctx, conn, metadata, onClose)
  274. } else {
  275. r.connection.NewPacketConnection(ctx, selectedOutbound, conn, metadata, onClose)
  276. }
  277. return nil
  278. }
  279. func (r *Router) PreMatch(metadata adapter.InboundContext, routeContext tun.DirectRouteContext, timeout time.Duration, supportBypass bool) (tun.DirectRouteDestination, error) {
  280. selectedRule, _, _, _, err := r.matchRule(r.ctx, &metadata, true, supportBypass, nil, nil)
  281. if err != nil {
  282. return nil, err
  283. }
  284. var directRouteOutbound adapter.DirectRouteOutbound
  285. if selectedRule != nil {
  286. switch action := selectedRule.Action().(type) {
  287. case *R.RuleActionReject:
  288. switch metadata.Network {
  289. case N.NetworkTCP:
  290. if action.Method == C.RuleActionRejectMethodReply {
  291. return nil, E.New("reject method `reply` is not supported for TCP connections")
  292. }
  293. case N.NetworkUDP:
  294. if action.Method == C.RuleActionRejectMethodReply {
  295. return nil, E.New("reject method `reply` is not supported for UDP connections")
  296. }
  297. }
  298. return nil, action.Error(context.Background())
  299. case *R.RuleActionBypass:
  300. if supportBypass {
  301. return nil, &R.BypassedError{Cause: tun.ErrBypass}
  302. }
  303. if routeContext == nil {
  304. return nil, nil
  305. }
  306. outbound, loaded := r.outbound.Outbound(action.Outbound)
  307. if !loaded {
  308. return nil, E.New("outbound not found: ", action.Outbound)
  309. }
  310. if !common.Contains(outbound.Network(), metadata.Network) {
  311. return nil, E.New(metadata.Network, " is not supported by outbound: ", action.Outbound)
  312. }
  313. directRouteOutbound = outbound.(adapter.DirectRouteOutbound)
  314. case *R.RuleActionRoute:
  315. if routeContext == nil {
  316. return nil, nil
  317. }
  318. outbound, loaded := r.outbound.Outbound(action.Outbound)
  319. if !loaded {
  320. return nil, E.New("outbound not found: ", action.Outbound)
  321. }
  322. if !common.Contains(outbound.Network(), metadata.Network) {
  323. return nil, E.New(metadata.Network, " is not supported by outbound: ", action.Outbound)
  324. }
  325. directRouteOutbound = outbound.(adapter.DirectRouteOutbound)
  326. }
  327. }
  328. if directRouteOutbound == nil {
  329. if selectedRule != nil || metadata.Network != N.NetworkICMP {
  330. return nil, nil
  331. }
  332. defaultOutbound := r.outbound.Default()
  333. if !common.Contains(defaultOutbound.Network(), metadata.Network) {
  334. return nil, E.New(metadata.Network, " is not supported by default outbound: ", defaultOutbound.Tag())
  335. }
  336. directRouteOutbound = defaultOutbound.(adapter.DirectRouteOutbound)
  337. }
  338. if metadata.Destination.IsDomain() {
  339. if len(metadata.DestinationAddresses) == 0 {
  340. var strategy C.DomainStrategy
  341. if metadata.Source.IsIPv4() {
  342. strategy = C.DomainStrategyIPv4Only
  343. } else {
  344. strategy = C.DomainStrategyIPv6Only
  345. }
  346. err = r.actionResolve(r.ctx, &metadata, &R.RuleActionResolve{
  347. Strategy: strategy,
  348. })
  349. if err != nil {
  350. return nil, err
  351. }
  352. }
  353. var newDestination netip.Addr
  354. if metadata.Source.IsIPv4() {
  355. for _, address := range metadata.DestinationAddresses {
  356. if address.Is4() {
  357. newDestination = address
  358. break
  359. }
  360. }
  361. } else {
  362. for _, address := range metadata.DestinationAddresses {
  363. if address.Is6() {
  364. newDestination = address
  365. break
  366. }
  367. }
  368. }
  369. if !newDestination.IsValid() {
  370. if metadata.Source.IsIPv4() {
  371. return nil, E.New("no IPv4 address found for domain: ", metadata.Destination.Fqdn)
  372. } else {
  373. return nil, E.New("no IPv6 address found for domain: ", metadata.Destination.Fqdn)
  374. }
  375. }
  376. metadata.Destination = M.Socksaddr{
  377. Addr: newDestination,
  378. }
  379. routeContext = ping.NewContextDestinationWriter(routeContext, metadata.OriginDestination.Addr)
  380. var routeDestination tun.DirectRouteDestination
  381. routeDestination, err = directRouteOutbound.NewDirectRouteConnection(metadata, routeContext, timeout)
  382. if err != nil {
  383. return nil, err
  384. }
  385. return ping.NewDestinationWriter(routeDestination, newDestination), nil
  386. }
  387. return directRouteOutbound.NewDirectRouteConnection(metadata, routeContext, timeout)
  388. }
  389. func (r *Router) matchRule(
  390. ctx context.Context, metadata *adapter.InboundContext, preMatch bool, supportBypass bool,
  391. inputConn net.Conn, inputPacketConn N.PacketConn,
  392. ) (
  393. selectedRule adapter.Rule, selectedRuleIndex int,
  394. buffers []*buf.Buffer, packetBuffers []*N.PacketBuffer, fatalErr error,
  395. ) {
  396. r.searchProcessInfo(ctx, metadata)
  397. if r.neighborResolver != nil && metadata.SourceMACAddress == nil && metadata.Source.Addr.IsValid() {
  398. mac, macFound := r.neighborResolver.LookupMAC(metadata.Source.Addr)
  399. if macFound {
  400. metadata.SourceMACAddress = mac
  401. }
  402. hostname, hostnameFound := r.neighborResolver.LookupHostname(metadata.Source.Addr)
  403. if hostnameFound {
  404. metadata.SourceHostname = hostname
  405. if macFound {
  406. r.logger.InfoContext(ctx, "found neighbor: ", mac, ", hostname: ", hostname)
  407. } else {
  408. r.logger.InfoContext(ctx, "found neighbor hostname: ", hostname)
  409. }
  410. } else if macFound {
  411. r.logger.InfoContext(ctx, "found neighbor: ", mac)
  412. }
  413. }
  414. if metadata.Destination.Addr.IsValid() && r.dnsTransport.FakeIP() != nil && r.dnsTransport.FakeIP().Store().Contains(metadata.Destination.Addr) {
  415. domain, loaded := r.dnsTransport.FakeIP().Store().Lookup(metadata.Destination.Addr)
  416. if !loaded {
  417. fatalErr = E.New("missing fakeip record, try enable `experimental.cache_file`")
  418. return
  419. }
  420. if domain != "" {
  421. metadata.OriginDestination = metadata.Destination
  422. metadata.Destination = M.Socksaddr{
  423. Fqdn: domain,
  424. Port: metadata.Destination.Port,
  425. }
  426. metadata.FakeIP = true
  427. r.logger.DebugContext(ctx, "found fakeip domain: ", domain)
  428. }
  429. } else if metadata.Domain == "" {
  430. domain, loaded := r.dns.LookupReverseMapping(metadata.Destination.Addr)
  431. if loaded {
  432. metadata.Domain = domain
  433. r.logger.DebugContext(ctx, "found reserve mapped domain: ", metadata.Domain)
  434. }
  435. }
  436. if metadata.Destination.IsIPv4() {
  437. metadata.IPVersion = 4
  438. } else if metadata.Destination.IsIPv6() {
  439. metadata.IPVersion = 6
  440. }
  441. match:
  442. for currentRuleIndex, currentRule := range r.rules {
  443. metadata.ResetRuleCache()
  444. if !currentRule.Match(metadata) {
  445. continue
  446. }
  447. if !preMatch {
  448. ruleDescription := currentRule.String()
  449. if ruleDescription != "" {
  450. r.logger.DebugContext(ctx, "match[", currentRuleIndex, "] ", currentRule, " => ", currentRule.Action())
  451. } else {
  452. r.logger.DebugContext(ctx, "match[", currentRuleIndex, "] => ", currentRule.Action())
  453. }
  454. } else {
  455. switch currentRule.Action().Type() {
  456. case C.RuleActionTypeReject:
  457. ruleDescription := currentRule.String()
  458. if ruleDescription != "" {
  459. r.logger.DebugContext(ctx, "pre-match[", currentRuleIndex, "] ", currentRule, " => ", currentRule.Action())
  460. } else {
  461. r.logger.DebugContext(ctx, "pre-match[", currentRuleIndex, "] => ", currentRule.Action())
  462. }
  463. }
  464. }
  465. var routeOptions *R.RuleActionRouteOptions
  466. switch action := currentRule.Action().(type) {
  467. case *R.RuleActionRoute:
  468. routeOptions = &action.RuleActionRouteOptions
  469. case *R.RuleActionRouteOptions:
  470. routeOptions = action
  471. }
  472. if routeOptions != nil {
  473. // TODO: add nat
  474. if (routeOptions.OverrideAddress.IsValid() || routeOptions.OverridePort > 0) && !metadata.RouteOriginalDestination.IsValid() {
  475. metadata.RouteOriginalDestination = metadata.Destination
  476. }
  477. if routeOptions.OverrideAddress.IsValid() {
  478. metadata.Destination = M.Socksaddr{
  479. Addr: routeOptions.OverrideAddress.Addr,
  480. Port: metadata.Destination.Port,
  481. Fqdn: routeOptions.OverrideAddress.Fqdn,
  482. }
  483. metadata.DestinationAddresses = nil
  484. }
  485. if routeOptions.OverridePort > 0 {
  486. metadata.Destination = M.Socksaddr{
  487. Addr: metadata.Destination.Addr,
  488. Port: routeOptions.OverridePort,
  489. Fqdn: metadata.Destination.Fqdn,
  490. }
  491. }
  492. if routeOptions.NetworkStrategy != nil {
  493. metadata.NetworkStrategy = routeOptions.NetworkStrategy
  494. }
  495. if len(routeOptions.NetworkType) > 0 {
  496. metadata.NetworkType = routeOptions.NetworkType
  497. }
  498. if len(routeOptions.FallbackNetworkType) > 0 {
  499. metadata.FallbackNetworkType = routeOptions.FallbackNetworkType
  500. }
  501. if routeOptions.FallbackDelay != 0 {
  502. metadata.FallbackDelay = routeOptions.FallbackDelay
  503. }
  504. if routeOptions.UDPDisableDomainUnmapping {
  505. metadata.UDPDisableDomainUnmapping = true
  506. }
  507. if routeOptions.UDPConnect {
  508. metadata.UDPConnect = true
  509. }
  510. if routeOptions.UDPTimeout > 0 {
  511. metadata.UDPTimeout = routeOptions.UDPTimeout
  512. }
  513. if routeOptions.TLSFragment {
  514. metadata.TLSFragment = true
  515. metadata.TLSFragmentFallbackDelay = routeOptions.TLSFragmentFallbackDelay
  516. }
  517. if routeOptions.TLSRecordFragment {
  518. metadata.TLSRecordFragment = true
  519. }
  520. }
  521. switch action := currentRule.Action().(type) {
  522. case *R.RuleActionSniff:
  523. if !preMatch {
  524. newBuffer, newPacketBuffers, newErr := r.actionSniff(ctx, metadata, action, inputConn, inputPacketConn, buffers, packetBuffers)
  525. if newBuffer != nil {
  526. buffers = append(buffers, newBuffer)
  527. } else if len(newPacketBuffers) > 0 {
  528. packetBuffers = append(packetBuffers, newPacketBuffers...)
  529. }
  530. if newErr != nil {
  531. fatalErr = newErr
  532. return
  533. }
  534. } else if metadata.Network != N.NetworkICMP {
  535. selectedRule = currentRule
  536. selectedRuleIndex = currentRuleIndex
  537. break match
  538. }
  539. case *R.RuleActionResolve:
  540. fatalErr = r.actionResolve(ctx, metadata, action)
  541. if fatalErr != nil {
  542. return
  543. }
  544. }
  545. actionType := currentRule.Action().Type()
  546. if actionType == C.RuleActionTypeRoute ||
  547. actionType == C.RuleActionTypeReject ||
  548. actionType == C.RuleActionTypeHijackDNS {
  549. selectedRule = currentRule
  550. selectedRuleIndex = currentRuleIndex
  551. break match
  552. }
  553. if actionType == C.RuleActionTypeBypass {
  554. bypassAction := currentRule.Action().(*R.RuleActionBypass)
  555. if !supportBypass && bypassAction.Outbound == "" {
  556. continue match
  557. }
  558. selectedRule = currentRule
  559. selectedRuleIndex = currentRuleIndex
  560. break match
  561. }
  562. }
  563. return
  564. }
  565. func (r *Router) actionSniff(
  566. ctx context.Context, metadata *adapter.InboundContext, action *R.RuleActionSniff,
  567. inputConn net.Conn, inputPacketConn N.PacketConn, inputBuffers []*buf.Buffer, inputPacketBuffers []*N.PacketBuffer,
  568. ) (buffer *buf.Buffer, packetBuffers []*N.PacketBuffer, fatalErr error) {
  569. if sniff.Skip(metadata) {
  570. r.logger.DebugContext(ctx, "sniff skipped due to port considered as server-first")
  571. return
  572. } else if metadata.Protocol != "" {
  573. r.logger.DebugContext(ctx, "duplicate sniff skipped")
  574. return
  575. }
  576. if inputConn != nil {
  577. if len(action.StreamSniffers) == 0 && len(action.PacketSniffers) > 0 {
  578. return
  579. } else if slices.Equal(metadata.SnifferNames, action.SnifferNames) && metadata.SniffError != nil && !errors.Is(metadata.SniffError, sniff.ErrNeedMoreData) {
  580. r.logger.DebugContext(ctx, "packet sniff skipped due to previous error: ", metadata.SniffError)
  581. return
  582. }
  583. var streamSniffers []sniff.StreamSniffer
  584. if len(action.StreamSniffers) > 0 {
  585. streamSniffers = action.StreamSniffers
  586. } else {
  587. streamSniffers = []sniff.StreamSniffer{
  588. sniff.TLSClientHello,
  589. sniff.HTTPHost,
  590. sniff.StreamDomainNameQuery,
  591. sniff.BitTorrent,
  592. sniff.SSH,
  593. sniff.RDP,
  594. }
  595. }
  596. sniffBuffer := buf.NewPacket()
  597. err := sniff.PeekStream(
  598. ctx,
  599. metadata,
  600. inputConn,
  601. inputBuffers,
  602. sniffBuffer,
  603. action.Timeout,
  604. streamSniffers...,
  605. )
  606. metadata.SnifferNames = action.SnifferNames
  607. metadata.SniffError = err
  608. if err == nil {
  609. //goland:noinspection GoDeprecation
  610. if action.OverrideDestination && M.IsDomainName(metadata.Domain) {
  611. metadata.Destination = M.Socksaddr{
  612. Fqdn: metadata.Domain,
  613. Port: metadata.Destination.Port,
  614. }
  615. }
  616. if metadata.Domain != "" && metadata.Client != "" {
  617. r.logger.DebugContext(ctx, "sniffed protocol: ", metadata.Protocol, ", domain: ", metadata.Domain, ", client: ", metadata.Client)
  618. } else if metadata.Domain != "" {
  619. r.logger.DebugContext(ctx, "sniffed protocol: ", metadata.Protocol, ", domain: ", metadata.Domain)
  620. } else {
  621. r.logger.DebugContext(ctx, "sniffed protocol: ", metadata.Protocol)
  622. }
  623. }
  624. if !sniffBuffer.IsEmpty() {
  625. buffer = sniffBuffer
  626. } else {
  627. sniffBuffer.Release()
  628. }
  629. } else if inputPacketConn != nil {
  630. if len(action.PacketSniffers) == 0 && len(action.StreamSniffers) > 0 {
  631. return
  632. } else if slices.Equal(metadata.SnifferNames, action.SnifferNames) && metadata.SniffError != nil && !errors.Is(metadata.SniffError, sniff.ErrNeedMoreData) {
  633. r.logger.DebugContext(ctx, "packet sniff skipped due to previous error: ", metadata.SniffError)
  634. return
  635. }
  636. quicMoreData := func() bool {
  637. return slices.Equal(metadata.SnifferNames, action.SnifferNames) && errors.Is(metadata.SniffError, sniff.ErrNeedMoreData)
  638. }
  639. var packetSniffers []sniff.PacketSniffer
  640. if len(action.PacketSniffers) > 0 {
  641. packetSniffers = action.PacketSniffers
  642. } else {
  643. packetSniffers = []sniff.PacketSniffer{
  644. sniff.DomainNameQuery,
  645. sniff.QUICClientHello,
  646. sniff.STUNMessage,
  647. sniff.UTP,
  648. sniff.UDPTracker,
  649. sniff.DTLSRecord,
  650. sniff.NTP,
  651. }
  652. }
  653. var err error
  654. for _, packetBuffer := range inputPacketBuffers {
  655. if quicMoreData() {
  656. err = sniff.PeekPacket(
  657. ctx,
  658. metadata,
  659. packetBuffer.Buffer.Bytes(),
  660. sniff.QUICClientHello,
  661. )
  662. } else {
  663. err = sniff.PeekPacket(
  664. ctx, metadata,
  665. packetBuffer.Buffer.Bytes(),
  666. packetSniffers...,
  667. )
  668. }
  669. metadata.SnifferNames = action.SnifferNames
  670. metadata.SniffError = err
  671. if errors.Is(err, sniff.ErrNeedMoreData) {
  672. // TODO: replace with generic message when there are more multi-packet protocols
  673. r.logger.DebugContext(ctx, "attempt to sniff fragmented QUIC client hello")
  674. continue
  675. }
  676. goto finally
  677. }
  678. packetBuffers = inputPacketBuffers
  679. for {
  680. var (
  681. sniffBuffer = buf.NewPacket()
  682. destination M.Socksaddr
  683. done = make(chan struct{})
  684. )
  685. go func() {
  686. sniffTimeout := C.ReadPayloadTimeout
  687. if action.Timeout > 0 {
  688. sniffTimeout = action.Timeout
  689. }
  690. inputPacketConn.SetReadDeadline(time.Now().Add(sniffTimeout))
  691. destination, err = inputPacketConn.ReadPacket(sniffBuffer)
  692. inputPacketConn.SetReadDeadline(time.Time{})
  693. close(done)
  694. }()
  695. select {
  696. case <-done:
  697. case <-ctx.Done():
  698. inputPacketConn.Close()
  699. fatalErr = ctx.Err()
  700. return
  701. }
  702. if err != nil {
  703. sniffBuffer.Release()
  704. if !errors.Is(err, context.DeadlineExceeded) {
  705. fatalErr = err
  706. return
  707. }
  708. } else {
  709. if quicMoreData() {
  710. err = sniff.PeekPacket(
  711. ctx,
  712. metadata,
  713. sniffBuffer.Bytes(),
  714. sniff.QUICClientHello,
  715. )
  716. } else {
  717. err = sniff.PeekPacket(
  718. ctx, metadata,
  719. sniffBuffer.Bytes(),
  720. packetSniffers...,
  721. )
  722. }
  723. packetBuffer := N.NewPacketBuffer()
  724. *packetBuffer = N.PacketBuffer{
  725. Buffer: sniffBuffer,
  726. Destination: destination,
  727. }
  728. packetBuffers = append(packetBuffers, packetBuffer)
  729. metadata.SnifferNames = action.SnifferNames
  730. metadata.SniffError = err
  731. if errors.Is(err, sniff.ErrNeedMoreData) {
  732. // TODO: replace with generic message when there are more multi-packet protocols
  733. r.logger.DebugContext(ctx, "attempt to sniff fragmented QUIC client hello")
  734. continue
  735. }
  736. }
  737. goto finally
  738. }
  739. finally:
  740. if err == nil {
  741. //goland:noinspection GoDeprecation
  742. if action.OverrideDestination && M.IsDomainName(metadata.Domain) {
  743. metadata.Destination = M.Socksaddr{
  744. Fqdn: metadata.Domain,
  745. Port: metadata.Destination.Port,
  746. }
  747. }
  748. if metadata.Domain != "" && metadata.Client != "" {
  749. r.logger.DebugContext(ctx, "sniffed packet protocol: ", metadata.Protocol, ", domain: ", metadata.Domain, ", client: ", metadata.Client)
  750. } else if metadata.Domain != "" {
  751. r.logger.DebugContext(ctx, "sniffed packet protocol: ", metadata.Protocol, ", domain: ", metadata.Domain)
  752. } else if metadata.Client != "" {
  753. r.logger.DebugContext(ctx, "sniffed packet protocol: ", metadata.Protocol, ", client: ", metadata.Client)
  754. } else {
  755. r.logger.DebugContext(ctx, "sniffed packet protocol: ", metadata.Protocol)
  756. }
  757. }
  758. }
  759. return
  760. }
  761. func (r *Router) actionResolve(ctx context.Context, metadata *adapter.InboundContext, action *R.RuleActionResolve) error {
  762. if metadata.Destination.IsDomain() {
  763. var transport adapter.DNSTransport
  764. if action.Server != "" {
  765. var loaded bool
  766. transport, loaded = r.dnsTransport.Transport(action.Server)
  767. if !loaded {
  768. return E.New("DNS server not found: ", action.Server)
  769. }
  770. }
  771. addresses, err := r.dns.Lookup(adapter.WithContext(ctx, metadata), metadata.Destination.Fqdn, adapter.DNSQueryOptions{
  772. Transport: transport,
  773. Strategy: action.Strategy,
  774. DisableCache: action.DisableCache,
  775. DisableOptimisticCache: action.DisableOptimisticCache,
  776. RewriteTTL: action.RewriteTTL,
  777. ClientSubnet: action.ClientSubnet,
  778. })
  779. if err != nil {
  780. return err
  781. }
  782. metadata.DestinationAddresses = addresses
  783. r.logger.DebugContext(ctx, "resolved [", strings.Join(F.MapToString(metadata.DestinationAddresses), " "), "]")
  784. }
  785. return nil
  786. }