route.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  1. package route
  2. import (
  3. "context"
  4. "errors"
  5. "net"
  6. "net/netip"
  7. "os"
  8. "os/user"
  9. "strings"
  10. "time"
  11. "github.com/sagernet/sing-box/adapter"
  12. "github.com/sagernet/sing-box/common/conntrack"
  13. "github.com/sagernet/sing-box/common/process"
  14. "github.com/sagernet/sing-box/common/sniff"
  15. C "github.com/sagernet/sing-box/constant"
  16. "github.com/sagernet/sing-box/option"
  17. "github.com/sagernet/sing-box/route/rule"
  18. "github.com/sagernet/sing-dns"
  19. "github.com/sagernet/sing-mux"
  20. "github.com/sagernet/sing-vmess"
  21. "github.com/sagernet/sing/common"
  22. "github.com/sagernet/sing/common/buf"
  23. "github.com/sagernet/sing/common/bufio"
  24. "github.com/sagernet/sing/common/bufio/deadline"
  25. E "github.com/sagernet/sing/common/exceptions"
  26. F "github.com/sagernet/sing/common/format"
  27. M "github.com/sagernet/sing/common/metadata"
  28. N "github.com/sagernet/sing/common/network"
  29. "github.com/sagernet/sing/common/uot"
  30. )
  31. // Deprecated: use RouteConnectionEx instead.
  32. func (r *Router) RouteConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error {
  33. return r.routeConnection(ctx, conn, metadata, nil)
  34. }
  35. func (r *Router) RouteConnectionEx(ctx context.Context, conn net.Conn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) {
  36. err := r.routeConnection(ctx, conn, metadata, onClose)
  37. if err != nil {
  38. N.CloseOnHandshakeFailure(conn, onClose, err)
  39. if E.IsClosedOrCanceled(err) {
  40. r.logger.DebugContext(ctx, "connection closed: ", err)
  41. } else {
  42. r.logger.ErrorContext(ctx, err)
  43. }
  44. }
  45. }
  46. func (r *Router) routeConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) error {
  47. if r.pauseManager.IsDevicePaused() {
  48. return E.New("reject connection to ", metadata.Destination, " while device paused")
  49. }
  50. //nolint:staticcheck
  51. if metadata.InboundDetour != "" {
  52. if metadata.LastInbound == metadata.InboundDetour {
  53. return E.New("routing loop on detour: ", metadata.InboundDetour)
  54. }
  55. detour, loaded := r.inbound.Get(metadata.InboundDetour)
  56. if !loaded {
  57. return E.New("inbound detour not found: ", metadata.InboundDetour)
  58. }
  59. injectable, isInjectable := detour.(adapter.TCPInjectableInbound)
  60. if !isInjectable {
  61. return E.New("inbound detour is not TCP injectable: ", metadata.InboundDetour)
  62. }
  63. metadata.LastInbound = metadata.Inbound
  64. metadata.Inbound = metadata.InboundDetour
  65. metadata.InboundDetour = ""
  66. injectable.NewConnectionEx(ctx, conn, metadata, onClose)
  67. return nil
  68. }
  69. conntrack.KillerCheck()
  70. metadata.Network = N.NetworkTCP
  71. switch metadata.Destination.Fqdn {
  72. case mux.Destination.Fqdn:
  73. return E.New("global multiplex is deprecated since sing-box v1.7.0, enable multiplex in Inbound fields instead.")
  74. case vmess.MuxDestination.Fqdn:
  75. return E.New("global multiplex (v2ray legacy) not supported since sing-box v1.7.0.")
  76. case uot.MagicAddress:
  77. return E.New("global UoT not supported since sing-box v1.7.0.")
  78. case uot.LegacyMagicAddress:
  79. return E.New("global UoT (legacy) not supported since sing-box v1.7.0.")
  80. }
  81. if deadline.NeedAdditionalReadDeadline(conn) {
  82. conn = deadline.NewConn(conn)
  83. }
  84. selectedRule, _, buffers, _, err := r.matchRule(ctx, &metadata, false, conn, nil)
  85. if err != nil {
  86. return err
  87. }
  88. var selectedOutbound adapter.Outbound
  89. if selectedRule != nil {
  90. switch action := selectedRule.Action().(type) {
  91. case *rule.RuleActionRoute:
  92. var loaded bool
  93. selectedOutbound, loaded = r.outbound.Outbound(action.Outbound)
  94. if !loaded {
  95. buf.ReleaseMulti(buffers)
  96. return E.New("outbound not found: ", action.Outbound)
  97. }
  98. if !common.Contains(selectedOutbound.Network(), N.NetworkTCP) {
  99. buf.ReleaseMulti(buffers)
  100. return E.New("TCP is not supported by outbound: ", selectedOutbound.Tag())
  101. }
  102. case *rule.RuleActionReject:
  103. buf.ReleaseMulti(buffers)
  104. N.CloseOnHandshakeFailure(conn, onClose, action.Error(ctx))
  105. return nil
  106. case *rule.RuleActionHijackDNS:
  107. for _, buffer := range buffers {
  108. conn = bufio.NewCachedConn(conn, buffer)
  109. }
  110. r.hijackDNSStream(ctx, conn, metadata)
  111. return nil
  112. }
  113. }
  114. if selectedRule == nil {
  115. defaultOutbound := r.outbound.Default()
  116. if !common.Contains(defaultOutbound.Network(), N.NetworkTCP) {
  117. buf.ReleaseMulti(buffers)
  118. return E.New("TCP is not supported by default outbound: ", defaultOutbound.Tag())
  119. }
  120. selectedOutbound = defaultOutbound
  121. }
  122. for _, buffer := range buffers {
  123. conn = bufio.NewCachedConn(conn, buffer)
  124. }
  125. if r.tracker != nil {
  126. conn = r.tracker.RoutedConnection(ctx, conn, metadata, selectedRule, selectedOutbound)
  127. }
  128. if outboundHandler, isHandler := selectedOutbound.(adapter.ConnectionHandlerEx); isHandler {
  129. outboundHandler.NewConnectionEx(ctx, conn, metadata, onClose)
  130. } else {
  131. r.connection.NewConnection(ctx, selectedOutbound, conn, metadata, onClose)
  132. }
  133. return nil
  134. }
  135. func (r *Router) RoutePacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error {
  136. err := r.routePacketConnection(ctx, conn, metadata, nil)
  137. if err != nil {
  138. conn.Close()
  139. if E.IsClosedOrCanceled(err) {
  140. r.logger.DebugContext(ctx, "connection closed: ", err)
  141. } else {
  142. r.logger.ErrorContext(ctx, err)
  143. }
  144. }
  145. return nil
  146. }
  147. func (r *Router) RoutePacketConnectionEx(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) {
  148. err := r.routePacketConnection(ctx, conn, metadata, onClose)
  149. if err != nil {
  150. N.CloseOnHandshakeFailure(conn, onClose, err)
  151. if E.IsClosedOrCanceled(err) {
  152. r.logger.DebugContext(ctx, "connection closed: ", err)
  153. } else {
  154. r.logger.ErrorContext(ctx, err)
  155. }
  156. } else if onClose != nil {
  157. onClose(nil)
  158. }
  159. }
  160. func (r *Router) routePacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) error {
  161. if r.pauseManager.IsDevicePaused() {
  162. return E.New("reject packet connection to ", metadata.Destination, " while device paused")
  163. }
  164. //nolint:staticcheck
  165. if metadata.InboundDetour != "" {
  166. if metadata.LastInbound == metadata.InboundDetour {
  167. return E.New("routing loop on detour: ", metadata.InboundDetour)
  168. }
  169. detour, loaded := r.inbound.Get(metadata.InboundDetour)
  170. if !loaded {
  171. return E.New("inbound detour not found: ", metadata.InboundDetour)
  172. }
  173. injectable, isInjectable := detour.(adapter.UDPInjectableInbound)
  174. if !isInjectable {
  175. return E.New("inbound detour is not UDP injectable: ", metadata.InboundDetour)
  176. }
  177. metadata.LastInbound = metadata.Inbound
  178. metadata.Inbound = metadata.InboundDetour
  179. metadata.InboundDetour = ""
  180. injectable.NewPacketConnectionEx(ctx, conn, metadata, onClose)
  181. return nil
  182. }
  183. conntrack.KillerCheck()
  184. // TODO: move to UoT
  185. metadata.Network = N.NetworkUDP
  186. // Currently we don't have deadline usages for UDP connections
  187. /*if deadline.NeedAdditionalReadDeadline(conn) {
  188. conn = deadline.NewPacketConn(bufio.NewNetPacketConn(conn))
  189. }*/
  190. selectedRule, _, _, packetBuffers, err := r.matchRule(ctx, &metadata, false, nil, conn)
  191. if err != nil {
  192. return err
  193. }
  194. var selectedOutbound adapter.Outbound
  195. var selectReturn bool
  196. if selectedRule != nil {
  197. switch action := selectedRule.Action().(type) {
  198. case *rule.RuleActionRoute:
  199. var loaded bool
  200. selectedOutbound, loaded = r.outbound.Outbound(action.Outbound)
  201. if !loaded {
  202. N.ReleaseMultiPacketBuffer(packetBuffers)
  203. return E.New("outbound not found: ", action.Outbound)
  204. }
  205. if !common.Contains(selectedOutbound.Network(), N.NetworkUDP) {
  206. N.ReleaseMultiPacketBuffer(packetBuffers)
  207. return E.New("UDP is not supported by outbound: ", selectedOutbound.Tag())
  208. }
  209. case *rule.RuleActionReject:
  210. N.ReleaseMultiPacketBuffer(packetBuffers)
  211. N.CloseOnHandshakeFailure(conn, onClose, action.Error(ctx))
  212. return nil
  213. case *rule.RuleActionHijackDNS:
  214. r.hijackDNSPacket(ctx, conn, packetBuffers, metadata)
  215. return nil
  216. }
  217. }
  218. if selectedRule == nil || selectReturn {
  219. defaultOutbound := r.outbound.Default()
  220. if !common.Contains(defaultOutbound.Network(), N.NetworkUDP) {
  221. N.ReleaseMultiPacketBuffer(packetBuffers)
  222. return E.New("UDP is not supported by outbound: ", defaultOutbound.Tag())
  223. }
  224. selectedOutbound = defaultOutbound
  225. }
  226. for _, buffer := range packetBuffers {
  227. conn = bufio.NewCachedPacketConn(conn, buffer.Buffer, buffer.Destination)
  228. N.PutPacketBuffer(buffer)
  229. }
  230. if r.tracker != nil {
  231. conn = r.tracker.RoutedPacketConnection(ctx, conn, metadata, selectedRule, selectedOutbound)
  232. }
  233. if metadata.FakeIP {
  234. conn = bufio.NewNATPacketConn(bufio.NewNetPacketConn(conn), metadata.OriginDestination, metadata.Destination)
  235. }
  236. if outboundHandler, isHandler := selectedOutbound.(adapter.PacketConnectionHandlerEx); isHandler {
  237. outboundHandler.NewPacketConnectionEx(ctx, conn, metadata, onClose)
  238. } else {
  239. r.connection.NewPacketConnection(ctx, selectedOutbound, conn, metadata, onClose)
  240. }
  241. return nil
  242. }
  243. func (r *Router) PreMatch(metadata adapter.InboundContext) error {
  244. selectedRule, _, _, _, err := r.matchRule(r.ctx, &metadata, true, nil, nil)
  245. if err != nil {
  246. return err
  247. }
  248. if selectedRule == nil {
  249. return nil
  250. }
  251. rejectAction, isReject := selectedRule.Action().(*rule.RuleActionReject)
  252. if !isReject {
  253. return nil
  254. }
  255. return rejectAction.Error(context.Background())
  256. }
  257. func (r *Router) matchRule(
  258. ctx context.Context, metadata *adapter.InboundContext, preMatch bool,
  259. inputConn net.Conn, inputPacketConn N.PacketConn,
  260. ) (
  261. selectedRule adapter.Rule, selectedRuleIndex int,
  262. buffers []*buf.Buffer, packetBuffers []*N.PacketBuffer, fatalErr error,
  263. ) {
  264. if r.processSearcher != nil && metadata.ProcessInfo == nil {
  265. var originDestination netip.AddrPort
  266. if metadata.OriginDestination.IsValid() {
  267. originDestination = metadata.OriginDestination.AddrPort()
  268. } else if metadata.Destination.IsIP() {
  269. originDestination = metadata.Destination.AddrPort()
  270. }
  271. processInfo, fErr := process.FindProcessInfo(r.processSearcher, ctx, metadata.Network, metadata.Source.AddrPort(), originDestination)
  272. if fErr != nil {
  273. r.logger.InfoContext(ctx, "failed to search process: ", fErr)
  274. } else {
  275. if processInfo.ProcessPath != "" {
  276. r.logger.InfoContext(ctx, "found process path: ", processInfo.ProcessPath)
  277. } else if processInfo.PackageName != "" {
  278. r.logger.InfoContext(ctx, "found package name: ", processInfo.PackageName)
  279. } else if processInfo.UserId != -1 {
  280. if /*needUserName &&*/ true {
  281. osUser, _ := user.LookupId(F.ToString(processInfo.UserId))
  282. if osUser != nil {
  283. processInfo.User = osUser.Username
  284. }
  285. }
  286. if processInfo.User != "" {
  287. r.logger.InfoContext(ctx, "found user: ", processInfo.User)
  288. } else {
  289. r.logger.InfoContext(ctx, "found user id: ", processInfo.UserId)
  290. }
  291. }
  292. metadata.ProcessInfo = processInfo
  293. }
  294. }
  295. if r.fakeIPStore != nil && r.fakeIPStore.Contains(metadata.Destination.Addr) {
  296. domain, loaded := r.fakeIPStore.Lookup(metadata.Destination.Addr)
  297. if !loaded {
  298. fatalErr = E.New("missing fakeip record, try to configure experimental.cache_file")
  299. return
  300. }
  301. metadata.OriginDestination = metadata.Destination
  302. metadata.Destination = M.Socksaddr{
  303. Fqdn: domain,
  304. Port: metadata.Destination.Port,
  305. }
  306. metadata.FakeIP = true
  307. r.logger.DebugContext(ctx, "found fakeip domain: ", domain)
  308. }
  309. if r.dnsReverseMapping != nil && metadata.Domain == "" {
  310. domain, loaded := r.dnsReverseMapping.Query(metadata.Destination.Addr)
  311. if loaded {
  312. metadata.Domain = domain
  313. r.logger.DebugContext(ctx, "found reserve mapped domain: ", metadata.Domain)
  314. }
  315. }
  316. if metadata.Destination.IsIPv4() {
  317. metadata.IPVersion = 4
  318. } else if metadata.Destination.IsIPv6() {
  319. metadata.IPVersion = 6
  320. }
  321. //nolint:staticcheck
  322. if metadata.InboundOptions != common.DefaultValue[option.InboundOptions]() {
  323. if !preMatch && metadata.InboundOptions.SniffEnabled {
  324. newBuffer, newPackerBuffers, newErr := r.actionSniff(ctx, metadata, &rule.RuleActionSniff{
  325. OverrideDestination: metadata.InboundOptions.SniffOverrideDestination,
  326. Timeout: time.Duration(metadata.InboundOptions.SniffTimeout),
  327. }, inputConn, inputPacketConn)
  328. if newErr != nil {
  329. fatalErr = newErr
  330. return
  331. }
  332. if newBuffer != nil {
  333. buffers = []*buf.Buffer{newBuffer}
  334. } else if len(newPackerBuffers) > 0 {
  335. packetBuffers = newPackerBuffers
  336. }
  337. }
  338. if dns.DomainStrategy(metadata.InboundOptions.DomainStrategy) != dns.DomainStrategyAsIS {
  339. fatalErr = r.actionResolve(ctx, metadata, &rule.RuleActionResolve{
  340. Strategy: dns.DomainStrategy(metadata.InboundOptions.DomainStrategy),
  341. })
  342. if fatalErr != nil {
  343. return
  344. }
  345. }
  346. if metadata.InboundOptions.UDPDisableDomainUnmapping {
  347. metadata.UDPDisableDomainUnmapping = true
  348. }
  349. metadata.InboundOptions = option.InboundOptions{}
  350. }
  351. match:
  352. for currentRuleIndex, currentRule := range r.rules {
  353. metadata.ResetRuleCache()
  354. if !currentRule.Match(metadata) {
  355. continue
  356. }
  357. if !preMatch {
  358. ruleDescription := currentRule.String()
  359. if ruleDescription != "" {
  360. r.logger.DebugContext(ctx, "match[", currentRuleIndex, "] ", currentRule, " => ", currentRule.Action())
  361. } else {
  362. r.logger.DebugContext(ctx, "match[", currentRuleIndex, "] => ", currentRule.Action())
  363. }
  364. } else {
  365. switch currentRule.Action().Type() {
  366. case C.RuleActionTypeReject:
  367. ruleDescription := currentRule.String()
  368. if ruleDescription != "" {
  369. r.logger.DebugContext(ctx, "pre-match[", currentRuleIndex, "] ", currentRule, " => ", currentRule.Action())
  370. } else {
  371. r.logger.DebugContext(ctx, "pre-match[", currentRuleIndex, "] => ", currentRule.Action())
  372. }
  373. }
  374. }
  375. var routeOptions *rule.RuleActionRouteOptions
  376. switch action := currentRule.Action().(type) {
  377. case *rule.RuleActionRoute:
  378. routeOptions = &action.RuleActionRouteOptions
  379. case *rule.RuleActionRouteOptions:
  380. routeOptions = action
  381. }
  382. if routeOptions != nil {
  383. // TODO: add nat
  384. if (routeOptions.OverrideAddress.IsValid() || routeOptions.OverridePort > 0) && !metadata.RouteOriginalDestination.IsValid() {
  385. metadata.RouteOriginalDestination = metadata.Destination
  386. }
  387. if routeOptions.OverrideAddress.IsValid() {
  388. metadata.Destination = M.Socksaddr{
  389. Addr: routeOptions.OverrideAddress.Addr,
  390. Port: metadata.Destination.Port,
  391. Fqdn: routeOptions.OverrideAddress.Fqdn,
  392. }
  393. }
  394. if routeOptions.OverridePort > 0 {
  395. metadata.Destination = M.Socksaddr{
  396. Addr: metadata.Destination.Addr,
  397. Port: routeOptions.OverridePort,
  398. Fqdn: metadata.Destination.Fqdn,
  399. }
  400. }
  401. metadata.NetworkStrategy = routeOptions.NetworkStrategy
  402. metadata.FallbackDelay = routeOptions.FallbackDelay
  403. if routeOptions.UDPDisableDomainUnmapping {
  404. metadata.UDPDisableDomainUnmapping = true
  405. }
  406. if routeOptions.UDPConnect {
  407. metadata.UDPConnect = true
  408. }
  409. if routeOptions.UDPTimeout > 0 {
  410. metadata.UDPTimeout = routeOptions.UDPTimeout
  411. }
  412. }
  413. switch action := currentRule.Action().(type) {
  414. case *rule.RuleActionSniff:
  415. if !preMatch {
  416. newBuffer, newPacketBuffers, newErr := r.actionSniff(ctx, metadata, action, inputConn, inputPacketConn)
  417. if newErr != nil {
  418. fatalErr = newErr
  419. return
  420. }
  421. if newBuffer != nil {
  422. buffers = append(buffers, newBuffer)
  423. } else if len(newPacketBuffers) > 0 {
  424. packetBuffers = append(packetBuffers, newPacketBuffers...)
  425. }
  426. } else {
  427. selectedRule = currentRule
  428. selectedRuleIndex = currentRuleIndex
  429. break match
  430. }
  431. case *rule.RuleActionResolve:
  432. fatalErr = r.actionResolve(ctx, metadata, action)
  433. if fatalErr != nil {
  434. return
  435. }
  436. }
  437. actionType := currentRule.Action().Type()
  438. if actionType == C.RuleActionTypeRoute ||
  439. actionType == C.RuleActionTypeReject ||
  440. actionType == C.RuleActionTypeHijackDNS ||
  441. (actionType == C.RuleActionTypeSniff && preMatch) {
  442. selectedRule = currentRule
  443. selectedRuleIndex = currentRuleIndex
  444. break match
  445. }
  446. }
  447. if !preMatch && metadata.Destination.Addr.IsUnspecified() {
  448. newBuffer, newPacketBuffers, newErr := r.actionSniff(ctx, metadata, &rule.RuleActionSniff{}, inputConn, inputPacketConn)
  449. if newErr != nil {
  450. fatalErr = newErr
  451. return
  452. }
  453. if newBuffer != nil {
  454. buffers = append(buffers, newBuffer)
  455. } else if len(newPacketBuffers) > 0 {
  456. packetBuffers = append(packetBuffers, newPacketBuffers...)
  457. }
  458. }
  459. return
  460. }
  461. func (r *Router) actionSniff(
  462. ctx context.Context, metadata *adapter.InboundContext, action *rule.RuleActionSniff,
  463. inputConn net.Conn, inputPacketConn N.PacketConn,
  464. ) (buffer *buf.Buffer, packetBuffers []*N.PacketBuffer, fatalErr error) {
  465. if sniff.Skip(metadata) {
  466. return
  467. } else if inputConn != nil {
  468. sniffBuffer := buf.NewPacket()
  469. var streamSniffers []sniff.StreamSniffer
  470. if len(action.StreamSniffers) > 0 {
  471. streamSniffers = action.StreamSniffers
  472. } else {
  473. streamSniffers = []sniff.StreamSniffer{
  474. sniff.TLSClientHello,
  475. sniff.HTTPHost,
  476. sniff.StreamDomainNameQuery,
  477. sniff.BitTorrent,
  478. sniff.SSH,
  479. sniff.RDP,
  480. }
  481. }
  482. err := sniff.PeekStream(
  483. ctx,
  484. metadata,
  485. inputConn,
  486. sniffBuffer,
  487. action.Timeout,
  488. streamSniffers...,
  489. )
  490. if err == nil {
  491. //goland:noinspection GoDeprecation
  492. if action.OverrideDestination && M.IsDomainName(metadata.Domain) {
  493. metadata.Destination = M.Socksaddr{
  494. Fqdn: metadata.Domain,
  495. Port: metadata.Destination.Port,
  496. }
  497. }
  498. if metadata.Domain != "" && metadata.Client != "" {
  499. r.logger.DebugContext(ctx, "sniffed protocol: ", metadata.Protocol, ", domain: ", metadata.Domain, ", client: ", metadata.Client)
  500. } else if metadata.Domain != "" {
  501. r.logger.DebugContext(ctx, "sniffed protocol: ", metadata.Protocol, ", domain: ", metadata.Domain)
  502. } else {
  503. r.logger.DebugContext(ctx, "sniffed protocol: ", metadata.Protocol)
  504. }
  505. }
  506. if !sniffBuffer.IsEmpty() {
  507. buffer = sniffBuffer
  508. } else {
  509. sniffBuffer.Release()
  510. }
  511. } else if inputPacketConn != nil {
  512. for {
  513. var (
  514. sniffBuffer = buf.NewPacket()
  515. destination M.Socksaddr
  516. done = make(chan struct{})
  517. err error
  518. )
  519. go func() {
  520. sniffTimeout := C.ReadPayloadTimeout
  521. if action.Timeout > 0 {
  522. sniffTimeout = action.Timeout
  523. }
  524. inputPacketConn.SetReadDeadline(time.Now().Add(sniffTimeout))
  525. destination, err = inputPacketConn.ReadPacket(sniffBuffer)
  526. inputPacketConn.SetReadDeadline(time.Time{})
  527. close(done)
  528. }()
  529. select {
  530. case <-done:
  531. case <-ctx.Done():
  532. inputPacketConn.Close()
  533. fatalErr = ctx.Err()
  534. return
  535. }
  536. if err != nil {
  537. sniffBuffer.Release()
  538. if !errors.Is(err, os.ErrDeadlineExceeded) {
  539. fatalErr = err
  540. return
  541. }
  542. } else {
  543. // TODO: maybe always override destination
  544. if metadata.Destination.Addr.IsUnspecified() {
  545. metadata.Destination = destination
  546. }
  547. if len(packetBuffers) > 0 {
  548. err = sniff.PeekPacket(
  549. ctx,
  550. metadata,
  551. sniffBuffer.Bytes(),
  552. sniff.QUICClientHello,
  553. )
  554. } else {
  555. var packetSniffers []sniff.PacketSniffer
  556. if len(action.PacketSniffers) > 0 {
  557. packetSniffers = action.PacketSniffers
  558. } else {
  559. packetSniffers = []sniff.PacketSniffer{
  560. sniff.DomainNameQuery,
  561. sniff.QUICClientHello,
  562. sniff.STUNMessage,
  563. sniff.UTP,
  564. sniff.UDPTracker,
  565. sniff.DTLSRecord,
  566. }
  567. }
  568. err = sniff.PeekPacket(
  569. ctx, metadata,
  570. sniffBuffer.Bytes(),
  571. packetSniffers...,
  572. )
  573. }
  574. packetBuffer := N.NewPacketBuffer()
  575. *packetBuffer = N.PacketBuffer{
  576. Buffer: sniffBuffer,
  577. Destination: destination,
  578. }
  579. packetBuffers = append(packetBuffers, packetBuffer)
  580. if E.IsMulti(err, sniff.ErrClientHelloFragmented) && len(packetBuffers) == 0 {
  581. r.logger.DebugContext(ctx, "attempt to sniff fragmented QUIC client hello")
  582. continue
  583. }
  584. if metadata.Protocol != "" {
  585. //goland:noinspection GoDeprecation
  586. if action.OverrideDestination && M.IsDomainName(metadata.Domain) {
  587. metadata.Destination = M.Socksaddr{
  588. Fqdn: metadata.Domain,
  589. Port: metadata.Destination.Port,
  590. }
  591. }
  592. if metadata.Domain != "" && metadata.Client != "" {
  593. r.logger.DebugContext(ctx, "sniffed packet protocol: ", metadata.Protocol, ", domain: ", metadata.Domain, ", client: ", metadata.Client)
  594. } else if metadata.Domain != "" {
  595. r.logger.DebugContext(ctx, "sniffed packet protocol: ", metadata.Protocol, ", domain: ", metadata.Domain)
  596. } else if metadata.Client != "" {
  597. r.logger.DebugContext(ctx, "sniffed packet protocol: ", metadata.Protocol, ", client: ", metadata.Client)
  598. } else {
  599. r.logger.DebugContext(ctx, "sniffed packet protocol: ", metadata.Protocol)
  600. }
  601. }
  602. }
  603. break
  604. }
  605. }
  606. return
  607. }
  608. func (r *Router) actionResolve(ctx context.Context, metadata *adapter.InboundContext, action *rule.RuleActionResolve) error {
  609. if metadata.Destination.IsFqdn() {
  610. metadata.DNSServer = action.Server
  611. addresses, err := r.Lookup(adapter.WithContext(ctx, metadata), metadata.Destination.Fqdn, action.Strategy)
  612. if err != nil {
  613. return err
  614. }
  615. metadata.DestinationAddresses = addresses
  616. r.dnsLogger.DebugContext(ctx, "resolved [", strings.Join(F.MapToString(metadata.DestinationAddresses), " "), "]")
  617. if metadata.Destination.IsIPv4() {
  618. metadata.IPVersion = 4
  619. } else if metadata.Destination.IsIPv6() {
  620. metadata.IPVersion = 6
  621. }
  622. }
  623. return nil
  624. }