1
0

proxy.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  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. }
  181. locations := pxy.cfg.Locations
  182. if len(locations) == 0 {
  183. locations = []string{""}
  184. }
  185. for _, domain := range pxy.cfg.CustomDomains {
  186. routeConfig.Domain = domain
  187. for _, location := range locations {
  188. routeConfig.Location = location
  189. err := pxy.ctl.svr.httpReverseProxy.Register(routeConfig.Domain, routeConfig.Location, routeConfig.RewriteHost, pxy.GetRealConn)
  190. if err != nil {
  191. return err
  192. }
  193. tmpDomain := routeConfig.Domain
  194. tmpLocation := routeConfig.Location
  195. pxy.closeFuncs = append(pxy.closeFuncs, func() {
  196. pxy.ctl.svr.httpReverseProxy.UnRegister(tmpDomain, tmpLocation)
  197. })
  198. pxy.Info("http proxy listen for host [%s] location [%s]", routeConfig.Domain, routeConfig.Location)
  199. }
  200. }
  201. if pxy.cfg.SubDomain != "" {
  202. routeConfig.Domain = pxy.cfg.SubDomain + "." + config.ServerCommonCfg.SubDomainHost
  203. for _, location := range locations {
  204. routeConfig.Location = location
  205. err := pxy.ctl.svr.httpReverseProxy.Register(routeConfig.Domain, routeConfig.Location, routeConfig.RewriteHost, pxy.GetRealConn)
  206. if err != nil {
  207. return err
  208. }
  209. tmpDomain := routeConfig.Domain
  210. tmpLocation := routeConfig.Location
  211. pxy.closeFuncs = append(pxy.closeFuncs, func() {
  212. pxy.ctl.svr.httpReverseProxy.UnRegister(tmpDomain, tmpLocation)
  213. })
  214. pxy.Info("http proxy listen for host [%s] location [%s]", routeConfig.Domain, routeConfig.Location)
  215. }
  216. }
  217. return
  218. }
  219. func (pxy *HttpProxy) GetConf() config.ProxyConf {
  220. return pxy.cfg
  221. }
  222. func (pxy *HttpProxy) GetRealConn() (workConn frpNet.Conn, err error) {
  223. tmpConn, errRet := pxy.GetWorkConnFromPool()
  224. if errRet != nil {
  225. err = errRet
  226. return
  227. }
  228. var rwc io.ReadWriteCloser = tmpConn
  229. if pxy.cfg.UseEncryption {
  230. rwc, err = frpIo.WithEncryption(rwc, []byte(config.ServerCommonCfg.PrivilegeToken))
  231. if err != nil {
  232. pxy.Error("create encryption stream error: %v", err)
  233. return
  234. }
  235. }
  236. if pxy.cfg.UseCompression {
  237. rwc = frpIo.WithCompression(rwc)
  238. }
  239. workConn = frpNet.WrapReadWriteCloserToConn(rwc, tmpConn)
  240. return
  241. }
  242. func (pxy *HttpProxy) Close() {
  243. pxy.BaseProxy.Close()
  244. for _, closeFn := range pxy.closeFuncs {
  245. closeFn()
  246. }
  247. }
  248. type HttpsProxy struct {
  249. BaseProxy
  250. cfg *config.HttpsProxyConf
  251. }
  252. func (pxy *HttpsProxy) Run() (err error) {
  253. routeConfig := &vhost.VhostRouteConfig{}
  254. for _, domain := range pxy.cfg.CustomDomains {
  255. routeConfig.Domain = domain
  256. l, err := pxy.ctl.svr.VhostHttpsMuxer.Listen(routeConfig)
  257. if err != nil {
  258. return err
  259. }
  260. l.AddLogPrefix(pxy.name)
  261. pxy.Info("https proxy listen for host [%s]", routeConfig.Domain)
  262. pxy.listeners = append(pxy.listeners, l)
  263. }
  264. if pxy.cfg.SubDomain != "" {
  265. routeConfig.Domain = pxy.cfg.SubDomain + "." + config.ServerCommonCfg.SubDomainHost
  266. l, err := pxy.ctl.svr.VhostHttpsMuxer.Listen(routeConfig)
  267. if err != nil {
  268. return err
  269. }
  270. l.AddLogPrefix(pxy.name)
  271. pxy.Info("https proxy listen for host [%s]", routeConfig.Domain)
  272. pxy.listeners = append(pxy.listeners, l)
  273. }
  274. pxy.startListenHandler(pxy, HandleUserTcpConnection)
  275. return
  276. }
  277. func (pxy *HttpsProxy) GetConf() config.ProxyConf {
  278. return pxy.cfg
  279. }
  280. func (pxy *HttpsProxy) Close() {
  281. pxy.BaseProxy.Close()
  282. }
  283. type StcpProxy struct {
  284. BaseProxy
  285. cfg *config.StcpProxyConf
  286. }
  287. func (pxy *StcpProxy) Run() error {
  288. listener, err := pxy.ctl.svr.visitorManager.Listen(pxy.GetName(), pxy.cfg.Sk)
  289. if err != nil {
  290. return err
  291. }
  292. listener.AddLogPrefix(pxy.name)
  293. pxy.listeners = append(pxy.listeners, listener)
  294. pxy.Info("stcp proxy custom listen success")
  295. pxy.startListenHandler(pxy, HandleUserTcpConnection)
  296. return nil
  297. }
  298. func (pxy *StcpProxy) GetConf() config.ProxyConf {
  299. return pxy.cfg
  300. }
  301. func (pxy *StcpProxy) Close() {
  302. pxy.BaseProxy.Close()
  303. pxy.ctl.svr.visitorManager.CloseListener(pxy.GetName())
  304. }
  305. type XtcpProxy struct {
  306. BaseProxy
  307. cfg *config.XtcpProxyConf
  308. closeCh chan struct{}
  309. }
  310. func (pxy *XtcpProxy) Run() error {
  311. if pxy.ctl.svr.natHoleController == nil {
  312. pxy.Error("udp port for xtcp is not specified.")
  313. return fmt.Errorf("xtcp is not supported in frps")
  314. }
  315. sidCh := pxy.ctl.svr.natHoleController.ListenClient(pxy.GetName(), pxy.cfg.Sk)
  316. go func() {
  317. for {
  318. select {
  319. case <-pxy.closeCh:
  320. break
  321. case sid := <-sidCh:
  322. workConn, err := pxy.GetWorkConnFromPool()
  323. if err != nil {
  324. continue
  325. }
  326. m := &msg.NatHoleSid{
  327. Sid: sid,
  328. }
  329. err = msg.WriteMsg(workConn, m)
  330. if err != nil {
  331. pxy.Warn("write nat hole sid package error, %v", err)
  332. }
  333. }
  334. }
  335. }()
  336. return nil
  337. }
  338. func (pxy *XtcpProxy) GetConf() config.ProxyConf {
  339. return pxy.cfg
  340. }
  341. func (pxy *XtcpProxy) Close() {
  342. pxy.BaseProxy.Close()
  343. pxy.ctl.svr.natHoleController.CloseClient(pxy.GetName())
  344. errors.PanicToError(func() {
  345. close(pxy.closeCh)
  346. })
  347. }
  348. type UdpProxy struct {
  349. BaseProxy
  350. cfg *config.UdpProxyConf
  351. // udpConn is the listener of udp packages
  352. udpConn *net.UDPConn
  353. // there are always only one workConn at the same time
  354. // get another one if it closed
  355. workConn net.Conn
  356. // sendCh is used for sending packages to workConn
  357. sendCh chan *msg.UdpPacket
  358. // readCh is used for reading packages from workConn
  359. readCh chan *msg.UdpPacket
  360. // checkCloseCh is used for watching if workConn is closed
  361. checkCloseCh chan int
  362. isClosed bool
  363. }
  364. func (pxy *UdpProxy) Run() (err error) {
  365. addr, err := net.ResolveUDPAddr("udp", fmt.Sprintf("%s:%d", config.ServerCommonCfg.ProxyBindAddr, pxy.cfg.RemotePort))
  366. if err != nil {
  367. return err
  368. }
  369. udpConn, err := net.ListenUDP("udp", addr)
  370. if err != nil {
  371. pxy.Warn("listen udp port error: %v", err)
  372. return err
  373. }
  374. pxy.Info("udp proxy listen port [%d]", pxy.cfg.RemotePort)
  375. pxy.udpConn = udpConn
  376. pxy.sendCh = make(chan *msg.UdpPacket, 1024)
  377. pxy.readCh = make(chan *msg.UdpPacket, 1024)
  378. pxy.checkCloseCh = make(chan int)
  379. // read message from workConn, if it returns any error, notify proxy to start a new workConn
  380. workConnReaderFn := func(conn net.Conn) {
  381. for {
  382. var (
  383. rawMsg msg.Message
  384. errRet error
  385. )
  386. pxy.Trace("loop waiting message from udp workConn")
  387. // client will send heartbeat in workConn for keeping alive
  388. conn.SetReadDeadline(time.Now().Add(time.Duration(60) * time.Second))
  389. if rawMsg, errRet = msg.ReadMsg(conn); errRet != nil {
  390. pxy.Warn("read from workConn for udp error: %v", errRet)
  391. conn.Close()
  392. // notify proxy to start a new work connection
  393. // ignore error here, it means the proxy is closed
  394. errors.PanicToError(func() {
  395. pxy.checkCloseCh <- 1
  396. })
  397. return
  398. }
  399. conn.SetReadDeadline(time.Time{})
  400. switch m := rawMsg.(type) {
  401. case *msg.Ping:
  402. pxy.Trace("udp work conn get ping message")
  403. continue
  404. case *msg.UdpPacket:
  405. if errRet := errors.PanicToError(func() {
  406. pxy.Trace("get udp message from workConn: %s", m.Content)
  407. pxy.readCh <- m
  408. StatsAddTrafficOut(pxy.GetName(), int64(len(m.Content)))
  409. }); errRet != nil {
  410. conn.Close()
  411. pxy.Info("reader goroutine for udp work connection closed")
  412. return
  413. }
  414. }
  415. }
  416. }
  417. // send message to workConn
  418. workConnSenderFn := func(conn net.Conn, ctx context.Context) {
  419. var errRet error
  420. for {
  421. select {
  422. case udpMsg, ok := <-pxy.sendCh:
  423. if !ok {
  424. pxy.Info("sender goroutine for udp work connection closed")
  425. return
  426. }
  427. if errRet = msg.WriteMsg(conn, udpMsg); errRet != nil {
  428. pxy.Info("sender goroutine for udp work connection closed: %v", errRet)
  429. conn.Close()
  430. return
  431. } else {
  432. pxy.Trace("send message to udp workConn: %s", udpMsg.Content)
  433. StatsAddTrafficIn(pxy.GetName(), int64(len(udpMsg.Content)))
  434. continue
  435. }
  436. case <-ctx.Done():
  437. pxy.Info("sender goroutine for udp work connection closed")
  438. return
  439. }
  440. }
  441. }
  442. go func() {
  443. // Sleep a while for waiting control send the NewProxyResp to client.
  444. time.Sleep(500 * time.Millisecond)
  445. for {
  446. workConn, err := pxy.GetWorkConnFromPool()
  447. if err != nil {
  448. time.Sleep(1 * time.Second)
  449. // check if proxy is closed
  450. select {
  451. case _, ok := <-pxy.checkCloseCh:
  452. if !ok {
  453. return
  454. }
  455. default:
  456. }
  457. continue
  458. }
  459. // close the old workConn and replac it with a new one
  460. if pxy.workConn != nil {
  461. pxy.workConn.Close()
  462. }
  463. pxy.workConn = workConn
  464. ctx, cancel := context.WithCancel(context.Background())
  465. go workConnReaderFn(workConn)
  466. go workConnSenderFn(workConn, ctx)
  467. _, ok := <-pxy.checkCloseCh
  468. cancel()
  469. if !ok {
  470. return
  471. }
  472. }
  473. }()
  474. // Read from user connections and send wrapped udp message to sendCh (forwarded by workConn).
  475. // Client will transfor udp message to local udp service and waiting for response for a while.
  476. // Response will be wrapped to be forwarded by work connection to server.
  477. // Close readCh and sendCh at the end.
  478. go func() {
  479. udp.ForwardUserConn(udpConn, pxy.readCh, pxy.sendCh)
  480. pxy.Close()
  481. }()
  482. return nil
  483. }
  484. func (pxy *UdpProxy) GetConf() config.ProxyConf {
  485. return pxy.cfg
  486. }
  487. func (pxy *UdpProxy) Close() {
  488. pxy.mu.Lock()
  489. defer pxy.mu.Unlock()
  490. if !pxy.isClosed {
  491. pxy.isClosed = true
  492. pxy.BaseProxy.Close()
  493. if pxy.workConn != nil {
  494. pxy.workConn.Close()
  495. }
  496. pxy.udpConn.Close()
  497. // all channels only closed here
  498. close(pxy.checkCloseCh)
  499. close(pxy.readCh)
  500. close(pxy.sendCh)
  501. }
  502. }
  503. // HandleUserTcpConnection is used for incoming tcp user connections.
  504. // It can be used for tcp, http, https type.
  505. func HandleUserTcpConnection(pxy Proxy, userConn frpNet.Conn) {
  506. defer userConn.Close()
  507. // try all connections from the pool
  508. workConn, err := pxy.GetWorkConnFromPool()
  509. if err != nil {
  510. return
  511. }
  512. defer workConn.Close()
  513. var local io.ReadWriteCloser = workConn
  514. cfg := pxy.GetConf().GetBaseInfo()
  515. if cfg.UseEncryption {
  516. local, err = frpIo.WithEncryption(local, []byte(config.ServerCommonCfg.PrivilegeToken))
  517. if err != nil {
  518. pxy.Error("create encryption stream error: %v", err)
  519. return
  520. }
  521. }
  522. if cfg.UseCompression {
  523. local = frpIo.WithCompression(local)
  524. }
  525. pxy.Debug("join connections, workConn(l[%s] r[%s]) userConn(l[%s] r[%s])", workConn.LocalAddr().String(),
  526. workConn.RemoteAddr().String(), userConn.LocalAddr().String(), userConn.RemoteAddr().String())
  527. StatsOpenConnection(pxy.GetName())
  528. inCount, outCount := frpIo.Join(local, userConn)
  529. StatsCloseConnection(pxy.GetName())
  530. StatsAddTrafficIn(pxy.GetName(), inCount)
  531. StatsAddTrafficOut(pxy.GetName(), outCount)
  532. pxy.Debug("join connections closed")
  533. }