conn.go 5.7 KB

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