conn.go 12 KB

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