conn.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. package route
  2. import (
  3. "context"
  4. "io"
  5. "net"
  6. "net/netip"
  7. "os"
  8. "strings"
  9. "sync"
  10. "sync/atomic"
  11. "time"
  12. "github.com/sagernet/sing-box/adapter"
  13. "github.com/sagernet/sing-box/common/dialer"
  14. "github.com/sagernet/sing-box/common/tlsfragment"
  15. C "github.com/sagernet/sing-box/constant"
  16. "github.com/sagernet/sing/common"
  17. "github.com/sagernet/sing/common/buf"
  18. "github.com/sagernet/sing/common/bufio"
  19. "github.com/sagernet/sing/common/canceler"
  20. E "github.com/sagernet/sing/common/exceptions"
  21. "github.com/sagernet/sing/common/logger"
  22. M "github.com/sagernet/sing/common/metadata"
  23. N "github.com/sagernet/sing/common/network"
  24. "github.com/sagernet/sing/common/x/list"
  25. )
  26. var _ adapter.ConnectionManager = (*ConnectionManager)(nil)
  27. type ConnectionManager struct {
  28. logger logger.ContextLogger
  29. access sync.Mutex
  30. connections list.List[io.Closer]
  31. }
  32. func NewConnectionManager(logger logger.ContextLogger) *ConnectionManager {
  33. return &ConnectionManager{
  34. logger: logger,
  35. }
  36. }
  37. func (m *ConnectionManager) Start(stage adapter.StartStage) error {
  38. return nil
  39. }
  40. func (m *ConnectionManager) Count() int {
  41. return m.connections.Len()
  42. }
  43. func (m *ConnectionManager) CloseAll() {
  44. m.access.Lock()
  45. var closers []io.Closer
  46. for element := m.connections.Front(); element != nil; {
  47. nextElement := element.Next()
  48. closers = append(closers, element.Value)
  49. m.connections.Remove(element)
  50. element = nextElement
  51. }
  52. m.access.Unlock()
  53. for _, closer := range closers {
  54. common.Close(closer)
  55. }
  56. }
  57. func (m *ConnectionManager) Close() error {
  58. m.CloseAll()
  59. return nil
  60. }
  61. func (m *ConnectionManager) TrackConn(conn net.Conn) net.Conn {
  62. m.access.Lock()
  63. element := m.connections.PushBack(conn)
  64. m.access.Unlock()
  65. return &trackedConn{
  66. Conn: conn,
  67. manager: m,
  68. element: element,
  69. }
  70. }
  71. func (m *ConnectionManager) TrackPacketConn(conn net.PacketConn) net.PacketConn {
  72. m.access.Lock()
  73. element := m.connections.PushBack(conn)
  74. m.access.Unlock()
  75. return &trackedPacketConn{
  76. PacketConn: conn,
  77. manager: m,
  78. element: element,
  79. }
  80. }
  81. func (m *ConnectionManager) NewConnection(ctx context.Context, this N.Dialer, conn net.Conn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) {
  82. ctx = adapter.WithContext(ctx, &metadata)
  83. var (
  84. remoteConn net.Conn
  85. err error
  86. )
  87. if len(metadata.DestinationAddresses) > 0 || metadata.Destination.IsIP() {
  88. remoteConn, err = dialer.DialSerialNetwork(ctx, this, N.NetworkTCP, metadata.Destination, metadata.DestinationAddresses, metadata.NetworkStrategy, metadata.NetworkType, metadata.FallbackNetworkType, metadata.FallbackDelay)
  89. } else {
  90. remoteConn, err = this.DialContext(ctx, N.NetworkTCP, metadata.Destination)
  91. }
  92. if err != nil {
  93. var remoteString string
  94. if len(metadata.DestinationAddresses) > 0 {
  95. remoteString = "[" + strings.Join(common.Map(metadata.DestinationAddresses, netip.Addr.String), ",") + "]"
  96. } else {
  97. remoteString = metadata.Destination.String()
  98. }
  99. var dialerString string
  100. if outbound, isOutbound := this.(adapter.Outbound); isOutbound {
  101. dialerString = " using outbound/" + outbound.Type() + "[" + outbound.Tag() + "]"
  102. }
  103. err = E.Cause(err, "open connection to ", remoteString, dialerString)
  104. N.CloseOnHandshakeFailure(conn, onClose, err)
  105. m.logger.ErrorContext(ctx, err)
  106. return
  107. }
  108. err = N.ReportConnHandshakeSuccess(conn, remoteConn)
  109. if err != nil {
  110. err = E.Cause(err, "report handshake success")
  111. remoteConn.Close()
  112. N.CloseOnHandshakeFailure(conn, onClose, err)
  113. m.logger.ErrorContext(ctx, err)
  114. return
  115. }
  116. if metadata.TLSFragment || metadata.TLSRecordFragment {
  117. remoteConn = tf.NewConn(remoteConn, ctx, metadata.TLSFragment, metadata.TLSRecordFragment, metadata.TLSFragmentFallbackDelay)
  118. }
  119. var done atomic.Bool
  120. if m.kickWriteHandshake(ctx, conn, remoteConn, false, &done, onClose) {
  121. return
  122. }
  123. if m.kickWriteHandshake(ctx, remoteConn, conn, true, &done, onClose) {
  124. return
  125. }
  126. go m.connectionCopy(ctx, conn, remoteConn, false, &done, onClose)
  127. go m.connectionCopy(ctx, remoteConn, conn, true, &done, onClose)
  128. }
  129. func (m *ConnectionManager) NewPacketConnection(ctx context.Context, this N.Dialer, conn N.PacketConn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) {
  130. ctx = adapter.WithContext(ctx, &metadata)
  131. var (
  132. remotePacketConn net.PacketConn
  133. remoteConn net.Conn
  134. destinationAddress netip.Addr
  135. err error
  136. )
  137. if metadata.UDPConnect {
  138. parallelDialer, isParallelDialer := this.(dialer.ParallelInterfaceDialer)
  139. if len(metadata.DestinationAddresses) > 0 {
  140. if isParallelDialer {
  141. remoteConn, err = dialer.DialSerialNetwork(ctx, parallelDialer, N.NetworkUDP, metadata.Destination, metadata.DestinationAddresses, metadata.NetworkStrategy, metadata.NetworkType, metadata.FallbackNetworkType, metadata.FallbackDelay)
  142. } else {
  143. remoteConn, err = N.DialSerial(ctx, this, N.NetworkUDP, metadata.Destination, metadata.DestinationAddresses)
  144. }
  145. } else if metadata.Destination.IsIP() {
  146. if isParallelDialer {
  147. remoteConn, err = dialer.DialSerialNetwork(ctx, parallelDialer, N.NetworkUDP, metadata.Destination, metadata.DestinationAddresses, metadata.NetworkStrategy, metadata.NetworkType, metadata.FallbackNetworkType, metadata.FallbackDelay)
  148. } else {
  149. remoteConn, err = this.DialContext(ctx, N.NetworkUDP, metadata.Destination)
  150. }
  151. } else {
  152. remoteConn, err = this.DialContext(ctx, N.NetworkUDP, metadata.Destination)
  153. }
  154. if err != nil {
  155. var remoteString string
  156. if len(metadata.DestinationAddresses) > 0 {
  157. remoteString = "[" + strings.Join(common.Map(metadata.DestinationAddresses, netip.Addr.String), ",") + "]"
  158. } else {
  159. remoteString = metadata.Destination.String()
  160. }
  161. var dialerString string
  162. if outbound, isOutbound := this.(adapter.Outbound); isOutbound {
  163. dialerString = " using outbound/" + outbound.Type() + "[" + outbound.Tag() + "]"
  164. }
  165. err = E.Cause(err, "open packet connection to ", remoteString, dialerString)
  166. N.CloseOnHandshakeFailure(conn, onClose, err)
  167. m.logger.ErrorContext(ctx, err)
  168. return
  169. }
  170. remotePacketConn = bufio.NewUnbindPacketConn(remoteConn)
  171. connRemoteAddr := M.AddrFromNet(remoteConn.RemoteAddr())
  172. if connRemoteAddr != metadata.Destination.Addr {
  173. destinationAddress = connRemoteAddr
  174. }
  175. } else {
  176. if len(metadata.DestinationAddresses) > 0 {
  177. remotePacketConn, destinationAddress, err = dialer.ListenSerialNetworkPacket(ctx, this, metadata.Destination, metadata.DestinationAddresses, metadata.NetworkStrategy, metadata.NetworkType, metadata.FallbackNetworkType, metadata.FallbackDelay)
  178. } else if packetDialer, withDestination := this.(dialer.PacketDialerWithDestination); withDestination {
  179. remotePacketConn, destinationAddress, err = packetDialer.ListenPacketWithDestination(ctx, metadata.Destination)
  180. } else {
  181. remotePacketConn, err = this.ListenPacket(ctx, metadata.Destination)
  182. }
  183. if err != nil {
  184. var dialerString string
  185. if outbound, isOutbound := this.(adapter.Outbound); isOutbound {
  186. dialerString = " using outbound/" + outbound.Type() + "[" + outbound.Tag() + "]"
  187. }
  188. err = E.Cause(err, "listen packet connection using ", dialerString)
  189. N.CloseOnHandshakeFailure(conn, onClose, err)
  190. m.logger.ErrorContext(ctx, err)
  191. return
  192. }
  193. }
  194. err = N.ReportPacketConnHandshakeSuccess(conn, remotePacketConn)
  195. if err != nil {
  196. conn.Close()
  197. remotePacketConn.Close()
  198. m.logger.ErrorContext(ctx, "report handshake success: ", err)
  199. return
  200. }
  201. if destinationAddress.IsValid() {
  202. var originDestination M.Socksaddr
  203. if metadata.RouteOriginalDestination.IsValid() {
  204. originDestination = metadata.RouteOriginalDestination
  205. } else {
  206. originDestination = metadata.Destination
  207. }
  208. if natConn, loaded := common.Cast[bufio.NATPacketConn](conn); loaded {
  209. natConn.UpdateDestination(destinationAddress)
  210. } else {
  211. destination := M.SocksaddrFrom(destinationAddress, metadata.Destination.Port)
  212. if metadata.Destination != destination {
  213. if metadata.UDPDisableDomainUnmapping {
  214. remotePacketConn = bufio.NewUnidirectionalNATPacketConn(bufio.NewPacketConn(remotePacketConn), destination, originDestination)
  215. } else {
  216. remotePacketConn = bufio.NewNATPacketConn(bufio.NewPacketConn(remotePacketConn), destination, originDestination)
  217. }
  218. } else if metadata.RouteOriginalDestination.IsValid() && metadata.RouteOriginalDestination != metadata.Destination {
  219. remotePacketConn = bufio.NewDestinationNATPacketConn(bufio.NewPacketConn(remotePacketConn), metadata.Destination, metadata.RouteOriginalDestination)
  220. }
  221. }
  222. } else if metadata.RouteOriginalDestination.IsValid() && metadata.RouteOriginalDestination != metadata.Destination {
  223. remotePacketConn = bufio.NewDestinationNATPacketConn(bufio.NewPacketConn(remotePacketConn), metadata.Destination, metadata.RouteOriginalDestination)
  224. }
  225. var udpTimeout time.Duration
  226. if metadata.UDPTimeout > 0 {
  227. udpTimeout = metadata.UDPTimeout
  228. } else {
  229. protocol := metadata.Protocol
  230. if protocol == "" {
  231. protocol = C.PortProtocols[metadata.Destination.Port]
  232. }
  233. if protocol != "" {
  234. udpTimeout = C.ProtocolTimeouts[protocol]
  235. }
  236. }
  237. if udpTimeout > 0 {
  238. ctx, conn = canceler.NewPacketConn(ctx, conn, udpTimeout)
  239. }
  240. destination := bufio.NewPacketConn(remotePacketConn)
  241. var done atomic.Bool
  242. go m.packetConnectionCopy(ctx, conn, destination, false, &done, onClose)
  243. go m.packetConnectionCopy(ctx, destination, conn, true, &done, onClose)
  244. }
  245. func (m *ConnectionManager) connectionCopy(ctx context.Context, source net.Conn, destination net.Conn, direction bool, done *atomic.Bool, onClose N.CloseHandlerFunc) {
  246. _, err := bufio.CopyWithIncreateBuffer(destination, source, bufio.DefaultIncreaseBufferAfter, bufio.DefaultBatchSize)
  247. if err != nil {
  248. common.Close(source, destination)
  249. } else if duplexDst, isDuplex := destination.(N.WriteCloser); isDuplex {
  250. err = duplexDst.CloseWrite()
  251. if err != nil {
  252. common.Close(source, destination)
  253. }
  254. } else {
  255. destination.Close()
  256. }
  257. if done.Swap(true) {
  258. if onClose != nil {
  259. onClose(err)
  260. }
  261. common.Close(source, destination)
  262. }
  263. if !direction {
  264. if err == nil {
  265. m.logger.DebugContext(ctx, "connection upload finished")
  266. } else if !E.IsClosedOrCanceled(err) {
  267. m.logger.ErrorContext(ctx, "connection upload closed: ", err)
  268. } else {
  269. m.logger.TraceContext(ctx, "connection upload closed")
  270. }
  271. } else {
  272. if err == nil {
  273. m.logger.DebugContext(ctx, "connection download finished")
  274. } else if !E.IsClosedOrCanceled(err) {
  275. m.logger.ErrorContext(ctx, "connection download closed: ", err)
  276. } else {
  277. m.logger.TraceContext(ctx, "connection download closed")
  278. }
  279. }
  280. }
  281. func (m *ConnectionManager) kickWriteHandshake(ctx context.Context, source net.Conn, destination net.Conn, direction bool, done *atomic.Bool, onClose N.CloseHandlerFunc) bool {
  282. if !N.NeedHandshakeForWrite(destination) {
  283. return false
  284. }
  285. var (
  286. cachedBuffer *buf.Buffer
  287. wrotePayload bool
  288. )
  289. sourceReader, readCounters := N.UnwrapCountReader(source, nil)
  290. destinationWriter, writeCounters := N.UnwrapCountWriter(destination, nil)
  291. if cachedReader, ok := sourceReader.(N.CachedReader); ok {
  292. cachedBuffer = cachedReader.ReadCached()
  293. }
  294. var err error
  295. if cachedBuffer != nil {
  296. wrotePayload = true
  297. dataLen := cachedBuffer.Len()
  298. _, err = destinationWriter.Write(cachedBuffer.Bytes())
  299. cachedBuffer.Release()
  300. if err == nil {
  301. for _, counter := range readCounters {
  302. counter(int64(dataLen))
  303. }
  304. for _, counter := range writeCounters {
  305. counter(int64(dataLen))
  306. }
  307. }
  308. } else {
  309. _ = destination.SetWriteDeadline(time.Now().Add(C.ReadPayloadTimeout))
  310. _, err = destinationWriter.Write(nil)
  311. _ = destination.SetWriteDeadline(time.Time{})
  312. }
  313. if err == nil {
  314. return false
  315. }
  316. if !wrotePayload && (E.IsMulti(err, os.ErrInvalid, context.DeadlineExceeded, io.EOF) || E.IsTimeout(err)) {
  317. return false
  318. }
  319. if !done.Swap(true) {
  320. if onClose != nil {
  321. onClose(err)
  322. }
  323. }
  324. common.Close(source, destination)
  325. if !direction {
  326. m.logger.ErrorContext(ctx, "connection upload handshake: ", err)
  327. } else {
  328. m.logger.ErrorContext(ctx, "connection download handshake: ", err)
  329. }
  330. return true
  331. }
  332. func (m *ConnectionManager) packetConnectionCopy(ctx context.Context, source N.PacketReader, destination N.PacketWriter, direction bool, done *atomic.Bool, onClose N.CloseHandlerFunc) {
  333. _, err := bufio.CopyPacket(destination, source)
  334. if !direction {
  335. if err == nil {
  336. m.logger.DebugContext(ctx, "packet upload finished")
  337. } else if E.IsClosedOrCanceled(err) {
  338. m.logger.TraceContext(ctx, "packet upload closed")
  339. } else {
  340. m.logger.DebugContext(ctx, "packet upload closed: ", err)
  341. }
  342. } else {
  343. if err == nil {
  344. m.logger.DebugContext(ctx, "packet download finished")
  345. } else if E.IsClosedOrCanceled(err) {
  346. m.logger.TraceContext(ctx, "packet download closed")
  347. } else {
  348. m.logger.DebugContext(ctx, "packet download closed: ", err)
  349. }
  350. }
  351. if !done.Swap(true) {
  352. if onClose != nil {
  353. onClose(err)
  354. }
  355. }
  356. common.Close(source, destination)
  357. }
  358. type trackedConn struct {
  359. net.Conn
  360. manager *ConnectionManager
  361. element *list.Element[io.Closer]
  362. }
  363. func (c *trackedConn) Close() error {
  364. c.manager.access.Lock()
  365. c.manager.connections.Remove(c.element)
  366. c.manager.access.Unlock()
  367. return c.Conn.Close()
  368. }
  369. func (c *trackedConn) Upstream() any {
  370. return c.Conn
  371. }
  372. func (c *trackedConn) ReaderReplaceable() bool {
  373. return true
  374. }
  375. func (c *trackedConn) WriterReplaceable() bool {
  376. return true
  377. }
  378. type trackedPacketConn struct {
  379. net.PacketConn
  380. manager *ConnectionManager
  381. element *list.Element[io.Closer]
  382. }
  383. func (c *trackedPacketConn) Close() error {
  384. c.manager.access.Lock()
  385. c.manager.connections.Remove(c.element)
  386. c.manager.access.Unlock()
  387. return c.PacketConn.Close()
  388. }
  389. func (c *trackedPacketConn) Upstream() any {
  390. return bufio.NewPacketConn(c.PacketConn)
  391. }
  392. func (c *trackedPacketConn) ReaderReplaceable() bool {
  393. return true
  394. }
  395. func (c *trackedPacketConn) WriterReplaceable() bool {
  396. return true
  397. }