proxy.go 14 KB

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