proxy.go 13 KB

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