proxy.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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. defer conn.Close()
  95. HandleTcpWorkConnection(&pxy.cfg.LocalSvrConf, pxy.proxyPlugin, &pxy.cfg.BaseProxyConf, conn)
  96. }
  97. // HTTP
  98. type HttpProxy struct {
  99. BaseProxy
  100. cfg *config.HttpProxyConf
  101. proxyPlugin plugin.Plugin
  102. }
  103. func (pxy *HttpProxy) Run() (err error) {
  104. if pxy.cfg.Plugin != "" {
  105. pxy.proxyPlugin, err = plugin.Create(pxy.cfg.Plugin, pxy.cfg.PluginParams)
  106. if err != nil {
  107. return
  108. }
  109. }
  110. return
  111. }
  112. func (pxy *HttpProxy) Close() {
  113. if pxy.proxyPlugin != nil {
  114. pxy.proxyPlugin.Close()
  115. }
  116. }
  117. func (pxy *HttpProxy) InWorkConn(conn frpNet.Conn) {
  118. defer conn.Close()
  119. HandleTcpWorkConnection(&pxy.cfg.LocalSvrConf, pxy.proxyPlugin, &pxy.cfg.BaseProxyConf, conn)
  120. }
  121. // HTTPS
  122. type HttpsProxy struct {
  123. BaseProxy
  124. cfg *config.HttpsProxyConf
  125. proxyPlugin plugin.Plugin
  126. }
  127. func (pxy *HttpsProxy) Run() (err error) {
  128. if pxy.cfg.Plugin != "" {
  129. pxy.proxyPlugin, err = plugin.Create(pxy.cfg.Plugin, pxy.cfg.PluginParams)
  130. if err != nil {
  131. return
  132. }
  133. }
  134. return
  135. }
  136. func (pxy *HttpsProxy) Close() {
  137. if pxy.proxyPlugin != nil {
  138. pxy.proxyPlugin.Close()
  139. }
  140. }
  141. func (pxy *HttpsProxy) InWorkConn(conn frpNet.Conn) {
  142. defer conn.Close()
  143. HandleTcpWorkConnection(&pxy.cfg.LocalSvrConf, pxy.proxyPlugin, &pxy.cfg.BaseProxyConf, conn)
  144. }
  145. // UDP
  146. type UdpProxy struct {
  147. BaseProxy
  148. cfg *config.UdpProxyConf
  149. localAddr *net.UDPAddr
  150. readCh chan *msg.UdpPacket
  151. // include msg.UdpPacket and msg.Ping
  152. sendCh chan msg.Message
  153. workConn frpNet.Conn
  154. }
  155. func (pxy *UdpProxy) Run() (err error) {
  156. pxy.localAddr, err = net.ResolveUDPAddr("udp", fmt.Sprintf("%s:%d", pxy.cfg.LocalIp, pxy.cfg.LocalPort))
  157. if err != nil {
  158. return
  159. }
  160. return
  161. }
  162. func (pxy *UdpProxy) Close() {
  163. pxy.mu.Lock()
  164. defer pxy.mu.Unlock()
  165. if !pxy.closed {
  166. pxy.closed = true
  167. if pxy.workConn != nil {
  168. pxy.workConn.Close()
  169. }
  170. if pxy.readCh != nil {
  171. close(pxy.readCh)
  172. }
  173. if pxy.sendCh != nil {
  174. close(pxy.sendCh)
  175. }
  176. }
  177. }
  178. func (pxy *UdpProxy) InWorkConn(conn frpNet.Conn) {
  179. pxy.Info("incoming a new work connection for udp proxy, %s", conn.RemoteAddr().String())
  180. // close resources releated with old workConn
  181. pxy.Close()
  182. pxy.mu.Lock()
  183. pxy.workConn = conn
  184. pxy.readCh = make(chan *msg.UdpPacket, 1024)
  185. pxy.sendCh = make(chan msg.Message, 1024)
  186. pxy.closed = false
  187. pxy.mu.Unlock()
  188. workConnReaderFn := func(conn net.Conn, readCh chan *msg.UdpPacket) {
  189. for {
  190. var udpMsg msg.UdpPacket
  191. if errRet := msg.ReadMsgInto(conn, &udpMsg); errRet != nil {
  192. pxy.Warn("read from workConn for udp error: %v", errRet)
  193. return
  194. }
  195. if errRet := errors.PanicToError(func() {
  196. pxy.Trace("get udp package from workConn: %s", udpMsg.Content)
  197. readCh <- &udpMsg
  198. }); errRet != nil {
  199. pxy.Info("reader goroutine for udp work connection closed: %v", errRet)
  200. return
  201. }
  202. }
  203. }
  204. workConnSenderFn := func(conn net.Conn, sendCh chan msg.Message) {
  205. defer func() {
  206. pxy.Info("writer goroutine for udp work connection closed")
  207. }()
  208. var errRet error
  209. for rawMsg := range sendCh {
  210. switch m := rawMsg.(type) {
  211. case *msg.UdpPacket:
  212. pxy.Trace("send udp package to workConn: %s", m.Content)
  213. case *msg.Ping:
  214. pxy.Trace("send ping message to udp workConn")
  215. }
  216. if errRet = msg.WriteMsg(conn, rawMsg); errRet != nil {
  217. pxy.Error("udp work write error: %v", errRet)
  218. return
  219. }
  220. }
  221. }
  222. heartbeatFn := func(conn net.Conn, sendCh chan msg.Message) {
  223. var errRet error
  224. for {
  225. time.Sleep(time.Duration(30) * time.Second)
  226. if errRet = errors.PanicToError(func() {
  227. sendCh <- &msg.Ping{}
  228. }); errRet != nil {
  229. pxy.Trace("heartbeat goroutine for udp work connection closed")
  230. break
  231. }
  232. }
  233. }
  234. go workConnSenderFn(pxy.workConn, pxy.sendCh)
  235. go workConnReaderFn(pxy.workConn, pxy.readCh)
  236. go heartbeatFn(pxy.workConn, pxy.sendCh)
  237. udp.Forwarder(pxy.localAddr, pxy.readCh, pxy.sendCh)
  238. }
  239. // Common handler for tcp work connections.
  240. func HandleTcpWorkConnection(localInfo *config.LocalSvrConf, proxyPlugin plugin.Plugin,
  241. baseInfo *config.BaseProxyConf, workConn frpNet.Conn) {
  242. var (
  243. remote io.ReadWriteCloser
  244. err error
  245. )
  246. remote = workConn
  247. if baseInfo.UseEncryption {
  248. remote, err = tcp.WithEncryption(remote, []byte(config.ClientCommonCfg.PrivilegeToken))
  249. if err != nil {
  250. workConn.Error("create encryption stream error: %v", err)
  251. return
  252. }
  253. }
  254. if baseInfo.UseCompression {
  255. remote = tcp.WithCompression(remote)
  256. }
  257. if proxyPlugin != nil {
  258. // if plugin is set, let plugin handle connections first
  259. workConn.Debug("handle by plugin: %s", proxyPlugin.Name())
  260. proxyPlugin.Handle(remote)
  261. workConn.Debug("handle by plugin finished")
  262. return
  263. } else {
  264. localConn, err := frpNet.ConnectTcpServer(fmt.Sprintf("%s:%d", localInfo.LocalIp, localInfo.LocalPort))
  265. if err != nil {
  266. workConn.Error("connect to local service [%s:%d] error: %v", localInfo.LocalIp, localInfo.LocalPort, err)
  267. return
  268. }
  269. workConn.Debug("join connections, localConn(l[%s] r[%s]) workConn(l[%s] r[%s])", localConn.LocalAddr().String(),
  270. localConn.RemoteAddr().String(), workConn.LocalAddr().String(), workConn.RemoteAddr().String())
  271. tcp.Join(localConn, remote)
  272. workConn.Debug("join connections closed")
  273. }
  274. }