proxy.go 7.9 KB

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