proxy.go 7.3 KB

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