client.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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) NeedAdditionalReadDeadline() bool {
  229. return true
  230. }
  231. func (c *ClientConn) Upstream() any {
  232. return c.Conn
  233. }
  234. type ClientPacketConn struct {
  235. N.ExtendedConn
  236. destination M.Socksaddr
  237. requestWrite bool
  238. responseRead bool
  239. }
  240. func (c *ClientPacketConn) readResponse() error {
  241. response, err := ReadStreamResponse(c.ExtendedConn)
  242. if err != nil {
  243. return err
  244. }
  245. if response.Status == statusError {
  246. return E.New("remote error: ", response.Message)
  247. }
  248. return nil
  249. }
  250. func (c *ClientPacketConn) Read(b []byte) (n int, err error) {
  251. if !c.responseRead {
  252. err = c.readResponse()
  253. if err != nil {
  254. return
  255. }
  256. c.responseRead = true
  257. }
  258. var length uint16
  259. err = binary.Read(c.ExtendedConn, binary.BigEndian, &length)
  260. if err != nil {
  261. return
  262. }
  263. if cap(b) < int(length) {
  264. return 0, io.ErrShortBuffer
  265. }
  266. return io.ReadFull(c.ExtendedConn, b[:length])
  267. }
  268. func (c *ClientPacketConn) writeRequest(payload []byte) (n int, err error) {
  269. request := StreamRequest{
  270. Network: N.NetworkUDP,
  271. Destination: c.destination,
  272. }
  273. rLen := requestLen(request)
  274. if len(payload) > 0 {
  275. rLen += 2 + len(payload)
  276. }
  277. _buffer := buf.StackNewSize(rLen)
  278. defer common.KeepAlive(_buffer)
  279. buffer := common.Dup(_buffer)
  280. defer buffer.Release()
  281. EncodeStreamRequest(request, buffer)
  282. if len(payload) > 0 {
  283. common.Must(
  284. binary.Write(buffer, binary.BigEndian, uint16(len(payload))),
  285. common.Error(buffer.Write(payload)),
  286. )
  287. }
  288. _, err = c.ExtendedConn.Write(buffer.Bytes())
  289. if err != nil {
  290. return
  291. }
  292. c.requestWrite = true
  293. return len(payload), nil
  294. }
  295. func (c *ClientPacketConn) Write(b []byte) (n int, err error) {
  296. if !c.requestWrite {
  297. return c.writeRequest(b)
  298. }
  299. err = binary.Write(c.ExtendedConn, binary.BigEndian, uint16(len(b)))
  300. if err != nil {
  301. return
  302. }
  303. return c.ExtendedConn.Write(b)
  304. }
  305. func (c *ClientPacketConn) ReadBuffer(buffer *buf.Buffer) (err error) {
  306. if !c.responseRead {
  307. err = c.readResponse()
  308. if err != nil {
  309. return
  310. }
  311. c.responseRead = true
  312. }
  313. var length uint16
  314. err = binary.Read(c.ExtendedConn, binary.BigEndian, &length)
  315. if err != nil {
  316. return
  317. }
  318. _, err = buffer.ReadFullFrom(c.ExtendedConn, int(length))
  319. return
  320. }
  321. func (c *ClientPacketConn) WriteBuffer(buffer *buf.Buffer) error {
  322. if !c.requestWrite {
  323. defer buffer.Release()
  324. return common.Error(c.writeRequest(buffer.Bytes()))
  325. }
  326. bLen := buffer.Len()
  327. binary.BigEndian.PutUint16(buffer.ExtendHeader(2), uint16(bLen))
  328. return c.ExtendedConn.WriteBuffer(buffer)
  329. }
  330. func (c *ClientPacketConn) FrontHeadroom() int {
  331. return 2
  332. }
  333. func (c *ClientPacketConn) ReadPacket(buffer *buf.Buffer) (destination M.Socksaddr, err error) {
  334. err = c.ReadBuffer(buffer)
  335. return
  336. }
  337. func (c *ClientPacketConn) WritePacket(buffer *buf.Buffer, destination M.Socksaddr) error {
  338. return c.WriteBuffer(buffer)
  339. }
  340. func (c *ClientPacketConn) LocalAddr() net.Addr {
  341. return c.ExtendedConn.LocalAddr()
  342. }
  343. func (c *ClientPacketConn) RemoteAddr() net.Addr {
  344. return c.destination.UDPAddr()
  345. }
  346. func (c *ClientPacketConn) NeedAdditionalReadDeadline() bool {
  347. return true
  348. }
  349. func (c *ClientPacketConn) Upstream() any {
  350. return c.ExtendedConn
  351. }
  352. var _ N.NetPacketConn = (*ClientPacketAddrConn)(nil)
  353. type ClientPacketAddrConn struct {
  354. N.ExtendedConn
  355. destination M.Socksaddr
  356. requestWrite bool
  357. responseRead bool
  358. }
  359. func (c *ClientPacketAddrConn) readResponse() error {
  360. response, err := ReadStreamResponse(c.ExtendedConn)
  361. if err != nil {
  362. return err
  363. }
  364. if response.Status == statusError {
  365. return E.New("remote error: ", response.Message)
  366. }
  367. return nil
  368. }
  369. func (c *ClientPacketAddrConn) ReadFrom(p []byte) (n int, addr net.Addr, err error) {
  370. if !c.responseRead {
  371. err = c.readResponse()
  372. if err != nil {
  373. return
  374. }
  375. c.responseRead = true
  376. }
  377. destination, err := M.SocksaddrSerializer.ReadAddrPort(c.ExtendedConn)
  378. if err != nil {
  379. return
  380. }
  381. if destination.IsFqdn() {
  382. addr = destination
  383. } else {
  384. addr = destination.UDPAddr()
  385. }
  386. var length uint16
  387. err = binary.Read(c.ExtendedConn, binary.BigEndian, &length)
  388. if err != nil {
  389. return
  390. }
  391. if cap(p) < int(length) {
  392. return 0, nil, io.ErrShortBuffer
  393. }
  394. n, err = io.ReadFull(c.ExtendedConn, p[:length])
  395. return
  396. }
  397. func (c *ClientPacketAddrConn) writeRequest(payload []byte, destination M.Socksaddr) (n int, err error) {
  398. request := StreamRequest{
  399. Network: N.NetworkUDP,
  400. Destination: c.destination,
  401. PacketAddr: true,
  402. }
  403. rLen := requestLen(request)
  404. if len(payload) > 0 {
  405. rLen += M.SocksaddrSerializer.AddrPortLen(destination) + 2 + len(payload)
  406. }
  407. _buffer := buf.StackNewSize(rLen)
  408. defer common.KeepAlive(_buffer)
  409. buffer := common.Dup(_buffer)
  410. defer buffer.Release()
  411. EncodeStreamRequest(request, buffer)
  412. if len(payload) > 0 {
  413. common.Must(
  414. M.SocksaddrSerializer.WriteAddrPort(buffer, destination),
  415. binary.Write(buffer, binary.BigEndian, uint16(len(payload))),
  416. common.Error(buffer.Write(payload)),
  417. )
  418. }
  419. _, err = c.ExtendedConn.Write(buffer.Bytes())
  420. if err != nil {
  421. return
  422. }
  423. c.requestWrite = true
  424. return len(payload), nil
  425. }
  426. func (c *ClientPacketAddrConn) WriteTo(p []byte, addr net.Addr) (n int, err error) {
  427. if !c.requestWrite {
  428. return c.writeRequest(p, M.SocksaddrFromNet(addr))
  429. }
  430. err = M.SocksaddrSerializer.WriteAddrPort(c.ExtendedConn, M.SocksaddrFromNet(addr))
  431. if err != nil {
  432. return
  433. }
  434. err = binary.Write(c.ExtendedConn, binary.BigEndian, uint16(len(p)))
  435. if err != nil {
  436. return
  437. }
  438. return c.ExtendedConn.Write(p)
  439. }
  440. func (c *ClientPacketAddrConn) ReadPacket(buffer *buf.Buffer) (destination M.Socksaddr, err error) {
  441. if !c.responseRead {
  442. err = c.readResponse()
  443. if err != nil {
  444. return
  445. }
  446. c.responseRead = true
  447. }
  448. destination, err = M.SocksaddrSerializer.ReadAddrPort(c.ExtendedConn)
  449. if err != nil {
  450. return
  451. }
  452. var length uint16
  453. err = binary.Read(c.ExtendedConn, binary.BigEndian, &length)
  454. if err != nil {
  455. return
  456. }
  457. _, err = buffer.ReadFullFrom(c.ExtendedConn, int(length))
  458. return
  459. }
  460. func (c *ClientPacketAddrConn) WritePacket(buffer *buf.Buffer, destination M.Socksaddr) error {
  461. if !c.requestWrite {
  462. defer buffer.Release()
  463. return common.Error(c.writeRequest(buffer.Bytes(), destination))
  464. }
  465. bLen := buffer.Len()
  466. header := buf.With(buffer.ExtendHeader(M.SocksaddrSerializer.AddrPortLen(destination) + 2))
  467. common.Must(
  468. M.SocksaddrSerializer.WriteAddrPort(header, destination),
  469. binary.Write(header, binary.BigEndian, uint16(bLen)),
  470. )
  471. return c.ExtendedConn.WriteBuffer(buffer)
  472. }
  473. func (c *ClientPacketAddrConn) LocalAddr() net.Addr {
  474. return c.ExtendedConn.LocalAddr()
  475. }
  476. func (c *ClientPacketAddrConn) FrontHeadroom() int {
  477. return 2 + M.MaxSocksaddrLength
  478. }
  479. func (c *ClientPacketAddrConn) NeedAdditionalReadDeadline() bool {
  480. return true
  481. }
  482. func (c *ClientPacketAddrConn) Upstream() any {
  483. return c.ExtendedConn
  484. }