proxy.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  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 proxy
  15. import (
  16. "bytes"
  17. "fmt"
  18. "io"
  19. "net"
  20. "sync"
  21. "time"
  22. "github.com/fatedier/frp/g"
  23. "github.com/fatedier/frp/models/config"
  24. "github.com/fatedier/frp/models/msg"
  25. "github.com/fatedier/frp/models/plugin"
  26. "github.com/fatedier/frp/models/proto/udp"
  27. "github.com/fatedier/frp/utils/log"
  28. frpNet "github.com/fatedier/frp/utils/net"
  29. "github.com/fatedier/golib/errors"
  30. frpIo "github.com/fatedier/golib/io"
  31. "github.com/fatedier/golib/pool"
  32. )
  33. // Proxy defines how to handle work connections for different proxy type.
  34. type Proxy interface {
  35. Run() error
  36. // InWorkConn accept work connections registered to server.
  37. InWorkConn(conn frpNet.Conn)
  38. Close()
  39. log.Logger
  40. }
  41. func NewProxy(pxyConf config.ProxyConf) (pxy Proxy) {
  42. baseProxy := BaseProxy{
  43. Logger: log.NewPrefixLogger(pxyConf.GetBaseInfo().ProxyName),
  44. }
  45. switch cfg := pxyConf.(type) {
  46. case *config.TcpProxyConf:
  47. pxy = &TcpProxy{
  48. BaseProxy: &baseProxy,
  49. cfg: cfg,
  50. }
  51. case *config.UdpProxyConf:
  52. pxy = &UdpProxy{
  53. BaseProxy: &baseProxy,
  54. cfg: cfg,
  55. }
  56. case *config.HttpProxyConf:
  57. pxy = &HttpProxy{
  58. BaseProxy: &baseProxy,
  59. cfg: cfg,
  60. }
  61. case *config.HttpsProxyConf:
  62. pxy = &HttpsProxy{
  63. BaseProxy: &baseProxy,
  64. cfg: cfg,
  65. }
  66. case *config.StcpProxyConf:
  67. pxy = &StcpProxy{
  68. BaseProxy: &baseProxy,
  69. cfg: cfg,
  70. }
  71. case *config.XtcpProxyConf:
  72. pxy = &XtcpProxy{
  73. BaseProxy: &baseProxy,
  74. cfg: cfg,
  75. }
  76. }
  77. return
  78. }
  79. type BaseProxy struct {
  80. closed bool
  81. mu sync.RWMutex
  82. log.Logger
  83. }
  84. // TCP
  85. type TcpProxy struct {
  86. *BaseProxy
  87. cfg *config.TcpProxyConf
  88. proxyPlugin plugin.Plugin
  89. }
  90. func (pxy *TcpProxy) Run() (err error) {
  91. if pxy.cfg.Plugin != "" {
  92. pxy.proxyPlugin, err = plugin.Create(pxy.cfg.Plugin, pxy.cfg.PluginParams)
  93. if err != nil {
  94. return
  95. }
  96. }
  97. return
  98. }
  99. func (pxy *TcpProxy) Close() {
  100. if pxy.proxyPlugin != nil {
  101. pxy.proxyPlugin.Close()
  102. }
  103. }
  104. func (pxy *TcpProxy) InWorkConn(conn frpNet.Conn) {
  105. HandleTcpWorkConnection(&pxy.cfg.LocalSvrConf, pxy.proxyPlugin, &pxy.cfg.BaseProxyConf, conn,
  106. []byte(g.GlbClientCfg.Token))
  107. }
  108. // HTTP
  109. type HttpProxy struct {
  110. *BaseProxy
  111. cfg *config.HttpProxyConf
  112. proxyPlugin plugin.Plugin
  113. }
  114. func (pxy *HttpProxy) Run() (err error) {
  115. if pxy.cfg.Plugin != "" {
  116. pxy.proxyPlugin, err = plugin.Create(pxy.cfg.Plugin, pxy.cfg.PluginParams)
  117. if err != nil {
  118. return
  119. }
  120. }
  121. return
  122. }
  123. func (pxy *HttpProxy) Close() {
  124. if pxy.proxyPlugin != nil {
  125. pxy.proxyPlugin.Close()
  126. }
  127. }
  128. func (pxy *HttpProxy) InWorkConn(conn frpNet.Conn) {
  129. HandleTcpWorkConnection(&pxy.cfg.LocalSvrConf, pxy.proxyPlugin, &pxy.cfg.BaseProxyConf, conn,
  130. []byte(g.GlbClientCfg.Token))
  131. }
  132. // HTTPS
  133. type HttpsProxy struct {
  134. *BaseProxy
  135. cfg *config.HttpsProxyConf
  136. proxyPlugin plugin.Plugin
  137. }
  138. func (pxy *HttpsProxy) Run() (err error) {
  139. if pxy.cfg.Plugin != "" {
  140. pxy.proxyPlugin, err = plugin.Create(pxy.cfg.Plugin, pxy.cfg.PluginParams)
  141. if err != nil {
  142. return
  143. }
  144. }
  145. return
  146. }
  147. func (pxy *HttpsProxy) Close() {
  148. if pxy.proxyPlugin != nil {
  149. pxy.proxyPlugin.Close()
  150. }
  151. }
  152. func (pxy *HttpsProxy) InWorkConn(conn frpNet.Conn) {
  153. HandleTcpWorkConnection(&pxy.cfg.LocalSvrConf, pxy.proxyPlugin, &pxy.cfg.BaseProxyConf, conn,
  154. []byte(g.GlbClientCfg.Token))
  155. }
  156. // STCP
  157. type StcpProxy struct {
  158. *BaseProxy
  159. cfg *config.StcpProxyConf
  160. proxyPlugin plugin.Plugin
  161. }
  162. func (pxy *StcpProxy) Run() (err error) {
  163. if pxy.cfg.Plugin != "" {
  164. pxy.proxyPlugin, err = plugin.Create(pxy.cfg.Plugin, pxy.cfg.PluginParams)
  165. if err != nil {
  166. return
  167. }
  168. }
  169. return
  170. }
  171. func (pxy *StcpProxy) Close() {
  172. if pxy.proxyPlugin != nil {
  173. pxy.proxyPlugin.Close()
  174. }
  175. }
  176. func (pxy *StcpProxy) InWorkConn(conn frpNet.Conn) {
  177. HandleTcpWorkConnection(&pxy.cfg.LocalSvrConf, pxy.proxyPlugin, &pxy.cfg.BaseProxyConf, conn,
  178. []byte(g.GlbClientCfg.Token))
  179. }
  180. // XTCP
  181. type XtcpProxy struct {
  182. *BaseProxy
  183. cfg *config.XtcpProxyConf
  184. proxyPlugin plugin.Plugin
  185. }
  186. func (pxy *XtcpProxy) Run() (err error) {
  187. if pxy.cfg.Plugin != "" {
  188. pxy.proxyPlugin, err = plugin.Create(pxy.cfg.Plugin, pxy.cfg.PluginParams)
  189. if err != nil {
  190. return
  191. }
  192. }
  193. return
  194. }
  195. func (pxy *XtcpProxy) Close() {
  196. if pxy.proxyPlugin != nil {
  197. pxy.proxyPlugin.Close()
  198. }
  199. }
  200. func (pxy *XtcpProxy) InWorkConn(conn frpNet.Conn) {
  201. defer conn.Close()
  202. var natHoleSidMsg msg.NatHoleSid
  203. err := msg.ReadMsgInto(conn, &natHoleSidMsg)
  204. if err != nil {
  205. pxy.Error("xtcp read from workConn error: %v", err)
  206. return
  207. }
  208. natHoleClientMsg := &msg.NatHoleClient{
  209. ProxyName: pxy.cfg.ProxyName,
  210. Sid: natHoleSidMsg.Sid,
  211. }
  212. raddr, _ := net.ResolveUDPAddr("udp",
  213. fmt.Sprintf("%s:%d", g.GlbClientCfg.ServerAddr, g.GlbClientCfg.ServerUdpPort))
  214. clientConn, err := net.DialUDP("udp", nil, raddr)
  215. defer clientConn.Close()
  216. err = msg.WriteMsg(clientConn, natHoleClientMsg)
  217. if err != nil {
  218. pxy.Error("send natHoleClientMsg to server error: %v", err)
  219. return
  220. }
  221. // Wait for client address at most 5 seconds.
  222. var natHoleRespMsg msg.NatHoleResp
  223. clientConn.SetReadDeadline(time.Now().Add(5 * time.Second))
  224. buf := pool.GetBuf(1024)
  225. n, err := clientConn.Read(buf)
  226. if err != nil {
  227. pxy.Error("get natHoleRespMsg error: %v", err)
  228. return
  229. }
  230. err = msg.ReadMsgInto(bytes.NewReader(buf[:n]), &natHoleRespMsg)
  231. if err != nil {
  232. pxy.Error("get natHoleRespMsg error: %v", err)
  233. return
  234. }
  235. clientConn.SetReadDeadline(time.Time{})
  236. clientConn.Close()
  237. if natHoleRespMsg.Error != "" {
  238. pxy.Error("natHoleRespMsg get error info: %s", natHoleRespMsg.Error)
  239. return
  240. }
  241. pxy.Trace("get natHoleRespMsg, sid [%s], client address [%s]", natHoleRespMsg.Sid, natHoleRespMsg.ClientAddr)
  242. // Send sid to visitor udp address.
  243. time.Sleep(time.Second)
  244. laddr, _ := net.ResolveUDPAddr("udp", clientConn.LocalAddr().String())
  245. daddr, err := net.ResolveUDPAddr("udp", natHoleRespMsg.VisitorAddr)
  246. if err != nil {
  247. pxy.Error("resolve visitor udp address error: %v", err)
  248. return
  249. }
  250. lConn, err := net.DialUDP("udp", laddr, daddr)
  251. if err != nil {
  252. pxy.Error("dial visitor udp address error: %v", err)
  253. return
  254. }
  255. lConn.Write([]byte(natHoleRespMsg.Sid))
  256. kcpConn, err := frpNet.NewKcpConnFromUdp(lConn, true, natHoleRespMsg.VisitorAddr)
  257. if err != nil {
  258. pxy.Error("create kcp connection from udp connection error: %v", err)
  259. return
  260. }
  261. HandleTcpWorkConnection(&pxy.cfg.LocalSvrConf, pxy.proxyPlugin, &pxy.cfg.BaseProxyConf,
  262. frpNet.WrapConn(kcpConn), []byte(pxy.cfg.Sk))
  263. }
  264. // UDP
  265. type UdpProxy struct {
  266. *BaseProxy
  267. cfg *config.UdpProxyConf
  268. localAddr *net.UDPAddr
  269. readCh chan *msg.UdpPacket
  270. // include msg.UdpPacket and msg.Ping
  271. sendCh chan msg.Message
  272. workConn frpNet.Conn
  273. }
  274. func (pxy *UdpProxy) Run() (err error) {
  275. pxy.localAddr, err = net.ResolveUDPAddr("udp", fmt.Sprintf("%s:%d", pxy.cfg.LocalIp, pxy.cfg.LocalPort))
  276. if err != nil {
  277. return
  278. }
  279. return
  280. }
  281. func (pxy *UdpProxy) Close() {
  282. pxy.mu.Lock()
  283. defer pxy.mu.Unlock()
  284. if !pxy.closed {
  285. pxy.closed = true
  286. if pxy.workConn != nil {
  287. pxy.workConn.Close()
  288. }
  289. if pxy.readCh != nil {
  290. close(pxy.readCh)
  291. }
  292. if pxy.sendCh != nil {
  293. close(pxy.sendCh)
  294. }
  295. }
  296. }
  297. func (pxy *UdpProxy) InWorkConn(conn frpNet.Conn) {
  298. pxy.Info("incoming a new work connection for udp proxy, %s", conn.RemoteAddr().String())
  299. // close resources releated with old workConn
  300. pxy.Close()
  301. pxy.mu.Lock()
  302. pxy.workConn = conn
  303. pxy.readCh = make(chan *msg.UdpPacket, 1024)
  304. pxy.sendCh = make(chan msg.Message, 1024)
  305. pxy.closed = false
  306. pxy.mu.Unlock()
  307. workConnReaderFn := func(conn net.Conn, readCh chan *msg.UdpPacket) {
  308. for {
  309. var udpMsg msg.UdpPacket
  310. if errRet := msg.ReadMsgInto(conn, &udpMsg); errRet != nil {
  311. pxy.Warn("read from workConn for udp error: %v", errRet)
  312. return
  313. }
  314. if errRet := errors.PanicToError(func() {
  315. pxy.Trace("get udp package from workConn: %s", udpMsg.Content)
  316. readCh <- &udpMsg
  317. }); errRet != nil {
  318. pxy.Info("reader goroutine for udp work connection closed: %v", errRet)
  319. return
  320. }
  321. }
  322. }
  323. workConnSenderFn := func(conn net.Conn, sendCh chan msg.Message) {
  324. defer func() {
  325. pxy.Info("writer goroutine for udp work connection closed")
  326. }()
  327. var errRet error
  328. for rawMsg := range sendCh {
  329. switch m := rawMsg.(type) {
  330. case *msg.UdpPacket:
  331. pxy.Trace("send udp package to workConn: %s", m.Content)
  332. case *msg.Ping:
  333. pxy.Trace("send ping message to udp workConn")
  334. }
  335. if errRet = msg.WriteMsg(conn, rawMsg); errRet != nil {
  336. pxy.Error("udp work write error: %v", errRet)
  337. return
  338. }
  339. }
  340. }
  341. heartbeatFn := func(conn net.Conn, sendCh chan msg.Message) {
  342. var errRet error
  343. for {
  344. time.Sleep(time.Duration(30) * time.Second)
  345. if errRet = errors.PanicToError(func() {
  346. sendCh <- &msg.Ping{}
  347. }); errRet != nil {
  348. pxy.Trace("heartbeat goroutine for udp work connection closed")
  349. break
  350. }
  351. }
  352. }
  353. go workConnSenderFn(pxy.workConn, pxy.sendCh)
  354. go workConnReaderFn(pxy.workConn, pxy.readCh)
  355. go heartbeatFn(pxy.workConn, pxy.sendCh)
  356. udp.Forwarder(pxy.localAddr, pxy.readCh, pxy.sendCh)
  357. }
  358. // Common handler for tcp work connections.
  359. func HandleTcpWorkConnection(localInfo *config.LocalSvrConf, proxyPlugin plugin.Plugin,
  360. baseInfo *config.BaseProxyConf, workConn frpNet.Conn, encKey []byte) {
  361. var (
  362. remote io.ReadWriteCloser
  363. err error
  364. )
  365. remote = workConn
  366. if baseInfo.UseEncryption {
  367. remote, err = frpIo.WithEncryption(remote, encKey)
  368. if err != nil {
  369. workConn.Close()
  370. workConn.Error("create encryption stream error: %v", err)
  371. return
  372. }
  373. }
  374. if baseInfo.UseCompression {
  375. remote = frpIo.WithCompression(remote)
  376. }
  377. if proxyPlugin != nil {
  378. // if plugin is set, let plugin handle connections first
  379. workConn.Debug("handle by plugin: %s", proxyPlugin.Name())
  380. proxyPlugin.Handle(remote, workConn)
  381. workConn.Debug("handle by plugin finished")
  382. return
  383. } else {
  384. localConn, err := frpNet.ConnectServer("tcp", fmt.Sprintf("%s:%d", localInfo.LocalIp, localInfo.LocalPort))
  385. if err != nil {
  386. workConn.Close()
  387. workConn.Error("connect to local service [%s:%d] error: %v", localInfo.LocalIp, localInfo.LocalPort, err)
  388. return
  389. }
  390. workConn.Debug("join connections, localConn(l[%s] r[%s]) workConn(l[%s] r[%s])", localConn.LocalAddr().String(),
  391. localConn.RemoteAddr().String(), workConn.LocalAddr().String(), workConn.RemoteAddr().String())
  392. frpIo.Join(localConn, remote)
  393. workConn.Debug("join connections closed")
  394. }
  395. }