client.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. package mux
  2. import (
  3. "context"
  4. "encoding/binary"
  5. "io"
  6. "net"
  7. "sync"
  8. "github.com/sagernet/sing-box/option"
  9. "github.com/sagernet/sing/common"
  10. "github.com/sagernet/sing/common/buf"
  11. "github.com/sagernet/sing/common/bufio"
  12. E "github.com/sagernet/sing/common/exceptions"
  13. M "github.com/sagernet/sing/common/metadata"
  14. N "github.com/sagernet/sing/common/network"
  15. "github.com/sagernet/sing/common/x/list"
  16. )
  17. var _ N.Dialer = (*Client)(nil)
  18. type Client struct {
  19. access sync.Mutex
  20. connections list.List[abstractSession]
  21. ctx context.Context
  22. dialer N.Dialer
  23. protocol Protocol
  24. maxConnections int
  25. minStreams int
  26. maxStreams int
  27. }
  28. func NewClient(ctx context.Context, dialer N.Dialer, protocol Protocol, maxConnections int, minStreams int, maxStreams int) *Client {
  29. return &Client{
  30. ctx: ctx,
  31. dialer: dialer,
  32. protocol: protocol,
  33. maxConnections: maxConnections,
  34. minStreams: minStreams,
  35. maxStreams: maxStreams,
  36. }
  37. }
  38. func NewClientWithOptions(ctx context.Context, dialer N.Dialer, options option.MultiplexOptions) (N.Dialer, error) {
  39. if !options.Enabled {
  40. return nil, nil
  41. }
  42. if options.MaxConnections == 0 && options.MaxStreams == 0 {
  43. options.MinStreams = 8
  44. }
  45. protocol, err := ParseProtocol(options.Protocol)
  46. if err != nil {
  47. return nil, err
  48. }
  49. return NewClient(ctx, dialer, protocol, options.MaxConnections, options.MinStreams, options.MaxStreams), nil
  50. }
  51. func (c *Client) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
  52. switch N.NetworkName(network) {
  53. case N.NetworkTCP:
  54. stream, err := c.openStream()
  55. if err != nil {
  56. return nil, err
  57. }
  58. return &ClientConn{Conn: stream, destination: destination}, nil
  59. case N.NetworkUDP:
  60. stream, err := c.openStream()
  61. if err != nil {
  62. return nil, err
  63. }
  64. return bufio.NewUnbindPacketConn(&ClientPacketConn{ExtendedConn: bufio.NewExtendedConn(stream), destination: destination}), nil
  65. default:
  66. return nil, E.Extend(N.ErrUnknownNetwork, network)
  67. }
  68. }
  69. func (c *Client) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
  70. stream, err := c.openStream()
  71. if err != nil {
  72. return nil, err
  73. }
  74. return &ClientPacketAddrConn{ExtendedConn: bufio.NewExtendedConn(stream), destination: destination}, nil
  75. }
  76. func (c *Client) openStream() (net.Conn, error) {
  77. var (
  78. session abstractSession
  79. stream net.Conn
  80. err error
  81. )
  82. for attempts := 0; attempts < 2; attempts++ {
  83. session, err = c.offer()
  84. if err != nil {
  85. continue
  86. }
  87. stream, err = session.Open()
  88. if err != nil {
  89. continue
  90. }
  91. break
  92. }
  93. if err != nil {
  94. return nil, err
  95. }
  96. return &wrapStream{stream}, nil
  97. }
  98. func (c *Client) offer() (abstractSession, error) {
  99. c.access.Lock()
  100. defer c.access.Unlock()
  101. sessions := make([]abstractSession, 0, c.maxConnections)
  102. for element := c.connections.Front(); element != nil; {
  103. if element.Value.IsClosed() {
  104. nextElement := element.Next()
  105. c.connections.Remove(element)
  106. element = nextElement
  107. continue
  108. }
  109. sessions = append(sessions, element.Value)
  110. element = element.Next()
  111. }
  112. sLen := len(sessions)
  113. if sLen == 0 {
  114. return c.offerNew()
  115. }
  116. session := common.MinBy(sessions, abstractSession.NumStreams)
  117. numStreams := session.NumStreams()
  118. if numStreams == 0 {
  119. return session, nil
  120. }
  121. if c.maxConnections > 0 {
  122. if sLen >= c.maxConnections || numStreams < c.minStreams {
  123. return session, nil
  124. }
  125. } else {
  126. if c.maxStreams > 0 && numStreams < c.maxStreams {
  127. return session, nil
  128. }
  129. }
  130. return c.offerNew()
  131. }
  132. func (c *Client) offerNew() (abstractSession, error) {
  133. conn, err := c.dialer.DialContext(c.ctx, N.NetworkTCP, Destination)
  134. if err != nil {
  135. return nil, err
  136. }
  137. if vectorisedWriter, isVectorised := bufio.CreateVectorisedWriter(conn); isVectorised {
  138. conn = &vectorisedProtocolConn{protocolConn{Conn: conn, protocol: c.protocol}, vectorisedWriter}
  139. } else {
  140. conn = &protocolConn{Conn: conn, protocol: c.protocol}
  141. }
  142. session, err := c.protocol.newClient(conn)
  143. if err != nil {
  144. return nil, err
  145. }
  146. c.connections.PushBack(session)
  147. return session, nil
  148. }
  149. func (c *Client) Close() error {
  150. c.access.Lock()
  151. defer c.access.Unlock()
  152. for _, session := range c.connections.Array() {
  153. session.Close()
  154. }
  155. return nil
  156. }
  157. type ClientConn struct {
  158. net.Conn
  159. destination M.Socksaddr
  160. requestWrite bool
  161. responseRead bool
  162. }
  163. func (c *ClientConn) readResponse() error {
  164. response, err := ReadStreamResponse(c.Conn)
  165. if err != nil {
  166. return err
  167. }
  168. if response.Status == statusError {
  169. return E.New("remote error: ", response.Message)
  170. }
  171. return nil
  172. }
  173. func (c *ClientConn) Read(b []byte) (n int, err error) {
  174. if !c.responseRead {
  175. err = c.readResponse()
  176. if err != nil {
  177. return
  178. }
  179. c.responseRead = true
  180. }
  181. return c.Conn.Read(b)
  182. }
  183. func (c *ClientConn) Write(b []byte) (n int, err error) {
  184. if c.requestWrite {
  185. return c.Conn.Write(b)
  186. }
  187. request := StreamRequest{
  188. Network: N.NetworkTCP,
  189. Destination: c.destination,
  190. }
  191. _buffer := buf.StackNewSize(requestLen(request) + len(b))
  192. defer common.KeepAlive(_buffer)
  193. buffer := common.Dup(_buffer)
  194. defer buffer.Release()
  195. EncodeStreamRequest(request, buffer)
  196. buffer.Write(b)
  197. _, err = c.Conn.Write(buffer.Bytes())
  198. if err != nil {
  199. return
  200. }
  201. c.requestWrite = true
  202. return len(b), nil
  203. }
  204. func (c *ClientConn) ReadFrom(r io.Reader) (n int64, err error) {
  205. if !c.requestWrite {
  206. return bufio.ReadFrom0(c, r)
  207. }
  208. return bufio.Copy(c.Conn, r)
  209. }
  210. func (c *ClientConn) WriteTo(w io.Writer) (n int64, err error) {
  211. if !c.responseRead {
  212. return bufio.WriteTo0(c, w)
  213. }
  214. return bufio.Copy(w, c.Conn)
  215. }
  216. func (c *ClientConn) LocalAddr() net.Addr {
  217. return c.Conn.LocalAddr()
  218. }
  219. func (c *ClientConn) RemoteAddr() net.Addr {
  220. return c.destination.TCPAddr()
  221. }
  222. func (c *ClientConn) ReaderReplaceable() bool {
  223. return c.responseRead
  224. }
  225. func (c *ClientConn) WriterReplaceable() bool {
  226. return c.requestWrite
  227. }
  228. func (c *ClientConn) Upstream() any {
  229. return c.Conn
  230. }
  231. type ClientPacketConn struct {
  232. N.ExtendedConn
  233. destination M.Socksaddr
  234. requestWrite bool
  235. responseRead bool
  236. }
  237. func (c *ClientPacketConn) readResponse() error {
  238. response, err := ReadStreamResponse(c.ExtendedConn)
  239. if err != nil {
  240. return err
  241. }
  242. if response.Status == statusError {
  243. return E.New("remote error: ", response.Message)
  244. }
  245. return nil
  246. }
  247. func (c *ClientPacketConn) Read(b []byte) (n int, err error) {
  248. if !c.responseRead {
  249. err = c.readResponse()
  250. if err != nil {
  251. return
  252. }
  253. c.responseRead = true
  254. }
  255. var length uint16
  256. err = binary.Read(c.ExtendedConn, binary.BigEndian, &length)
  257. if err != nil {
  258. return
  259. }
  260. if cap(b) < int(length) {
  261. return 0, io.ErrShortBuffer
  262. }
  263. return io.ReadFull(c.ExtendedConn, b[:length])
  264. }
  265. func (c *ClientPacketConn) writeRequest(payload []byte) (n int, err error) {
  266. request := StreamRequest{
  267. Network: N.NetworkUDP,
  268. Destination: c.destination,
  269. }
  270. rLen := requestLen(request)
  271. if len(payload) > 0 {
  272. rLen += 2 + len(payload)
  273. }
  274. _buffer := buf.StackNewSize(rLen)
  275. defer common.KeepAlive(_buffer)
  276. buffer := common.Dup(_buffer)
  277. defer buffer.Release()
  278. EncodeStreamRequest(request, buffer)
  279. if len(payload) > 0 {
  280. common.Must(
  281. binary.Write(buffer, binary.BigEndian, uint16(len(payload))),
  282. common.Error(buffer.Write(payload)),
  283. )
  284. }
  285. _, err = c.ExtendedConn.Write(buffer.Bytes())
  286. if err != nil {
  287. return
  288. }
  289. c.requestWrite = true
  290. return len(payload), nil
  291. }
  292. func (c *ClientPacketConn) Write(b []byte) (n int, err error) {
  293. if !c.requestWrite {
  294. return c.writeRequest(b)
  295. }
  296. err = binary.Write(c.ExtendedConn, binary.BigEndian, uint16(len(b)))
  297. if err != nil {
  298. return
  299. }
  300. return c.ExtendedConn.Write(b)
  301. }
  302. func (c *ClientPacketConn) WriteBuffer(buffer *buf.Buffer) error {
  303. if !c.requestWrite {
  304. defer buffer.Release()
  305. return common.Error(c.writeRequest(buffer.Bytes()))
  306. }
  307. bLen := buffer.Len()
  308. binary.BigEndian.PutUint16(buffer.ExtendHeader(2), uint16(bLen))
  309. return c.ExtendedConn.WriteBuffer(buffer)
  310. }
  311. func (c *ClientPacketConn) FrontHeadroom() int {
  312. return 2
  313. }
  314. func (c *ClientPacketConn) WritePacket(buffer *buf.Buffer, destination M.Socksaddr) error {
  315. return c.WriteBuffer(buffer)
  316. }
  317. func (c *ClientPacketConn) LocalAddr() net.Addr {
  318. return c.ExtendedConn.LocalAddr()
  319. }
  320. func (c *ClientPacketConn) RemoteAddr() net.Addr {
  321. return c.destination.UDPAddr()
  322. }
  323. func (c *ClientPacketConn) Upstream() any {
  324. return c.ExtendedConn
  325. }
  326. var _ N.NetPacketConn = (*ClientPacketAddrConn)(nil)
  327. type ClientPacketAddrConn struct {
  328. N.ExtendedConn
  329. destination M.Socksaddr
  330. requestWrite bool
  331. responseRead bool
  332. }
  333. func (c *ClientPacketAddrConn) readResponse() error {
  334. response, err := ReadStreamResponse(c.ExtendedConn)
  335. if err != nil {
  336. return err
  337. }
  338. if response.Status == statusError {
  339. return E.New("remote error: ", response.Message)
  340. }
  341. return nil
  342. }
  343. func (c *ClientPacketAddrConn) ReadFrom(p []byte) (n int, addr net.Addr, err error) {
  344. if !c.responseRead {
  345. err = c.readResponse()
  346. if err != nil {
  347. return
  348. }
  349. c.responseRead = true
  350. }
  351. destination, err := M.SocksaddrSerializer.ReadAddrPort(c.ExtendedConn)
  352. if err != nil {
  353. return
  354. }
  355. addr = destination.UDPAddr()
  356. var length uint16
  357. err = binary.Read(c.ExtendedConn, binary.BigEndian, &length)
  358. if err != nil {
  359. return
  360. }
  361. if cap(p) < int(length) {
  362. return 0, nil, io.ErrShortBuffer
  363. }
  364. n, err = io.ReadFull(c.ExtendedConn, p[:length])
  365. return
  366. }
  367. func (c *ClientPacketAddrConn) writeRequest(payload []byte, destination M.Socksaddr) (n int, err error) {
  368. request := StreamRequest{
  369. Network: N.NetworkUDP,
  370. Destination: c.destination,
  371. PacketAddr: true,
  372. }
  373. rLen := requestLen(request)
  374. if len(payload) > 0 {
  375. rLen += M.SocksaddrSerializer.AddrPortLen(destination) + 2 + len(payload)
  376. }
  377. _buffer := buf.StackNewSize(rLen)
  378. defer common.KeepAlive(_buffer)
  379. buffer := common.Dup(_buffer)
  380. defer buffer.Release()
  381. EncodeStreamRequest(request, buffer)
  382. if len(payload) > 0 {
  383. common.Must(
  384. M.SocksaddrSerializer.WriteAddrPort(buffer, destination),
  385. binary.Write(buffer, binary.BigEndian, uint16(len(payload))),
  386. common.Error(buffer.Write(payload)),
  387. )
  388. }
  389. _, err = c.ExtendedConn.Write(buffer.Bytes())
  390. if err != nil {
  391. return
  392. }
  393. c.requestWrite = true
  394. return len(payload), nil
  395. }
  396. func (c *ClientPacketAddrConn) WriteTo(p []byte, addr net.Addr) (n int, err error) {
  397. if !c.requestWrite {
  398. return c.writeRequest(p, M.SocksaddrFromNet(addr))
  399. }
  400. err = M.SocksaddrSerializer.WriteAddrPort(c.ExtendedConn, M.SocksaddrFromNet(addr))
  401. if err != nil {
  402. return
  403. }
  404. err = binary.Write(c.ExtendedConn, binary.BigEndian, uint16(len(p)))
  405. if err != nil {
  406. return
  407. }
  408. return c.ExtendedConn.Write(p)
  409. }
  410. func (c *ClientPacketAddrConn) ReadPacket(buffer *buf.Buffer) (destination M.Socksaddr, err error) {
  411. if !c.responseRead {
  412. err = c.readResponse()
  413. if err != nil {
  414. return
  415. }
  416. c.responseRead = true
  417. }
  418. destination, err = M.SocksaddrSerializer.ReadAddrPort(c.ExtendedConn)
  419. if err != nil {
  420. return
  421. }
  422. var length uint16
  423. err = binary.Read(c.ExtendedConn, binary.BigEndian, &length)
  424. if err != nil {
  425. return
  426. }
  427. if buffer.FreeLen() < int(length) {
  428. return destination, io.ErrShortBuffer
  429. }
  430. _, err = io.ReadFull(c.ExtendedConn, buffer.Extend(int(length)))
  431. return
  432. }
  433. func (c *ClientPacketAddrConn) WritePacket(buffer *buf.Buffer, destination M.Socksaddr) error {
  434. if !c.requestWrite {
  435. defer buffer.Release()
  436. return common.Error(c.writeRequest(buffer.Bytes(), destination))
  437. }
  438. bLen := buffer.Len()
  439. header := buf.With(buffer.ExtendHeader(M.SocksaddrSerializer.AddrPortLen(destination) + 2))
  440. common.Must(
  441. M.SocksaddrSerializer.WriteAddrPort(header, destination),
  442. binary.Write(header, binary.BigEndian, uint16(bLen)),
  443. )
  444. return c.ExtendedConn.WriteBuffer(buffer)
  445. }
  446. func (c *ClientPacketAddrConn) LocalAddr() net.Addr {
  447. return c.ExtendedConn.LocalAddr()
  448. }
  449. func (c *ClientPacketAddrConn) FrontHeadroom() int {
  450. return 2 + M.MaxSocksaddrLength
  451. }
  452. func (c *ClientPacketAddrConn) Upstream() any {
  453. return c.ExtendedConn
  454. }