proxy.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  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 server
  15. import (
  16. "context"
  17. "fmt"
  18. "io"
  19. "net"
  20. "sync"
  21. "time"
  22. "github.com/fatedier/frp/models/config"
  23. "github.com/fatedier/frp/models/msg"
  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. "github.com/fatedier/frp/utils/vhost"
  30. )
  31. type Proxy interface {
  32. Run() error
  33. GetControl() *Control
  34. GetName() string
  35. GetConf() config.ProxyConf
  36. GetWorkConnFromPool() (workConn frpNet.Conn, err error)
  37. Close()
  38. log.Logger
  39. }
  40. type BaseProxy struct {
  41. name string
  42. ctl *Control
  43. listeners []frpNet.Listener
  44. mu sync.RWMutex
  45. log.Logger
  46. }
  47. func (pxy *BaseProxy) GetName() string {
  48. return pxy.name
  49. }
  50. func (pxy *BaseProxy) GetControl() *Control {
  51. return pxy.ctl
  52. }
  53. func (pxy *BaseProxy) Close() {
  54. pxy.Info("proxy closing")
  55. for _, l := range pxy.listeners {
  56. l.Close()
  57. }
  58. }
  59. func (pxy *BaseProxy) GetWorkConnFromPool() (workConn frpNet.Conn, err error) {
  60. ctl := pxy.GetControl()
  61. // try all connections from the pool
  62. for i := 0; i < ctl.poolCount+1; i++ {
  63. if workConn, err = ctl.GetWorkConn(); err != nil {
  64. pxy.Warn("failed to get work connection: %v", err)
  65. return
  66. }
  67. pxy.Info("get a new work connection: [%s]", workConn.RemoteAddr().String())
  68. workConn.AddLogPrefix(pxy.GetName())
  69. err := msg.WriteMsg(workConn, &msg.StartWorkConn{
  70. ProxyName: pxy.GetName(),
  71. })
  72. if err != nil {
  73. workConn.Warn("failed to send message to work connection from pool: %v, times: %d", err, i)
  74. workConn.Close()
  75. } else {
  76. break
  77. }
  78. }
  79. if err != nil {
  80. pxy.Error("try to get work connection failed in the end")
  81. return
  82. }
  83. return
  84. }
  85. // startListenHandler start a goroutine handler for each listener.
  86. // p: p will just be passed to handler(Proxy, frpNet.Conn).
  87. // handler: each proxy type can set different handler function to deal with connections accepted from listeners.
  88. func (pxy *BaseProxy) startListenHandler(p Proxy, handler func(Proxy, frpNet.Conn)) {
  89. for _, listener := range pxy.listeners {
  90. go func(l frpNet.Listener) {
  91. for {
  92. // block
  93. // if listener is closed, err returned
  94. c, err := l.Accept()
  95. if err != nil {
  96. pxy.Info("listener is closed")
  97. return
  98. }
  99. pxy.Debug("get a user connection [%s]", c.RemoteAddr().String())
  100. go handler(p, c)
  101. }
  102. }(listener)
  103. }
  104. }
  105. func NewProxy(ctl *Control, pxyConf config.ProxyConf) (pxy Proxy, err error) {
  106. basePxy := BaseProxy{
  107. name: pxyConf.GetName(),
  108. ctl: ctl,
  109. listeners: make([]frpNet.Listener, 0),
  110. Logger: log.NewPrefixLogger(ctl.runId),
  111. }
  112. switch cfg := pxyConf.(type) {
  113. case *config.TcpProxyConf:
  114. pxy = &TcpProxy{
  115. BaseProxy: basePxy,
  116. cfg: cfg,
  117. }
  118. case *config.HttpProxyConf:
  119. pxy = &HttpProxy{
  120. BaseProxy: basePxy,
  121. cfg: cfg,
  122. }
  123. case *config.HttpsProxyConf:
  124. pxy = &HttpsProxy{
  125. BaseProxy: basePxy,
  126. cfg: cfg,
  127. }
  128. case *config.UdpProxyConf:
  129. pxy = &UdpProxy{
  130. BaseProxy: basePxy,
  131. cfg: cfg,
  132. }
  133. case *config.StcpProxyConf:
  134. pxy = &StcpProxy{
  135. BaseProxy: basePxy,
  136. cfg: cfg,
  137. }
  138. case *config.XtcpProxyConf:
  139. pxy = &XtcpProxy{
  140. BaseProxy: basePxy,
  141. cfg: cfg,
  142. }
  143. default:
  144. return pxy, fmt.Errorf("proxy type not support")
  145. }
  146. pxy.AddLogPrefix(pxy.GetName())
  147. return
  148. }
  149. type TcpProxy struct {
  150. BaseProxy
  151. cfg *config.TcpProxyConf
  152. }
  153. func (pxy *TcpProxy) Run() error {
  154. listener, err := frpNet.ListenTcp(config.ServerCommonCfg.ProxyBindAddr, pxy.cfg.RemotePort)
  155. if err != nil {
  156. return err
  157. }
  158. listener.AddLogPrefix(pxy.name)
  159. pxy.listeners = append(pxy.listeners, listener)
  160. pxy.Info("tcp proxy listen port [%d]", pxy.cfg.RemotePort)
  161. pxy.startListenHandler(pxy, HandleUserTcpConnection)
  162. return nil
  163. }
  164. func (pxy *TcpProxy) GetConf() config.ProxyConf {
  165. return pxy.cfg
  166. }
  167. func (pxy *TcpProxy) Close() {
  168. pxy.BaseProxy.Close()
  169. }
  170. type HttpProxy struct {
  171. BaseProxy
  172. cfg *config.HttpProxyConf
  173. closeFuncs []func()
  174. }
  175. func (pxy *HttpProxy) Run() (err error) {
  176. routeConfig := vhost.VhostRouteConfig{
  177. RewriteHost: pxy.cfg.HostHeaderRewrite,
  178. Username: pxy.cfg.HttpUser,
  179. Password: pxy.cfg.HttpPwd,
  180. CreateConnFn: pxy.GetRealConn,
  181. }
  182. locations := pxy.cfg.Locations
  183. if len(locations) == 0 {
  184. locations = []string{""}
  185. }
  186. for _, domain := range pxy.cfg.CustomDomains {
  187. routeConfig.Domain = domain
  188. for _, location := range locations {
  189. routeConfig.Location = location
  190. err := pxy.ctl.svr.httpReverseProxy.Register(routeConfig)
  191. if err != nil {
  192. return err
  193. }
  194. tmpDomain := routeConfig.Domain
  195. tmpLocation := routeConfig.Location
  196. pxy.closeFuncs = append(pxy.closeFuncs, func() {
  197. pxy.ctl.svr.httpReverseProxy.UnRegister(tmpDomain, tmpLocation)
  198. })
  199. pxy.Info("http proxy listen for host [%s] location [%s]", routeConfig.Domain, routeConfig.Location)
  200. }
  201. }
  202. if pxy.cfg.SubDomain != "" {
  203. routeConfig.Domain = pxy.cfg.SubDomain + "." + config.ServerCommonCfg.SubDomainHost
  204. for _, location := range locations {
  205. routeConfig.Location = location
  206. err := pxy.ctl.svr.httpReverseProxy.Register(routeConfig)
  207. if err != nil {
  208. return err
  209. }
  210. tmpDomain := routeConfig.Domain
  211. tmpLocation := routeConfig.Location
  212. pxy.closeFuncs = append(pxy.closeFuncs, func() {
  213. pxy.ctl.svr.httpReverseProxy.UnRegister(tmpDomain, tmpLocation)
  214. })
  215. pxy.Info("http proxy listen for host [%s] location [%s]", routeConfig.Domain, routeConfig.Location)
  216. }
  217. }
  218. return
  219. }
  220. func (pxy *HttpProxy) GetConf() config.ProxyConf {
  221. return pxy.cfg
  222. }
  223. func (pxy *HttpProxy) GetRealConn() (workConn frpNet.Conn, err error) {
  224. tmpConn, errRet := pxy.GetWorkConnFromPool()
  225. if errRet != nil {
  226. err = errRet
  227. return
  228. }
  229. var rwc io.ReadWriteCloser = tmpConn
  230. if pxy.cfg.UseEncryption {
  231. rwc, err = frpIo.WithEncryption(rwc, []byte(config.ServerCommonCfg.PrivilegeToken))
  232. if err != nil {
  233. pxy.Error("create encryption stream error: %v", err)
  234. return
  235. }
  236. }
  237. if pxy.cfg.UseCompression {
  238. rwc = frpIo.WithCompression(rwc)
  239. }
  240. workConn = frpNet.WrapReadWriteCloserToConn(rwc, tmpConn)
  241. return
  242. }
  243. func (pxy *HttpProxy) Close() {
  244. pxy.BaseProxy.Close()
  245. for _, closeFn := range pxy.closeFuncs {
  246. closeFn()
  247. }
  248. }
  249. type HttpsProxy struct {
  250. BaseProxy
  251. cfg *config.HttpsProxyConf
  252. }
  253. func (pxy *HttpsProxy) Run() (err error) {
  254. routeConfig := &vhost.VhostRouteConfig{}
  255. for _, domain := range pxy.cfg.CustomDomains {
  256. routeConfig.Domain = domain
  257. l, err := pxy.ctl.svr.VhostHttpsMuxer.Listen(routeConfig)
  258. if err != nil {
  259. return err
  260. }
  261. l.AddLogPrefix(pxy.name)
  262. pxy.Info("https proxy listen for host [%s]", routeConfig.Domain)
  263. pxy.listeners = append(pxy.listeners, l)
  264. }
  265. if pxy.cfg.SubDomain != "" {
  266. routeConfig.Domain = pxy.cfg.SubDomain + "." + config.ServerCommonCfg.SubDomainHost
  267. l, err := pxy.ctl.svr.VhostHttpsMuxer.Listen(routeConfig)
  268. if err != nil {
  269. return err
  270. }
  271. l.AddLogPrefix(pxy.name)
  272. pxy.Info("https proxy listen for host [%s]", routeConfig.Domain)
  273. pxy.listeners = append(pxy.listeners, l)
  274. }
  275. pxy.startListenHandler(pxy, HandleUserTcpConnection)
  276. return
  277. }
  278. func (pxy *HttpsProxy) GetConf() config.ProxyConf {
  279. return pxy.cfg
  280. }
  281. func (pxy *HttpsProxy) Close() {
  282. pxy.BaseProxy.Close()
  283. }
  284. type StcpProxy struct {
  285. BaseProxy
  286. cfg *config.StcpProxyConf
  287. }
  288. func (pxy *StcpProxy) Run() error {
  289. listener, err := pxy.ctl.svr.visitorManager.Listen(pxy.GetName(), pxy.cfg.Sk)
  290. if err != nil {
  291. return err
  292. }
  293. listener.AddLogPrefix(pxy.name)
  294. pxy.listeners = append(pxy.listeners, listener)
  295. pxy.Info("stcp proxy custom listen success")
  296. pxy.startListenHandler(pxy, HandleUserTcpConnection)
  297. return nil
  298. }
  299. func (pxy *StcpProxy) GetConf() config.ProxyConf {
  300. return pxy.cfg
  301. }
  302. func (pxy *StcpProxy) Close() {
  303. pxy.BaseProxy.Close()
  304. pxy.ctl.svr.visitorManager.CloseListener(pxy.GetName())
  305. }
  306. type XtcpProxy struct {
  307. BaseProxy
  308. cfg *config.XtcpProxyConf
  309. closeCh chan struct{}
  310. }
  311. func (pxy *XtcpProxy) Run() error {
  312. if pxy.ctl.svr.natHoleController == nil {
  313. pxy.Error("udp port for xtcp is not specified.")
  314. return fmt.Errorf("xtcp is not supported in frps")
  315. }
  316. sidCh := pxy.ctl.svr.natHoleController.ListenClient(pxy.GetName(), pxy.cfg.Sk)
  317. go func() {
  318. for {
  319. select {
  320. case <-pxy.closeCh:
  321. break
  322. case sid := <-sidCh:
  323. workConn, err := pxy.GetWorkConnFromPool()
  324. if err != nil {
  325. continue
  326. }
  327. m := &msg.NatHoleSid{
  328. Sid: sid,
  329. }
  330. err = msg.WriteMsg(workConn, m)
  331. if err != nil {
  332. pxy.Warn("write nat hole sid package error, %v", err)
  333. }
  334. }
  335. }
  336. }()
  337. return nil
  338. }
  339. func (pxy *XtcpProxy) GetConf() config.ProxyConf {
  340. return pxy.cfg
  341. }
  342. func (pxy *XtcpProxy) Close() {
  343. pxy.BaseProxy.Close()
  344. pxy.ctl.svr.natHoleController.CloseClient(pxy.GetName())
  345. errors.PanicToError(func() {
  346. close(pxy.closeCh)
  347. })
  348. }
  349. type UdpProxy struct {
  350. BaseProxy
  351. cfg *config.UdpProxyConf
  352. // udpConn is the listener of udp packages
  353. udpConn *net.UDPConn
  354. // there are always only one workConn at the same time
  355. // get another one if it closed
  356. workConn net.Conn
  357. // sendCh is used for sending packages to workConn
  358. sendCh chan *msg.UdpPacket
  359. // readCh is used for reading packages from workConn
  360. readCh chan *msg.UdpPacket
  361. // checkCloseCh is used for watching if workConn is closed
  362. checkCloseCh chan int
  363. isClosed bool
  364. }
  365. func (pxy *UdpProxy) Run() (err error) {
  366. addr, err := net.ResolveUDPAddr("udp", fmt.Sprintf("%s:%d", config.ServerCommonCfg.ProxyBindAddr, pxy.cfg.RemotePort))
  367. if err != nil {
  368. return err
  369. }
  370. udpConn, err := net.ListenUDP("udp", addr)
  371. if err != nil {
  372. pxy.Warn("listen udp port error: %v", err)
  373. return err
  374. }
  375. pxy.Info("udp proxy listen port [%d]", pxy.cfg.RemotePort)
  376. pxy.udpConn = udpConn
  377. pxy.sendCh = make(chan *msg.UdpPacket, 1024)
  378. pxy.readCh = make(chan *msg.UdpPacket, 1024)
  379. pxy.checkCloseCh = make(chan int)
  380. // read message from workConn, if it returns any error, notify proxy to start a new workConn
  381. workConnReaderFn := func(conn net.Conn) {
  382. for {
  383. var (
  384. rawMsg msg.Message
  385. errRet error
  386. )
  387. pxy.Trace("loop waiting message from udp workConn")
  388. // client will send heartbeat in workConn for keeping alive
  389. conn.SetReadDeadline(time.Now().Add(time.Duration(60) * time.Second))
  390. if rawMsg, errRet = msg.ReadMsg(conn); errRet != nil {
  391. pxy.Warn("read from workConn for udp error: %v", errRet)
  392. conn.Close()
  393. // notify proxy to start a new work connection
  394. // ignore error here, it means the proxy is closed
  395. errors.PanicToError(func() {
  396. pxy.checkCloseCh <- 1
  397. })
  398. return
  399. }
  400. conn.SetReadDeadline(time.Time{})
  401. switch m := rawMsg.(type) {
  402. case *msg.Ping:
  403. pxy.Trace("udp work conn get ping message")
  404. continue
  405. case *msg.UdpPacket:
  406. if errRet := errors.PanicToError(func() {
  407. pxy.Trace("get udp message from workConn: %s", m.Content)
  408. pxy.readCh <- m
  409. StatsAddTrafficOut(pxy.GetName(), int64(len(m.Content)))
  410. }); errRet != nil {
  411. conn.Close()
  412. pxy.Info("reader goroutine for udp work connection closed")
  413. return
  414. }
  415. }
  416. }
  417. }
  418. // send message to workConn
  419. workConnSenderFn := func(conn net.Conn, ctx context.Context) {
  420. var errRet error
  421. for {
  422. select {
  423. case udpMsg, ok := <-pxy.sendCh:
  424. if !ok {
  425. pxy.Info("sender goroutine for udp work connection closed")
  426. return
  427. }
  428. if errRet = msg.WriteMsg(conn, udpMsg); errRet != nil {
  429. pxy.Info("sender goroutine for udp work connection closed: %v", errRet)
  430. conn.Close()
  431. return
  432. } else {
  433. pxy.Trace("send message to udp workConn: %s", udpMsg.Content)
  434. StatsAddTrafficIn(pxy.GetName(), int64(len(udpMsg.Content)))
  435. continue
  436. }
  437. case <-ctx.Done():
  438. pxy.Info("sender goroutine for udp work connection closed")
  439. return
  440. }
  441. }
  442. }
  443. go func() {
  444. // Sleep a while for waiting control send the NewProxyResp to client.
  445. time.Sleep(500 * time.Millisecond)
  446. for {
  447. workConn, err := pxy.GetWorkConnFromPool()
  448. if err != nil {
  449. time.Sleep(1 * time.Second)
  450. // check if proxy is closed
  451. select {
  452. case _, ok := <-pxy.checkCloseCh:
  453. if !ok {
  454. return
  455. }
  456. default:
  457. }
  458. continue
  459. }
  460. // close the old workConn and replac it with a new one
  461. if pxy.workConn != nil {
  462. pxy.workConn.Close()
  463. }
  464. pxy.workConn = workConn
  465. ctx, cancel := context.WithCancel(context.Background())
  466. go workConnReaderFn(workConn)
  467. go workConnSenderFn(workConn, ctx)
  468. _, ok := <-pxy.checkCloseCh
  469. cancel()
  470. if !ok {
  471. return
  472. }
  473. }
  474. }()
  475. // Read from user connections and send wrapped udp message to sendCh (forwarded by workConn).
  476. // Client will transfor udp message to local udp service and waiting for response for a while.
  477. // Response will be wrapped to be forwarded by work connection to server.
  478. // Close readCh and sendCh at the end.
  479. go func() {
  480. udp.ForwardUserConn(udpConn, pxy.readCh, pxy.sendCh)
  481. pxy.Close()
  482. }()
  483. return nil
  484. }
  485. func (pxy *UdpProxy) GetConf() config.ProxyConf {
  486. return pxy.cfg
  487. }
  488. func (pxy *UdpProxy) Close() {
  489. pxy.mu.Lock()
  490. defer pxy.mu.Unlock()
  491. if !pxy.isClosed {
  492. pxy.isClosed = true
  493. pxy.BaseProxy.Close()
  494. if pxy.workConn != nil {
  495. pxy.workConn.Close()
  496. }
  497. pxy.udpConn.Close()
  498. // all channels only closed here
  499. close(pxy.checkCloseCh)
  500. close(pxy.readCh)
  501. close(pxy.sendCh)
  502. }
  503. }
  504. // HandleUserTcpConnection is used for incoming tcp user connections.
  505. // It can be used for tcp, http, https type.
  506. func HandleUserTcpConnection(pxy Proxy, userConn frpNet.Conn) {
  507. defer userConn.Close()
  508. // try all connections from the pool
  509. workConn, err := pxy.GetWorkConnFromPool()
  510. if err != nil {
  511. return
  512. }
  513. defer workConn.Close()
  514. var local io.ReadWriteCloser = workConn
  515. cfg := pxy.GetConf().GetBaseInfo()
  516. if cfg.UseEncryption {
  517. local, err = frpIo.WithEncryption(local, []byte(config.ServerCommonCfg.PrivilegeToken))
  518. if err != nil {
  519. pxy.Error("create encryption stream error: %v", err)
  520. return
  521. }
  522. }
  523. if cfg.UseCompression {
  524. local = frpIo.WithCompression(local)
  525. }
  526. pxy.Debug("join connections, workConn(l[%s] r[%s]) userConn(l[%s] r[%s])", workConn.LocalAddr().String(),
  527. workConn.RemoteAddr().String(), userConn.LocalAddr().String(), userConn.RemoteAddr().String())
  528. StatsOpenConnection(pxy.GetName())
  529. inCount, outCount := frpIo.Join(local, userConn)
  530. StatsCloseConnection(pxy.GetName())
  531. StatsAddTrafficIn(pxy.GetName(), inCount)
  532. StatsAddTrafficOut(pxy.GetName(), outCount)
  533. pxy.Debug("join connections closed")
  534. }