proxy.go 12 KB

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