proxy.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. // Copyright 2017 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 client
  15. import (
  16. "fmt"
  17. "io"
  18. "net"
  19. "sync"
  20. "time"
  21. "github.com/fatedier/frp/models/config"
  22. "github.com/fatedier/frp/models/msg"
  23. "github.com/fatedier/frp/models/proto/tcp"
  24. "github.com/fatedier/frp/models/proto/udp"
  25. "github.com/fatedier/frp/utils/errors"
  26. "github.com/fatedier/frp/utils/log"
  27. frpNet "github.com/fatedier/frp/utils/net"
  28. )
  29. // Proxy defines how to work for different proxy type.
  30. type Proxy interface {
  31. Run() error
  32. // InWorkConn accept work connections registered to server.
  33. InWorkConn(conn frpNet.Conn)
  34. Close()
  35. log.Logger
  36. }
  37. func NewProxy(ctl *Control, pxyConf config.ProxyConf) (pxy Proxy) {
  38. baseProxy := BaseProxy{
  39. ctl: ctl,
  40. Logger: log.NewPrefixLogger(pxyConf.GetName()),
  41. }
  42. switch cfg := pxyConf.(type) {
  43. case *config.TcpProxyConf:
  44. pxy = &TcpProxy{
  45. BaseProxy: baseProxy,
  46. cfg: cfg,
  47. }
  48. case *config.UdpProxyConf:
  49. pxy = &UdpProxy{
  50. BaseProxy: baseProxy,
  51. cfg: cfg,
  52. }
  53. case *config.HttpProxyConf:
  54. pxy = &HttpProxy{
  55. BaseProxy: baseProxy,
  56. cfg: cfg,
  57. }
  58. case *config.HttpsProxyConf:
  59. pxy = &HttpsProxy{
  60. BaseProxy: baseProxy,
  61. cfg: cfg,
  62. }
  63. }
  64. return
  65. }
  66. type BaseProxy struct {
  67. ctl *Control
  68. closed bool
  69. mu sync.RWMutex
  70. log.Logger
  71. }
  72. // TCP
  73. type TcpProxy struct {
  74. BaseProxy
  75. cfg *config.TcpProxyConf
  76. }
  77. func (pxy *TcpProxy) Run() (err error) {
  78. return
  79. }
  80. func (pxy *TcpProxy) Close() {
  81. }
  82. func (pxy *TcpProxy) InWorkConn(conn frpNet.Conn) {
  83. defer conn.Close()
  84. HandleTcpWorkConnection(&pxy.cfg.LocalSvrConf, &pxy.cfg.BaseProxyConf, conn)
  85. }
  86. // HTTP
  87. type HttpProxy struct {
  88. BaseProxy
  89. cfg *config.HttpProxyConf
  90. }
  91. func (pxy *HttpProxy) Run() (err error) {
  92. return
  93. }
  94. func (pxy *HttpProxy) Close() {
  95. }
  96. func (pxy *HttpProxy) InWorkConn(conn frpNet.Conn) {
  97. defer conn.Close()
  98. HandleTcpWorkConnection(&pxy.cfg.LocalSvrConf, &pxy.cfg.BaseProxyConf, conn)
  99. }
  100. // HTTPS
  101. type HttpsProxy struct {
  102. BaseProxy
  103. cfg *config.HttpsProxyConf
  104. }
  105. func (pxy *HttpsProxy) Run() (err error) {
  106. return
  107. }
  108. func (pxy *HttpsProxy) Close() {
  109. }
  110. func (pxy *HttpsProxy) InWorkConn(conn frpNet.Conn) {
  111. defer conn.Close()
  112. HandleTcpWorkConnection(&pxy.cfg.LocalSvrConf, &pxy.cfg.BaseProxyConf, conn)
  113. }
  114. // UDP
  115. type UdpProxy struct {
  116. BaseProxy
  117. cfg *config.UdpProxyConf
  118. localAddr *net.UDPAddr
  119. readCh chan *msg.UdpPacket
  120. // include msg.UdpPacket and msg.Ping
  121. sendCh chan msg.Message
  122. workConn frpNet.Conn
  123. }
  124. func (pxy *UdpProxy) Run() (err error) {
  125. pxy.localAddr, err = net.ResolveUDPAddr("udp", fmt.Sprintf("%s:%d", pxy.cfg.LocalIp, pxy.cfg.LocalPort))
  126. if err != nil {
  127. return
  128. }
  129. return
  130. }
  131. func (pxy *UdpProxy) Close() {
  132. pxy.mu.Lock()
  133. defer pxy.mu.Unlock()
  134. if !pxy.closed {
  135. pxy.closed = true
  136. if pxy.workConn != nil {
  137. pxy.workConn.Close()
  138. }
  139. if pxy.readCh != nil {
  140. close(pxy.readCh)
  141. }
  142. if pxy.sendCh != nil {
  143. close(pxy.sendCh)
  144. }
  145. }
  146. }
  147. func (pxy *UdpProxy) InWorkConn(conn frpNet.Conn) {
  148. pxy.Info("incoming a new work connection for udp proxy, %s", conn.RemoteAddr().String())
  149. // close resources releated with old workConn
  150. pxy.Close()
  151. pxy.mu.Lock()
  152. pxy.workConn = conn
  153. pxy.readCh = make(chan *msg.UdpPacket, 1024)
  154. pxy.sendCh = make(chan msg.Message, 1024)
  155. pxy.closed = false
  156. pxy.mu.Unlock()
  157. workConnReaderFn := func(conn net.Conn, readCh chan *msg.UdpPacket) {
  158. for {
  159. var udpMsg msg.UdpPacket
  160. if errRet := msg.ReadMsgInto(conn, &udpMsg); errRet != nil {
  161. pxy.Warn("read from workConn for udp error: %v", errRet)
  162. return
  163. }
  164. if errRet := errors.PanicToError(func() {
  165. pxy.Trace("get udp package from workConn: %s", udpMsg.Content)
  166. readCh <- &udpMsg
  167. }); errRet != nil {
  168. pxy.Info("reader goroutine for udp work connection closed: %v", errRet)
  169. return
  170. }
  171. }
  172. }
  173. workConnSenderFn := func(conn net.Conn, sendCh chan msg.Message) {
  174. defer func() {
  175. pxy.Info("writer goroutine for udp work connection closed")
  176. }()
  177. var errRet error
  178. for rawMsg := range sendCh {
  179. switch m := rawMsg.(type) {
  180. case *msg.UdpPacket:
  181. pxy.Trace("send udp package to workConn: %s", m.Content)
  182. case *msg.Ping:
  183. pxy.Trace("send ping message to udp workConn")
  184. }
  185. if errRet = msg.WriteMsg(conn, rawMsg); errRet != nil {
  186. pxy.Error("udp work write error: %v", errRet)
  187. return
  188. }
  189. }
  190. }
  191. heartbeatFn := func(conn net.Conn, sendCh chan msg.Message) {
  192. var errRet error
  193. for {
  194. time.Sleep(time.Duration(30) * time.Second)
  195. if errRet = errors.PanicToError(func() {
  196. sendCh <- &msg.Ping{}
  197. }); errRet != nil {
  198. pxy.Trace("heartbeat goroutine for udp work connection closed")
  199. }
  200. }
  201. }
  202. go workConnSenderFn(pxy.workConn, pxy.sendCh)
  203. go workConnReaderFn(pxy.workConn, pxy.readCh)
  204. go heartbeatFn(pxy.workConn, pxy.sendCh)
  205. udp.Forwarder(pxy.localAddr, pxy.readCh, pxy.sendCh)
  206. }
  207. // Common handler for tcp work connections.
  208. func HandleTcpWorkConnection(localInfo *config.LocalSvrConf, baseInfo *config.BaseProxyConf, workConn frpNet.Conn) {
  209. localConn, err := frpNet.ConnectTcpServer(fmt.Sprintf("%s:%d", localInfo.LocalIp, localInfo.LocalPort))
  210. if err != nil {
  211. workConn.Error("connect to local service [%s:%d] error: %v", localInfo.LocalIp, localInfo.LocalPort, err)
  212. return
  213. }
  214. var remote io.ReadWriteCloser
  215. remote = workConn
  216. if baseInfo.UseEncryption {
  217. remote, err = tcp.WithEncryption(remote, []byte(config.ClientCommonCfg.PrivilegeToken))
  218. if err != nil {
  219. workConn.Error("create encryption stream error: %v", err)
  220. return
  221. }
  222. }
  223. if baseInfo.UseCompression {
  224. remote = tcp.WithCompression(remote)
  225. }
  226. workConn.Debug("join connections, localConn(l[%s] r[%s]) workConn(l[%s] r[%s])", localConn.LocalAddr().String(),
  227. localConn.RemoteAddr().String(), workConn.LocalAddr().String(), workConn.RemoteAddr().String())
  228. tcp.Join(localConn, remote)
  229. workConn.Debug("join connections closed")
  230. }