visitor.go 14 KB

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