proxy.go 14 KB

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