conn.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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. "context"
  17. "crypto/tls"
  18. "errors"
  19. "fmt"
  20. "io"
  21. "net"
  22. "sync/atomic"
  23. "time"
  24. "github.com/fatedier/frp/pkg/util/xlog"
  25. gnet "github.com/fatedier/golib/net"
  26. kcp "github.com/fatedier/kcp-go"
  27. )
  28. type ContextGetter interface {
  29. Context() context.Context
  30. }
  31. type ContextSetter interface {
  32. WithContext(ctx context.Context)
  33. }
  34. func NewLogFromConn(conn net.Conn) *xlog.Logger {
  35. if c, ok := conn.(ContextGetter); ok {
  36. return xlog.FromContextSafe(c.Context())
  37. }
  38. return xlog.New()
  39. }
  40. func NewContextFromConn(conn net.Conn) context.Context {
  41. if c, ok := conn.(ContextGetter); ok {
  42. return c.Context()
  43. }
  44. return context.Background()
  45. }
  46. // ContextConn is the connection with context
  47. type ContextConn struct {
  48. net.Conn
  49. ctx context.Context
  50. }
  51. func NewContextConn(ctx context.Context, c net.Conn) *ContextConn {
  52. return &ContextConn{
  53. Conn: c,
  54. ctx: ctx,
  55. }
  56. }
  57. func (c *ContextConn) WithContext(ctx context.Context) {
  58. c.ctx = ctx
  59. }
  60. func (c *ContextConn) Context() context.Context {
  61. return c.ctx
  62. }
  63. type WrapReadWriteCloserConn struct {
  64. io.ReadWriteCloser
  65. underConn net.Conn
  66. }
  67. func WrapReadWriteCloserToConn(rwc io.ReadWriteCloser, underConn net.Conn) net.Conn {
  68. return &WrapReadWriteCloserConn{
  69. ReadWriteCloser: rwc,
  70. underConn: underConn,
  71. }
  72. }
  73. func (conn *WrapReadWriteCloserConn) LocalAddr() net.Addr {
  74. if conn.underConn != nil {
  75. return conn.underConn.LocalAddr()
  76. }
  77. return (*net.TCPAddr)(nil)
  78. }
  79. func (conn *WrapReadWriteCloserConn) RemoteAddr() net.Addr {
  80. if conn.underConn != nil {
  81. return conn.underConn.RemoteAddr()
  82. }
  83. return (*net.TCPAddr)(nil)
  84. }
  85. func (conn *WrapReadWriteCloserConn) SetDeadline(t time.Time) error {
  86. if conn.underConn != nil {
  87. return conn.underConn.SetDeadline(t)
  88. }
  89. return &net.OpError{Op: "set", Net: "wrap", Source: nil, Addr: nil, Err: errors.New("deadline not supported")}
  90. }
  91. func (conn *WrapReadWriteCloserConn) SetReadDeadline(t time.Time) error {
  92. if conn.underConn != nil {
  93. return conn.underConn.SetReadDeadline(t)
  94. }
  95. return &net.OpError{Op: "set", Net: "wrap", Source: nil, Addr: nil, Err: errors.New("deadline not supported")}
  96. }
  97. func (conn *WrapReadWriteCloserConn) SetWriteDeadline(t time.Time) error {
  98. if conn.underConn != nil {
  99. return conn.underConn.SetWriteDeadline(t)
  100. }
  101. return &net.OpError{Op: "set", Net: "wrap", Source: nil, Addr: nil, Err: errors.New("deadline not supported")}
  102. }
  103. type CloseNotifyConn struct {
  104. net.Conn
  105. // 1 means closed
  106. closeFlag int32
  107. closeFn func()
  108. }
  109. // closeFn will be only called once
  110. func WrapCloseNotifyConn(c net.Conn, closeFn func()) net.Conn {
  111. return &CloseNotifyConn{
  112. Conn: c,
  113. closeFn: closeFn,
  114. }
  115. }
  116. func (cc *CloseNotifyConn) Close() (err error) {
  117. pflag := atomic.SwapInt32(&cc.closeFlag, 1)
  118. if pflag == 0 {
  119. err = cc.Close()
  120. if cc.closeFn != nil {
  121. cc.closeFn()
  122. }
  123. }
  124. return
  125. }
  126. type StatsConn struct {
  127. net.Conn
  128. closed int64 // 1 means closed
  129. totalRead int64
  130. totalWrite int64
  131. statsFunc func(totalRead, totalWrite int64)
  132. }
  133. func WrapStatsConn(conn net.Conn, statsFunc func(total, totalWrite int64)) *StatsConn {
  134. return &StatsConn{
  135. Conn: conn,
  136. statsFunc: statsFunc,
  137. }
  138. }
  139. func (statsConn *StatsConn) Read(p []byte) (n int, err error) {
  140. n, err = statsConn.Conn.Read(p)
  141. statsConn.totalRead += int64(n)
  142. return
  143. }
  144. func (statsConn *StatsConn) Write(p []byte) (n int, err error) {
  145. n, err = statsConn.Conn.Write(p)
  146. statsConn.totalWrite += int64(n)
  147. return
  148. }
  149. func (statsConn *StatsConn) Close() (err error) {
  150. old := atomic.SwapInt64(&statsConn.closed, 1)
  151. if old != 1 {
  152. err = statsConn.Conn.Close()
  153. if statsConn.statsFunc != nil {
  154. statsConn.statsFunc(statsConn.totalRead, statsConn.totalWrite)
  155. }
  156. }
  157. return
  158. }
  159. func ConnectServer(protocol string, addr string) (c net.Conn, err error) {
  160. switch protocol {
  161. case "tcp":
  162. return net.Dial("tcp", addr)
  163. case "kcp":
  164. kcpConn, errRet := kcp.DialWithOptions(addr, nil, 10, 3)
  165. if errRet != nil {
  166. err = errRet
  167. return
  168. }
  169. kcpConn.SetStreamMode(true)
  170. kcpConn.SetWriteDelay(true)
  171. kcpConn.SetNoDelay(1, 20, 2, 1)
  172. kcpConn.SetWindowSize(128, 512)
  173. kcpConn.SetMtu(1350)
  174. kcpConn.SetACKNoDelay(false)
  175. kcpConn.SetReadBuffer(4194304)
  176. kcpConn.SetWriteBuffer(4194304)
  177. c = kcpConn
  178. return
  179. default:
  180. return nil, fmt.Errorf("unsupport protocol: %s", protocol)
  181. }
  182. }
  183. func ConnectServerByProxy(proxyURL string, protocol string, addr string) (c net.Conn, err error) {
  184. switch protocol {
  185. case "tcp":
  186. return gnet.DialTcpByProxy(proxyURL, addr)
  187. case "kcp":
  188. // http proxy is not supported for kcp
  189. return ConnectServer(protocol, addr)
  190. case "websocket":
  191. return ConnectWebsocketServer(addr)
  192. default:
  193. return nil, fmt.Errorf("unsupport protocol: %s", protocol)
  194. }
  195. }
  196. func ConnectServerByProxyWithTLS(proxyURL string, protocol string, addr string, tlsConfig *tls.Config) (c net.Conn, err error) {
  197. c, err = ConnectServerByProxy(proxyURL, protocol, addr)
  198. if err != nil {
  199. return
  200. }
  201. if tlsConfig == nil {
  202. return
  203. }
  204. c = WrapTLSClientConn(c, tlsConfig)
  205. return
  206. }