conn.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. // Copyright 2016 fatedier, fatedier@gmail.com
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package net
  15. import (
  16. "bytes"
  17. "errors"
  18. "fmt"
  19. "io"
  20. "net"
  21. "sync"
  22. "sync/atomic"
  23. "time"
  24. "github.com/fatedier/frp/utils/log"
  25. kcp "github.com/xtaci/kcp-go"
  26. )
  27. // Conn is the interface of connections used in frp.
  28. type Conn interface {
  29. net.Conn
  30. log.Logger
  31. }
  32. type WrapLogConn struct {
  33. net.Conn
  34. log.Logger
  35. }
  36. func WrapConn(c net.Conn) Conn {
  37. return &WrapLogConn{
  38. Conn: c,
  39. Logger: log.NewPrefixLogger(""),
  40. }
  41. }
  42. type WrapReadWriteCloserConn struct {
  43. io.ReadWriteCloser
  44. log.Logger
  45. underConn net.Conn
  46. }
  47. func WrapReadWriteCloserToConn(rwc io.ReadWriteCloser, underConn net.Conn) Conn {
  48. return &WrapReadWriteCloserConn{
  49. ReadWriteCloser: rwc,
  50. Logger: log.NewPrefixLogger(""),
  51. underConn: underConn,
  52. }
  53. }
  54. func (conn *WrapReadWriteCloserConn) LocalAddr() net.Addr {
  55. if conn.underConn != nil {
  56. return conn.underConn.LocalAddr()
  57. }
  58. return (*net.TCPAddr)(nil)
  59. }
  60. func (conn *WrapReadWriteCloserConn) RemoteAddr() net.Addr {
  61. if conn.underConn != nil {
  62. return conn.underConn.RemoteAddr()
  63. }
  64. return (*net.TCPAddr)(nil)
  65. }
  66. func (conn *WrapReadWriteCloserConn) SetDeadline(t time.Time) error {
  67. if conn.underConn != nil {
  68. return conn.underConn.SetDeadline(t)
  69. }
  70. return &net.OpError{Op: "set", Net: "wrap", Source: nil, Addr: nil, Err: errors.New("deadline not supported")}
  71. }
  72. func (conn *WrapReadWriteCloserConn) SetReadDeadline(t time.Time) error {
  73. if conn.underConn != nil {
  74. return conn.underConn.SetReadDeadline(t)
  75. }
  76. return &net.OpError{Op: "set", Net: "wrap", Source: nil, Addr: nil, Err: errors.New("deadline not supported")}
  77. }
  78. func (conn *WrapReadWriteCloserConn) SetWriteDeadline(t time.Time) error {
  79. if conn.underConn != nil {
  80. return conn.underConn.SetWriteDeadline(t)
  81. }
  82. return &net.OpError{Op: "set", Net: "wrap", Source: nil, Addr: nil, Err: errors.New("deadline not supported")}
  83. }
  84. func ConnectServer(protocol string, addr string) (c Conn, err error) {
  85. switch protocol {
  86. case "tcp":
  87. return ConnectTcpServer(addr)
  88. case "kcp":
  89. kcpConn, errRet := kcp.DialWithOptions(addr, nil, 10, 3)
  90. if errRet != nil {
  91. err = errRet
  92. return
  93. }
  94. kcpConn.SetStreamMode(true)
  95. kcpConn.SetWriteDelay(true)
  96. kcpConn.SetNoDelay(1, 20, 2, 1)
  97. kcpConn.SetWindowSize(128, 512)
  98. kcpConn.SetMtu(1350)
  99. kcpConn.SetACKNoDelay(false)
  100. kcpConn.SetReadBuffer(4194304)
  101. kcpConn.SetWriteBuffer(4194304)
  102. c = WrapConn(kcpConn)
  103. return
  104. default:
  105. return nil, fmt.Errorf("unsupport protocol: %s", protocol)
  106. }
  107. }
  108. func ConnectServerByHttpProxy(httpProxy string, protocol string, addr string) (c Conn, err error) {
  109. switch protocol {
  110. case "tcp":
  111. return ConnectTcpServerByHttpProxy(httpProxy, addr)
  112. case "kcp":
  113. // http proxy is not supported for kcp
  114. return ConnectServer(protocol, addr)
  115. default:
  116. return nil, fmt.Errorf("unsupport protocol: %s", protocol)
  117. }
  118. }
  119. type SharedConn struct {
  120. Conn
  121. sync.Mutex
  122. buf *bytes.Buffer
  123. }
  124. // the bytes you read in io.Reader, will be reserved in SharedConn
  125. func NewShareConn(conn Conn) (*SharedConn, io.Reader) {
  126. sc := &SharedConn{
  127. Conn: conn,
  128. buf: bytes.NewBuffer(make([]byte, 0, 1024)),
  129. }
  130. return sc, io.TeeReader(conn, sc.buf)
  131. }
  132. func (sc *SharedConn) Read(p []byte) (n int, err error) {
  133. sc.Lock()
  134. if sc.buf == nil {
  135. sc.Unlock()
  136. return sc.Conn.Read(p)
  137. }
  138. sc.Unlock()
  139. n, err = sc.buf.Read(p)
  140. if err == io.EOF {
  141. sc.Lock()
  142. sc.buf = nil
  143. sc.Unlock()
  144. var n2 int
  145. n2, err = sc.Conn.Read(p[n:])
  146. n += n2
  147. }
  148. return
  149. }
  150. func (sc *SharedConn) WriteBuff(buffer []byte) (err error) {
  151. sc.buf.Reset()
  152. _, err = sc.buf.Write(buffer)
  153. return err
  154. }
  155. type StatsConn struct {
  156. Conn
  157. closed int64 // 1 means closed
  158. totalRead int64
  159. totalWrite int64
  160. statsFunc func(totalRead, totalWrite int64)
  161. }
  162. func WrapStatsConn(conn Conn, statsFunc func(total, totalWrite int64)) *StatsConn {
  163. return &StatsConn{
  164. Conn: conn,
  165. statsFunc: statsFunc,
  166. }
  167. }
  168. func (statsConn *StatsConn) Read(p []byte) (n int, err error) {
  169. n, err = statsConn.Conn.Read(p)
  170. statsConn.totalRead += int64(n)
  171. return
  172. }
  173. func (statsConn *StatsConn) Write(p []byte) (n int, err error) {
  174. n, err = statsConn.Conn.Write(p)
  175. statsConn.totalWrite += int64(n)
  176. return
  177. }
  178. func (statsConn *StatsConn) Close() (err error) {
  179. old := atomic.SwapInt64(&statsConn.closed, 1)
  180. if old != 1 {
  181. err = statsConn.Conn.Close()
  182. if statsConn.statsFunc != nil {
  183. statsConn.statsFunc(statsConn.totalRead, statsConn.totalWrite)
  184. }
  185. }
  186. return
  187. }