visitor.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  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 client
  15. import (
  16. "bytes"
  17. "context"
  18. "fmt"
  19. "io"
  20. "net"
  21. "strconv"
  22. "sync"
  23. "time"
  24. "github.com/fatedier/frp/pkg/config"
  25. "github.com/fatedier/frp/pkg/msg"
  26. "github.com/fatedier/frp/pkg/proto/udp"
  27. frpNet "github.com/fatedier/frp/pkg/util/net"
  28. "github.com/fatedier/frp/pkg/util/util"
  29. "github.com/fatedier/frp/pkg/util/xlog"
  30. "github.com/fatedier/golib/errors"
  31. frpIo "github.com/fatedier/golib/io"
  32. "github.com/fatedier/golib/pool"
  33. fmux "github.com/hashicorp/yamux"
  34. )
  35. // Visitor is used for forward traffics from local port tot remote service.
  36. type Visitor interface {
  37. Run() error
  38. Close()
  39. }
  40. func NewVisitor(ctx context.Context, ctl *Control, cfg config.VisitorConf) (visitor Visitor) {
  41. xl := xlog.FromContextSafe(ctx).Spawn().AppendPrefix(cfg.GetBaseInfo().ProxyName)
  42. baseVisitor := BaseVisitor{
  43. ctl: ctl,
  44. ctx: xlog.NewContext(ctx, xl),
  45. }
  46. switch cfg := cfg.(type) {
  47. case *config.STCPVisitorConf:
  48. visitor = &STCPVisitor{
  49. BaseVisitor: &baseVisitor,
  50. cfg: cfg,
  51. }
  52. case *config.XTCPVisitorConf:
  53. visitor = &XTCPVisitor{
  54. BaseVisitor: &baseVisitor,
  55. cfg: cfg,
  56. }
  57. case *config.SUDPVisitorConf:
  58. visitor = &SUDPVisitor{
  59. BaseVisitor: &baseVisitor,
  60. cfg: cfg,
  61. checkCloseCh: make(chan struct{}),
  62. }
  63. }
  64. return
  65. }
  66. type BaseVisitor struct {
  67. ctl *Control
  68. l net.Listener
  69. closed bool
  70. mu sync.RWMutex
  71. ctx context.Context
  72. }
  73. type STCPVisitor struct {
  74. *BaseVisitor
  75. cfg *config.STCPVisitorConf
  76. }
  77. func (sv *STCPVisitor) Run() (err error) {
  78. sv.l, err = net.Listen("tcp", net.JoinHostPort(sv.cfg.BindAddr, strconv.Itoa(sv.cfg.BindPort)))
  79. if err != nil {
  80. return
  81. }
  82. go sv.worker()
  83. return
  84. }
  85. func (sv *STCPVisitor) Close() {
  86. sv.l.Close()
  87. }
  88. func (sv *STCPVisitor) worker() {
  89. xl := xlog.FromContextSafe(sv.ctx)
  90. for {
  91. conn, err := sv.l.Accept()
  92. if err != nil {
  93. xl.Warn("stcp local listener closed")
  94. return
  95. }
  96. go sv.handleConn(conn)
  97. }
  98. }
  99. func (sv *STCPVisitor) handleConn(userConn net.Conn) {
  100. xl := xlog.FromContextSafe(sv.ctx)
  101. defer userConn.Close()
  102. xl.Debug("get a new stcp user connection")
  103. visitorConn, err := sv.ctl.connectServer()
  104. if err != nil {
  105. return
  106. }
  107. defer visitorConn.Close()
  108. now := time.Now().Unix()
  109. newVisitorConnMsg := &msg.NewVisitorConn{
  110. ProxyName: sv.cfg.ServerName,
  111. SignKey: util.GetAuthKey(sv.cfg.Sk, now),
  112. Timestamp: now,
  113. UseEncryption: sv.cfg.UseEncryption,
  114. UseCompression: sv.cfg.UseCompression,
  115. }
  116. err = msg.WriteMsg(visitorConn, newVisitorConnMsg)
  117. if err != nil {
  118. xl.Warn("send newVisitorConnMsg to server error: %v", err)
  119. return
  120. }
  121. var newVisitorConnRespMsg msg.NewVisitorConnResp
  122. visitorConn.SetReadDeadline(time.Now().Add(10 * time.Second))
  123. err = msg.ReadMsgInto(visitorConn, &newVisitorConnRespMsg)
  124. if err != nil {
  125. xl.Warn("get newVisitorConnRespMsg error: %v", err)
  126. return
  127. }
  128. visitorConn.SetReadDeadline(time.Time{})
  129. if newVisitorConnRespMsg.Error != "" {
  130. xl.Warn("start new visitor connection error: %s", newVisitorConnRespMsg.Error)
  131. return
  132. }
  133. var remote io.ReadWriteCloser
  134. remote = visitorConn
  135. if sv.cfg.UseEncryption {
  136. remote, err = frpIo.WithEncryption(remote, []byte(sv.cfg.Sk))
  137. if err != nil {
  138. xl.Error("create encryption stream error: %v", err)
  139. return
  140. }
  141. }
  142. if sv.cfg.UseCompression {
  143. remote = frpIo.WithCompression(remote)
  144. }
  145. frpIo.Join(userConn, remote)
  146. }
  147. type XTCPVisitor struct {
  148. *BaseVisitor
  149. cfg *config.XTCPVisitorConf
  150. }
  151. func (sv *XTCPVisitor) Run() (err error) {
  152. sv.l, err = net.Listen("tcp", net.JoinHostPort(sv.cfg.BindAddr, strconv.Itoa(sv.cfg.BindPort)))
  153. if err != nil {
  154. return
  155. }
  156. go sv.worker()
  157. return
  158. }
  159. func (sv *XTCPVisitor) Close() {
  160. sv.l.Close()
  161. }
  162. func (sv *XTCPVisitor) worker() {
  163. xl := xlog.FromContextSafe(sv.ctx)
  164. for {
  165. conn, err := sv.l.Accept()
  166. if err != nil {
  167. xl.Warn("xtcp local listener closed")
  168. return
  169. }
  170. go sv.handleConn(conn)
  171. }
  172. }
  173. func (sv *XTCPVisitor) handleConn(userConn net.Conn) {
  174. xl := xlog.FromContextSafe(sv.ctx)
  175. defer userConn.Close()
  176. xl.Debug("get a new xtcp user connection")
  177. if sv.ctl.serverUDPPort == 0 {
  178. xl.Error("xtcp is not supported by server")
  179. return
  180. }
  181. raddr, err := net.ResolveUDPAddr("udp",
  182. fmt.Sprintf("%s:%d", sv.ctl.clientCfg.ServerAddr, sv.ctl.serverUDPPort))
  183. if err != nil {
  184. xl.Error("resolve server UDP addr error")
  185. return
  186. }
  187. visitorConn, err := net.DialUDP("udp", nil, raddr)
  188. if err != nil {
  189. xl.Warn("dial server udp addr error: %v", err)
  190. return
  191. }
  192. defer visitorConn.Close()
  193. now := time.Now().Unix()
  194. natHoleVisitorMsg := &msg.NatHoleVisitor{
  195. ProxyName: sv.cfg.ServerName,
  196. SignKey: util.GetAuthKey(sv.cfg.Sk, now),
  197. Timestamp: now,
  198. }
  199. err = msg.WriteMsg(visitorConn, natHoleVisitorMsg)
  200. if err != nil {
  201. xl.Warn("send natHoleVisitorMsg to server error: %v", err)
  202. return
  203. }
  204. // Wait for client address at most 10 seconds.
  205. var natHoleRespMsg msg.NatHoleResp
  206. visitorConn.SetReadDeadline(time.Now().Add(10 * time.Second))
  207. buf := pool.GetBuf(1024)
  208. n, err := visitorConn.Read(buf)
  209. if err != nil {
  210. xl.Warn("get natHoleRespMsg error: %v", err)
  211. return
  212. }
  213. err = msg.ReadMsgInto(bytes.NewReader(buf[:n]), &natHoleRespMsg)
  214. if err != nil {
  215. xl.Warn("get natHoleRespMsg error: %v", err)
  216. return
  217. }
  218. visitorConn.SetReadDeadline(time.Time{})
  219. pool.PutBuf(buf)
  220. if natHoleRespMsg.Error != "" {
  221. xl.Error("natHoleRespMsg get error info: %s", natHoleRespMsg.Error)
  222. return
  223. }
  224. xl.Trace("get natHoleRespMsg, sid [%s], client address [%s], visitor address [%s]", natHoleRespMsg.Sid, natHoleRespMsg.ClientAddr, natHoleRespMsg.VisitorAddr)
  225. // Close visitorConn, so we can use it's local address.
  226. visitorConn.Close()
  227. // send sid message to client
  228. laddr, _ := net.ResolveUDPAddr("udp", visitorConn.LocalAddr().String())
  229. daddr, err := net.ResolveUDPAddr("udp", natHoleRespMsg.ClientAddr)
  230. if err != nil {
  231. xl.Error("resolve client udp address error: %v", err)
  232. return
  233. }
  234. lConn, err := net.DialUDP("udp", laddr, daddr)
  235. if err != nil {
  236. xl.Error("dial client udp address error: %v", err)
  237. return
  238. }
  239. defer lConn.Close()
  240. lConn.Write([]byte(natHoleRespMsg.Sid))
  241. // read ack sid from client
  242. sidBuf := pool.GetBuf(1024)
  243. lConn.SetReadDeadline(time.Now().Add(8 * time.Second))
  244. n, err = lConn.Read(sidBuf)
  245. if err != nil {
  246. xl.Warn("get sid from client error: %v", err)
  247. return
  248. }
  249. lConn.SetReadDeadline(time.Time{})
  250. if string(sidBuf[:n]) != natHoleRespMsg.Sid {
  251. xl.Warn("incorrect sid from client")
  252. return
  253. }
  254. pool.PutBuf(sidBuf)
  255. xl.Info("nat hole connection make success, sid [%s]", natHoleRespMsg.Sid)
  256. // wrap kcp connection
  257. var remote io.ReadWriteCloser
  258. remote, err = frpNet.NewKCPConnFromUDP(lConn, true, natHoleRespMsg.ClientAddr)
  259. if err != nil {
  260. xl.Error("create kcp connection from udp connection error: %v", err)
  261. return
  262. }
  263. fmuxCfg := fmux.DefaultConfig()
  264. fmuxCfg.KeepAliveInterval = 5 * time.Second
  265. fmuxCfg.LogOutput = io.Discard
  266. sess, err := fmux.Client(remote, fmuxCfg)
  267. if err != nil {
  268. xl.Error("create yamux session error: %v", err)
  269. return
  270. }
  271. defer sess.Close()
  272. muxConn, err := sess.Open()
  273. if err != nil {
  274. xl.Error("open yamux stream error: %v", err)
  275. return
  276. }
  277. var muxConnRWCloser io.ReadWriteCloser = muxConn
  278. if sv.cfg.UseEncryption {
  279. muxConnRWCloser, err = frpIo.WithEncryption(muxConnRWCloser, []byte(sv.cfg.Sk))
  280. if err != nil {
  281. xl.Error("create encryption stream error: %v", err)
  282. return
  283. }
  284. }
  285. if sv.cfg.UseCompression {
  286. muxConnRWCloser = frpIo.WithCompression(muxConnRWCloser)
  287. }
  288. frpIo.Join(userConn, muxConnRWCloser)
  289. xl.Debug("join connections closed")
  290. }
  291. type SUDPVisitor struct {
  292. *BaseVisitor
  293. checkCloseCh chan struct{}
  294. // udpConn is the listener of udp packet
  295. udpConn *net.UDPConn
  296. readCh chan *msg.UDPPacket
  297. sendCh chan *msg.UDPPacket
  298. cfg *config.SUDPVisitorConf
  299. }
  300. // SUDP Run start listen a udp port
  301. func (sv *SUDPVisitor) Run() (err error) {
  302. xl := xlog.FromContextSafe(sv.ctx)
  303. addr, err := net.ResolveUDPAddr("udp", net.JoinHostPort(sv.cfg.BindAddr, strconv.Itoa(sv.cfg.BindPort)))
  304. if err != nil {
  305. return fmt.Errorf("sudp ResolveUDPAddr error: %v", err)
  306. }
  307. sv.udpConn, err = net.ListenUDP("udp", addr)
  308. if err != nil {
  309. return fmt.Errorf("listen udp port %s error: %v", addr.String(), err)
  310. }
  311. sv.sendCh = make(chan *msg.UDPPacket, 1024)
  312. sv.readCh = make(chan *msg.UDPPacket, 1024)
  313. xl.Info("sudp start to work, listen on %s", addr)
  314. go sv.dispatcher()
  315. go udp.ForwardUserConn(sv.udpConn, sv.readCh, sv.sendCh, int(sv.ctl.clientCfg.UDPPacketSize))
  316. return
  317. }
  318. func (sv *SUDPVisitor) dispatcher() {
  319. xl := xlog.FromContextSafe(sv.ctx)
  320. for {
  321. // loop for get frpc to frps tcp conn
  322. // setup worker
  323. // wait worker to finished
  324. // retry or exit
  325. visitorConn, err := sv.getNewVisitorConn()
  326. if err != nil {
  327. // check if proxy is closed
  328. // if checkCloseCh is close, we will return, other case we will continue to reconnect
  329. select {
  330. case <-sv.checkCloseCh:
  331. xl.Info("frpc sudp visitor proxy is closed")
  332. return
  333. default:
  334. }
  335. time.Sleep(3 * time.Second)
  336. xl.Warn("newVisitorConn to frps error: %v, try to reconnect", err)
  337. continue
  338. }
  339. sv.worker(visitorConn)
  340. select {
  341. case <-sv.checkCloseCh:
  342. return
  343. default:
  344. }
  345. }
  346. }
  347. func (sv *SUDPVisitor) worker(workConn net.Conn) {
  348. xl := xlog.FromContextSafe(sv.ctx)
  349. xl.Debug("starting sudp proxy worker")
  350. wg := &sync.WaitGroup{}
  351. wg.Add(2)
  352. closeCh := make(chan struct{})
  353. // udp service -> frpc -> frps -> frpc visitor -> user
  354. workConnReaderFn := func(conn net.Conn) {
  355. defer func() {
  356. conn.Close()
  357. close(closeCh)
  358. wg.Done()
  359. }()
  360. for {
  361. var (
  362. rawMsg msg.Message
  363. errRet error
  364. )
  365. // frpc will send heartbeat in workConn to frpc visitor for keeping alive
  366. conn.SetReadDeadline(time.Now().Add(60 * time.Second))
  367. if rawMsg, errRet = msg.ReadMsg(conn); errRet != nil {
  368. xl.Warn("read from workconn for user udp conn error: %v", errRet)
  369. return
  370. }
  371. conn.SetReadDeadline(time.Time{})
  372. switch m := rawMsg.(type) {
  373. case *msg.Ping:
  374. xl.Debug("frpc visitor get ping message from frpc")
  375. continue
  376. case *msg.UDPPacket:
  377. if errRet := errors.PanicToError(func() {
  378. sv.readCh <- m
  379. xl.Trace("frpc visitor get udp packet from workConn: %s", m.Content)
  380. }); errRet != nil {
  381. xl.Info("reader goroutine for udp work connection closed")
  382. return
  383. }
  384. }
  385. }
  386. }
  387. // udp service <- frpc <- frps <- frpc visitor <- user
  388. workConnSenderFn := func(conn net.Conn) {
  389. defer func() {
  390. conn.Close()
  391. wg.Done()
  392. }()
  393. var errRet error
  394. for {
  395. select {
  396. case udpMsg, ok := <-sv.sendCh:
  397. if !ok {
  398. xl.Info("sender goroutine for udp work connection closed")
  399. return
  400. }
  401. if errRet = msg.WriteMsg(conn, udpMsg); errRet != nil {
  402. xl.Warn("sender goroutine for udp work connection closed: %v", errRet)
  403. return
  404. }
  405. xl.Trace("send udp package to workConn: %s", udpMsg.Content)
  406. case <-closeCh:
  407. return
  408. }
  409. }
  410. }
  411. go workConnReaderFn(workConn)
  412. go workConnSenderFn(workConn)
  413. wg.Wait()
  414. xl.Info("sudp worker is closed")
  415. }
  416. func (sv *SUDPVisitor) getNewVisitorConn() (net.Conn, error) {
  417. xl := xlog.FromContextSafe(sv.ctx)
  418. visitorConn, err := sv.ctl.connectServer()
  419. if err != nil {
  420. return nil, fmt.Errorf("frpc connect frps error: %v", err)
  421. }
  422. now := time.Now().Unix()
  423. newVisitorConnMsg := &msg.NewVisitorConn{
  424. ProxyName: sv.cfg.ServerName,
  425. SignKey: util.GetAuthKey(sv.cfg.Sk, now),
  426. Timestamp: now,
  427. UseEncryption: sv.cfg.UseEncryption,
  428. UseCompression: sv.cfg.UseCompression,
  429. }
  430. err = msg.WriteMsg(visitorConn, newVisitorConnMsg)
  431. if err != nil {
  432. return nil, fmt.Errorf("frpc send newVisitorConnMsg to frps error: %v", err)
  433. }
  434. var newVisitorConnRespMsg msg.NewVisitorConnResp
  435. visitorConn.SetReadDeadline(time.Now().Add(10 * time.Second))
  436. err = msg.ReadMsgInto(visitorConn, &newVisitorConnRespMsg)
  437. if err != nil {
  438. return nil, fmt.Errorf("frpc read newVisitorConnRespMsg error: %v", err)
  439. }
  440. visitorConn.SetReadDeadline(time.Time{})
  441. if newVisitorConnRespMsg.Error != "" {
  442. return nil, fmt.Errorf("start new visitor connection error: %s", newVisitorConnRespMsg.Error)
  443. }
  444. var remote io.ReadWriteCloser
  445. remote = visitorConn
  446. if sv.cfg.UseEncryption {
  447. remote, err = frpIo.WithEncryption(remote, []byte(sv.cfg.Sk))
  448. if err != nil {
  449. xl.Error("create encryption stream error: %v", err)
  450. return nil, err
  451. }
  452. }
  453. if sv.cfg.UseCompression {
  454. remote = frpIo.WithCompression(remote)
  455. }
  456. return frpNet.WrapReadWriteCloserToConn(remote, visitorConn), nil
  457. }
  458. func (sv *SUDPVisitor) Close() {
  459. sv.mu.Lock()
  460. defer sv.mu.Unlock()
  461. select {
  462. case <-sv.checkCloseCh:
  463. return
  464. default:
  465. close(sv.checkCloseCh)
  466. }
  467. if sv.udpConn != nil {
  468. sv.udpConn.Close()
  469. }
  470. close(sv.readCh)
  471. close(sv.sendCh)
  472. }