proxy.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  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 proxy
  15. import (
  16. "bytes"
  17. "fmt"
  18. "io"
  19. "io/ioutil"
  20. "net"
  21. "strconv"
  22. "strings"
  23. "sync"
  24. "time"
  25. "github.com/fatedier/frp/g"
  26. "github.com/fatedier/frp/models/config"
  27. "github.com/fatedier/frp/models/msg"
  28. "github.com/fatedier/frp/models/plugin"
  29. "github.com/fatedier/frp/models/proto/udp"
  30. "github.com/fatedier/frp/utils/log"
  31. frpNet "github.com/fatedier/frp/utils/net"
  32. "github.com/fatedier/golib/errors"
  33. frpIo "github.com/fatedier/golib/io"
  34. "github.com/fatedier/golib/pool"
  35. fmux "github.com/hashicorp/yamux"
  36. )
  37. // Proxy defines how to handle work connections for different proxy type.
  38. type Proxy interface {
  39. Run() error
  40. // InWorkConn accept work connections registered to server.
  41. InWorkConn(conn frpNet.Conn)
  42. Close()
  43. log.Logger
  44. }
  45. func NewProxy(pxyConf config.ProxyConf) (pxy Proxy) {
  46. baseProxy := BaseProxy{
  47. Logger: log.NewPrefixLogger(pxyConf.GetBaseInfo().ProxyName),
  48. }
  49. switch cfg := pxyConf.(type) {
  50. case *config.TcpProxyConf:
  51. pxy = &TcpProxy{
  52. BaseProxy: &baseProxy,
  53. cfg: cfg,
  54. }
  55. case *config.UdpProxyConf:
  56. pxy = &UdpProxy{
  57. BaseProxy: &baseProxy,
  58. cfg: cfg,
  59. }
  60. case *config.HttpProxyConf:
  61. pxy = &HttpProxy{
  62. BaseProxy: &baseProxy,
  63. cfg: cfg,
  64. }
  65. case *config.HttpsProxyConf:
  66. pxy = &HttpsProxy{
  67. BaseProxy: &baseProxy,
  68. cfg: cfg,
  69. }
  70. case *config.StcpProxyConf:
  71. pxy = &StcpProxy{
  72. BaseProxy: &baseProxy,
  73. cfg: cfg,
  74. }
  75. case *config.XtcpProxyConf:
  76. pxy = &XtcpProxy{
  77. BaseProxy: &baseProxy,
  78. cfg: cfg,
  79. }
  80. }
  81. return
  82. }
  83. type BaseProxy struct {
  84. closed bool
  85. mu sync.RWMutex
  86. log.Logger
  87. }
  88. // TCP
  89. type TcpProxy struct {
  90. *BaseProxy
  91. cfg *config.TcpProxyConf
  92. proxyPlugin plugin.Plugin
  93. }
  94. func (pxy *TcpProxy) Run() (err error) {
  95. if pxy.cfg.Plugin != "" {
  96. pxy.proxyPlugin, err = plugin.Create(pxy.cfg.Plugin, pxy.cfg.PluginParams)
  97. if err != nil {
  98. return
  99. }
  100. }
  101. return
  102. }
  103. func (pxy *TcpProxy) Close() {
  104. if pxy.proxyPlugin != nil {
  105. pxy.proxyPlugin.Close()
  106. }
  107. }
  108. func (pxy *TcpProxy) InWorkConn(conn frpNet.Conn) {
  109. HandleTcpWorkConnection(&pxy.cfg.LocalSvrConf, pxy.proxyPlugin, &pxy.cfg.BaseProxyConf, conn,
  110. []byte(g.GlbClientCfg.Token))
  111. }
  112. // HTTP
  113. type HttpProxy struct {
  114. *BaseProxy
  115. cfg *config.HttpProxyConf
  116. proxyPlugin plugin.Plugin
  117. }
  118. func (pxy *HttpProxy) Run() (err error) {
  119. if pxy.cfg.Plugin != "" {
  120. pxy.proxyPlugin, err = plugin.Create(pxy.cfg.Plugin, pxy.cfg.PluginParams)
  121. if err != nil {
  122. return
  123. }
  124. }
  125. return
  126. }
  127. func (pxy *HttpProxy) Close() {
  128. if pxy.proxyPlugin != nil {
  129. pxy.proxyPlugin.Close()
  130. }
  131. }
  132. func (pxy *HttpProxy) InWorkConn(conn frpNet.Conn) {
  133. HandleTcpWorkConnection(&pxy.cfg.LocalSvrConf, pxy.proxyPlugin, &pxy.cfg.BaseProxyConf, conn,
  134. []byte(g.GlbClientCfg.Token))
  135. }
  136. // HTTPS
  137. type HttpsProxy struct {
  138. *BaseProxy
  139. cfg *config.HttpsProxyConf
  140. proxyPlugin plugin.Plugin
  141. }
  142. func (pxy *HttpsProxy) Run() (err error) {
  143. if pxy.cfg.Plugin != "" {
  144. pxy.proxyPlugin, err = plugin.Create(pxy.cfg.Plugin, pxy.cfg.PluginParams)
  145. if err != nil {
  146. return
  147. }
  148. }
  149. return
  150. }
  151. func (pxy *HttpsProxy) Close() {
  152. if pxy.proxyPlugin != nil {
  153. pxy.proxyPlugin.Close()
  154. }
  155. }
  156. func (pxy *HttpsProxy) InWorkConn(conn frpNet.Conn) {
  157. HandleTcpWorkConnection(&pxy.cfg.LocalSvrConf, pxy.proxyPlugin, &pxy.cfg.BaseProxyConf, conn,
  158. []byte(g.GlbClientCfg.Token))
  159. }
  160. // STCP
  161. type StcpProxy struct {
  162. *BaseProxy
  163. cfg *config.StcpProxyConf
  164. proxyPlugin plugin.Plugin
  165. }
  166. func (pxy *StcpProxy) Run() (err error) {
  167. if pxy.cfg.Plugin != "" {
  168. pxy.proxyPlugin, err = plugin.Create(pxy.cfg.Plugin, pxy.cfg.PluginParams)
  169. if err != nil {
  170. return
  171. }
  172. }
  173. return
  174. }
  175. func (pxy *StcpProxy) Close() {
  176. if pxy.proxyPlugin != nil {
  177. pxy.proxyPlugin.Close()
  178. }
  179. }
  180. func (pxy *StcpProxy) InWorkConn(conn frpNet.Conn) {
  181. HandleTcpWorkConnection(&pxy.cfg.LocalSvrConf, pxy.proxyPlugin, &pxy.cfg.BaseProxyConf, conn,
  182. []byte(g.GlbClientCfg.Token))
  183. }
  184. // XTCP
  185. type XtcpProxy struct {
  186. *BaseProxy
  187. cfg *config.XtcpProxyConf
  188. proxyPlugin plugin.Plugin
  189. }
  190. func (pxy *XtcpProxy) Run() (err error) {
  191. if pxy.cfg.Plugin != "" {
  192. pxy.proxyPlugin, err = plugin.Create(pxy.cfg.Plugin, pxy.cfg.PluginParams)
  193. if err != nil {
  194. return
  195. }
  196. }
  197. return
  198. }
  199. func (pxy *XtcpProxy) Close() {
  200. if pxy.proxyPlugin != nil {
  201. pxy.proxyPlugin.Close()
  202. }
  203. }
  204. func (pxy *XtcpProxy) InWorkConn(conn frpNet.Conn) {
  205. defer conn.Close()
  206. var natHoleSidMsg msg.NatHoleSid
  207. err := msg.ReadMsgInto(conn, &natHoleSidMsg)
  208. if err != nil {
  209. pxy.Error("xtcp read from workConn error: %v", err)
  210. return
  211. }
  212. natHoleClientMsg := &msg.NatHoleClient{
  213. ProxyName: pxy.cfg.ProxyName,
  214. Sid: natHoleSidMsg.Sid,
  215. }
  216. raddr, _ := net.ResolveUDPAddr("udp",
  217. fmt.Sprintf("%s:%d", g.GlbClientCfg.ServerAddr, g.GlbClientCfg.ServerUdpPort))
  218. clientConn, err := net.DialUDP("udp", nil, raddr)
  219. defer clientConn.Close()
  220. err = msg.WriteMsg(clientConn, natHoleClientMsg)
  221. if err != nil {
  222. pxy.Error("send natHoleClientMsg to server error: %v", err)
  223. return
  224. }
  225. // Wait for client address at most 5 seconds.
  226. var natHoleRespMsg msg.NatHoleResp
  227. clientConn.SetReadDeadline(time.Now().Add(5 * time.Second))
  228. buf := pool.GetBuf(1024)
  229. n, err := clientConn.Read(buf)
  230. if err != nil {
  231. pxy.Error("get natHoleRespMsg error: %v", err)
  232. return
  233. }
  234. err = msg.ReadMsgInto(bytes.NewReader(buf[:n]), &natHoleRespMsg)
  235. if err != nil {
  236. pxy.Error("get natHoleRespMsg error: %v", err)
  237. return
  238. }
  239. clientConn.SetReadDeadline(time.Time{})
  240. clientConn.Close()
  241. if natHoleRespMsg.Error != "" {
  242. pxy.Error("natHoleRespMsg get error info: %s", natHoleRespMsg.Error)
  243. return
  244. }
  245. pxy.Trace("get natHoleRespMsg, sid [%s], client address [%s] visitor address [%s]", natHoleRespMsg.Sid, natHoleRespMsg.ClientAddr, natHoleRespMsg.VisitorAddr)
  246. // Send detect message
  247. array := strings.Split(natHoleRespMsg.VisitorAddr, ":")
  248. if len(array) <= 1 {
  249. pxy.Error("get NatHoleResp visitor address error: %v", natHoleRespMsg.VisitorAddr)
  250. }
  251. laddr, _ := net.ResolveUDPAddr("udp", clientConn.LocalAddr().String())
  252. /*
  253. for i := 1000; i < 65000; i++ {
  254. pxy.sendDetectMsg(array[0], int64(i), laddr, "a")
  255. }
  256. */
  257. port, err := strconv.ParseInt(array[1], 10, 64)
  258. if err != nil {
  259. pxy.Error("get natHoleResp visitor address error: %v", natHoleRespMsg.VisitorAddr)
  260. return
  261. }
  262. pxy.sendDetectMsg(array[0], int(port), laddr, []byte(natHoleRespMsg.Sid))
  263. pxy.Trace("send all detect msg done")
  264. msg.WriteMsg(conn, &msg.NatHoleClientDetectOK{})
  265. // Listen for clientConn's address and wait for visitor connection
  266. lConn, err := net.ListenUDP("udp", laddr)
  267. if err != nil {
  268. pxy.Error("listen on visitorConn's local adress error: %v", err)
  269. return
  270. }
  271. defer lConn.Close()
  272. lConn.SetReadDeadline(time.Now().Add(8 * time.Second))
  273. sidBuf := pool.GetBuf(1024)
  274. var uAddr *net.UDPAddr
  275. n, uAddr, err = lConn.ReadFromUDP(sidBuf)
  276. if err != nil {
  277. pxy.Warn("get sid from visitor error: %v", err)
  278. return
  279. }
  280. lConn.SetReadDeadline(time.Time{})
  281. if string(sidBuf[:n]) != natHoleRespMsg.Sid {
  282. pxy.Warn("incorrect sid from visitor")
  283. return
  284. }
  285. pool.PutBuf(sidBuf)
  286. pxy.Info("nat hole connection make success, sid [%s]", natHoleRespMsg.Sid)
  287. lConn.WriteToUDP(sidBuf[:n], uAddr)
  288. kcpConn, err := frpNet.NewKcpConnFromUdp(lConn, false, natHoleRespMsg.VisitorAddr)
  289. if err != nil {
  290. pxy.Error("create kcp connection from udp connection error: %v", err)
  291. return
  292. }
  293. fmuxCfg := fmux.DefaultConfig()
  294. fmuxCfg.KeepAliveInterval = 5 * time.Second
  295. fmuxCfg.LogOutput = ioutil.Discard
  296. sess, err := fmux.Server(kcpConn, fmuxCfg)
  297. if err != nil {
  298. pxy.Error("create yamux server from kcp connection error: %v", err)
  299. return
  300. }
  301. defer sess.Close()
  302. muxConn, err := sess.Accept()
  303. if err != nil {
  304. pxy.Error("accept for yamux connection error: %v", err)
  305. return
  306. }
  307. HandleTcpWorkConnection(&pxy.cfg.LocalSvrConf, pxy.proxyPlugin, &pxy.cfg.BaseProxyConf,
  308. frpNet.WrapConn(muxConn), []byte(pxy.cfg.Sk))
  309. }
  310. func (pxy *XtcpProxy) sendDetectMsg(addr string, port int, laddr *net.UDPAddr, content []byte) (err error) {
  311. daddr, err := net.ResolveUDPAddr("udp", fmt.Sprintf("%s:%d", addr, port))
  312. if err != nil {
  313. return err
  314. }
  315. tConn, err := net.DialUDP("udp", laddr, daddr)
  316. if err != nil {
  317. return err
  318. }
  319. //uConn := ipv4.NewConn(tConn)
  320. //uConn.SetTTL(3)
  321. tConn.Write(content)
  322. tConn.Close()
  323. return nil
  324. }
  325. // UDP
  326. type UdpProxy struct {
  327. *BaseProxy
  328. cfg *config.UdpProxyConf
  329. localAddr *net.UDPAddr
  330. readCh chan *msg.UdpPacket
  331. // include msg.UdpPacket and msg.Ping
  332. sendCh chan msg.Message
  333. workConn frpNet.Conn
  334. }
  335. func (pxy *UdpProxy) Run() (err error) {
  336. pxy.localAddr, err = net.ResolveUDPAddr("udp", fmt.Sprintf("%s:%d", pxy.cfg.LocalIp, pxy.cfg.LocalPort))
  337. if err != nil {
  338. return
  339. }
  340. return
  341. }
  342. func (pxy *UdpProxy) Close() {
  343. pxy.mu.Lock()
  344. defer pxy.mu.Unlock()
  345. if !pxy.closed {
  346. pxy.closed = true
  347. if pxy.workConn != nil {
  348. pxy.workConn.Close()
  349. }
  350. if pxy.readCh != nil {
  351. close(pxy.readCh)
  352. }
  353. if pxy.sendCh != nil {
  354. close(pxy.sendCh)
  355. }
  356. }
  357. }
  358. func (pxy *UdpProxy) InWorkConn(conn frpNet.Conn) {
  359. pxy.Info("incoming a new work connection for udp proxy, %s", conn.RemoteAddr().String())
  360. // close resources releated with old workConn
  361. pxy.Close()
  362. pxy.mu.Lock()
  363. pxy.workConn = conn
  364. pxy.readCh = make(chan *msg.UdpPacket, 1024)
  365. pxy.sendCh = make(chan msg.Message, 1024)
  366. pxy.closed = false
  367. pxy.mu.Unlock()
  368. workConnReaderFn := func(conn net.Conn, readCh chan *msg.UdpPacket) {
  369. for {
  370. var udpMsg msg.UdpPacket
  371. if errRet := msg.ReadMsgInto(conn, &udpMsg); errRet != nil {
  372. pxy.Warn("read from workConn for udp error: %v", errRet)
  373. return
  374. }
  375. if errRet := errors.PanicToError(func() {
  376. pxy.Trace("get udp package from workConn: %s", udpMsg.Content)
  377. readCh <- &udpMsg
  378. }); errRet != nil {
  379. pxy.Info("reader goroutine for udp work connection closed: %v", errRet)
  380. return
  381. }
  382. }
  383. }
  384. workConnSenderFn := func(conn net.Conn, sendCh chan msg.Message) {
  385. defer func() {
  386. pxy.Info("writer goroutine for udp work connection closed")
  387. }()
  388. var errRet error
  389. for rawMsg := range sendCh {
  390. switch m := rawMsg.(type) {
  391. case *msg.UdpPacket:
  392. pxy.Trace("send udp package to workConn: %s", m.Content)
  393. case *msg.Ping:
  394. pxy.Trace("send ping message to udp workConn")
  395. }
  396. if errRet = msg.WriteMsg(conn, rawMsg); errRet != nil {
  397. pxy.Error("udp work write error: %v", errRet)
  398. return
  399. }
  400. }
  401. }
  402. heartbeatFn := func(conn net.Conn, sendCh chan msg.Message) {
  403. var errRet error
  404. for {
  405. time.Sleep(time.Duration(30) * time.Second)
  406. if errRet = errors.PanicToError(func() {
  407. sendCh <- &msg.Ping{}
  408. }); errRet != nil {
  409. pxy.Trace("heartbeat goroutine for udp work connection closed")
  410. break
  411. }
  412. }
  413. }
  414. go workConnSenderFn(pxy.workConn, pxy.sendCh)
  415. go workConnReaderFn(pxy.workConn, pxy.readCh)
  416. go heartbeatFn(pxy.workConn, pxy.sendCh)
  417. udp.Forwarder(pxy.localAddr, pxy.readCh, pxy.sendCh)
  418. }
  419. // Common handler for tcp work connections.
  420. func HandleTcpWorkConnection(localInfo *config.LocalSvrConf, proxyPlugin plugin.Plugin,
  421. baseInfo *config.BaseProxyConf, workConn frpNet.Conn, encKey []byte) {
  422. var (
  423. remote io.ReadWriteCloser
  424. err error
  425. )
  426. remote = workConn
  427. if baseInfo.UseEncryption {
  428. remote, err = frpIo.WithEncryption(remote, encKey)
  429. if err != nil {
  430. workConn.Close()
  431. workConn.Error("create encryption stream error: %v", err)
  432. return
  433. }
  434. }
  435. if baseInfo.UseCompression {
  436. remote = frpIo.WithCompression(remote)
  437. }
  438. if proxyPlugin != nil {
  439. // if plugin is set, let plugin handle connections first
  440. workConn.Debug("handle by plugin: %s", proxyPlugin.Name())
  441. proxyPlugin.Handle(remote, workConn)
  442. workConn.Debug("handle by plugin finished")
  443. return
  444. } else {
  445. localConn, err := frpNet.ConnectServer("tcp", fmt.Sprintf("%s:%d", localInfo.LocalIp, localInfo.LocalPort))
  446. if err != nil {
  447. workConn.Close()
  448. workConn.Error("connect to local service [%s:%d] error: %v", localInfo.LocalIp, localInfo.LocalPort, err)
  449. return
  450. }
  451. workConn.Debug("join connections, localConn(l[%s] r[%s]) workConn(l[%s] r[%s])", localConn.LocalAddr().String(),
  452. localConn.RemoteAddr().String(), workConn.LocalAddr().String(), workConn.RemoteAddr().String())
  453. frpIo.Join(localConn, remote)
  454. workConn.Debug("join connections closed")
  455. }
  456. }