1
0

visitor.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  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 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. 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. raddr, err := net.ResolveUDPAddr("udp",
  181. net.JoinHostPort(sv.ctl.clientCfg.ServerAddr, strconv.Itoa(sv.ctl.serverUDPPort)))
  182. if err != nil {
  183. xl.Error("resolve server UDP addr error")
  184. return
  185. }
  186. visitorConn, err := net.DialUDP("udp", nil, raddr)
  187. if err != nil {
  188. xl.Warn("dial server udp addr error: %v", err)
  189. return
  190. }
  191. defer visitorConn.Close()
  192. now := time.Now().Unix()
  193. natHoleVisitorMsg := &msg.NatHoleVisitor{
  194. ProxyName: sv.cfg.ServerName,
  195. SignKey: util.GetAuthKey(sv.cfg.Sk, now),
  196. Timestamp: now,
  197. }
  198. err = msg.WriteMsg(visitorConn, natHoleVisitorMsg)
  199. if err != nil {
  200. xl.Warn("send natHoleVisitorMsg to server error: %v", err)
  201. return
  202. }
  203. // Wait for client address at most 10 seconds.
  204. var natHoleRespMsg msg.NatHoleResp
  205. _ = visitorConn.SetReadDeadline(time.Now().Add(10 * time.Second))
  206. buf := pool.GetBuf(1024)
  207. n, err := visitorConn.Read(buf)
  208. if err != nil {
  209. xl.Warn("get natHoleRespMsg error: %v", err)
  210. return
  211. }
  212. err = msg.ReadMsgInto(bytes.NewReader(buf[:n]), &natHoleRespMsg)
  213. if err != nil {
  214. xl.Warn("get natHoleRespMsg error: %v", err)
  215. return
  216. }
  217. _ = visitorConn.SetReadDeadline(time.Time{})
  218. pool.PutBuf(buf)
  219. if natHoleRespMsg.Error != "" {
  220. xl.Error("natHoleRespMsg get error info: %s", natHoleRespMsg.Error)
  221. return
  222. }
  223. xl.Trace("get natHoleRespMsg, sid [%s], client address [%s], visitor address [%s]", natHoleRespMsg.Sid, natHoleRespMsg.ClientAddr, natHoleRespMsg.VisitorAddr)
  224. // Close visitorConn, so we can use it's local address.
  225. visitorConn.Close()
  226. // send sid message to client
  227. laddr, _ := net.ResolveUDPAddr("udp", visitorConn.LocalAddr().String())
  228. daddr, err := net.ResolveUDPAddr("udp", natHoleRespMsg.ClientAddr)
  229. if err != nil {
  230. xl.Error("resolve client udp address error: %v", err)
  231. return
  232. }
  233. lConn, err := net.DialUDP("udp", laddr, daddr)
  234. if err != nil {
  235. xl.Error("dial client udp address error: %v", err)
  236. return
  237. }
  238. defer lConn.Close()
  239. if _, err := lConn.Write([]byte(natHoleRespMsg.Sid)); err != nil {
  240. xl.Error("write sid error: %v", err)
  241. return
  242. }
  243. // read ack sid from client
  244. sidBuf := pool.GetBuf(1024)
  245. _ = lConn.SetReadDeadline(time.Now().Add(8 * time.Second))
  246. n, err = lConn.Read(sidBuf)
  247. if err != nil {
  248. xl.Warn("get sid from client error: %v", err)
  249. return
  250. }
  251. _ = lConn.SetReadDeadline(time.Time{})
  252. if string(sidBuf[:n]) != natHoleRespMsg.Sid {
  253. xl.Warn("incorrect sid from client")
  254. return
  255. }
  256. pool.PutBuf(sidBuf)
  257. xl.Info("nat hole connection make success, sid [%s]", natHoleRespMsg.Sid)
  258. // wrap kcp connection
  259. var remote io.ReadWriteCloser
  260. remote, err = frpNet.NewKCPConnFromUDP(lConn, true, natHoleRespMsg.ClientAddr)
  261. if err != nil {
  262. xl.Error("create kcp connection from udp connection error: %v", err)
  263. return
  264. }
  265. fmuxCfg := fmux.DefaultConfig()
  266. fmuxCfg.KeepAliveInterval = 5 * time.Second
  267. fmuxCfg.LogOutput = io.Discard
  268. sess, err := fmux.Client(remote, fmuxCfg)
  269. if err != nil {
  270. xl.Error("create yamux session error: %v", err)
  271. return
  272. }
  273. defer sess.Close()
  274. muxConn, err := sess.Open()
  275. if err != nil {
  276. xl.Error("open yamux stream error: %v", err)
  277. return
  278. }
  279. var muxConnRWCloser io.ReadWriteCloser = muxConn
  280. if sv.cfg.UseEncryption {
  281. muxConnRWCloser, err = frpIo.WithEncryption(muxConnRWCloser, []byte(sv.cfg.Sk))
  282. if err != nil {
  283. xl.Error("create encryption stream error: %v", err)
  284. return
  285. }
  286. }
  287. if sv.cfg.UseCompression {
  288. muxConnRWCloser = frpIo.WithCompression(muxConnRWCloser)
  289. }
  290. frpIo.Join(userConn, muxConnRWCloser)
  291. xl.Debug("join connections closed")
  292. }
  293. type SUDPVisitor struct {
  294. *BaseVisitor
  295. checkCloseCh chan struct{}
  296. // udpConn is the listener of udp packet
  297. udpConn *net.UDPConn
  298. readCh chan *msg.UDPPacket
  299. sendCh chan *msg.UDPPacket
  300. cfg *config.SUDPVisitorConf
  301. }
  302. // SUDP Run start listen a udp port
  303. func (sv *SUDPVisitor) Run() (err error) {
  304. xl := xlog.FromContextSafe(sv.ctx)
  305. addr, err := net.ResolveUDPAddr("udp", net.JoinHostPort(sv.cfg.BindAddr, strconv.Itoa(sv.cfg.BindPort)))
  306. if err != nil {
  307. return fmt.Errorf("sudp ResolveUDPAddr error: %v", err)
  308. }
  309. sv.udpConn, err = net.ListenUDP("udp", addr)
  310. if err != nil {
  311. return fmt.Errorf("listen udp port %s error: %v", addr.String(), err)
  312. }
  313. sv.sendCh = make(chan *msg.UDPPacket, 1024)
  314. sv.readCh = make(chan *msg.UDPPacket, 1024)
  315. xl.Info("sudp start to work, listen on %s", addr)
  316. go sv.dispatcher()
  317. go udp.ForwardUserConn(sv.udpConn, sv.readCh, sv.sendCh, int(sv.ctl.clientCfg.UDPPacketSize))
  318. return
  319. }
  320. func (sv *SUDPVisitor) dispatcher() {
  321. xl := xlog.FromContextSafe(sv.ctx)
  322. var (
  323. visitorConn net.Conn
  324. err error
  325. firstPacket *msg.UDPPacket
  326. )
  327. for {
  328. select {
  329. case firstPacket = <-sv.sendCh:
  330. if firstPacket == nil {
  331. xl.Info("frpc sudp visitor proxy is closed")
  332. return
  333. }
  334. case <-sv.checkCloseCh:
  335. xl.Info("frpc sudp visitor proxy is closed")
  336. return
  337. }
  338. visitorConn, err = sv.getNewVisitorConn()
  339. if err != nil {
  340. xl.Warn("newVisitorConn to frps error: %v, try to reconnect", err)
  341. continue
  342. }
  343. // visitorConn always be closed when worker done.
  344. sv.worker(visitorConn, firstPacket)
  345. select {
  346. case <-sv.checkCloseCh:
  347. return
  348. default:
  349. }
  350. }
  351. }
  352. func (sv *SUDPVisitor) worker(workConn net.Conn, firstPacket *msg.UDPPacket) {
  353. xl := xlog.FromContextSafe(sv.ctx)
  354. xl.Debug("starting sudp proxy worker")
  355. wg := &sync.WaitGroup{}
  356. wg.Add(2)
  357. closeCh := make(chan struct{})
  358. // udp service -> frpc -> frps -> frpc visitor -> user
  359. workConnReaderFn := func(conn net.Conn) {
  360. defer func() {
  361. conn.Close()
  362. close(closeCh)
  363. wg.Done()
  364. }()
  365. for {
  366. var (
  367. rawMsg msg.Message
  368. errRet error
  369. )
  370. // frpc will send heartbeat in workConn to frpc visitor for keeping alive
  371. _ = conn.SetReadDeadline(time.Now().Add(60 * time.Second))
  372. if rawMsg, errRet = msg.ReadMsg(conn); errRet != nil {
  373. xl.Warn("read from workconn for user udp conn error: %v", errRet)
  374. return
  375. }
  376. _ = conn.SetReadDeadline(time.Time{})
  377. switch m := rawMsg.(type) {
  378. case *msg.Ping:
  379. xl.Debug("frpc visitor get ping message from frpc")
  380. continue
  381. case *msg.UDPPacket:
  382. if errRet := errors.PanicToError(func() {
  383. sv.readCh <- m
  384. xl.Trace("frpc visitor get udp packet from workConn: %s", m.Content)
  385. }); errRet != nil {
  386. xl.Info("reader goroutine for udp work connection closed")
  387. return
  388. }
  389. }
  390. }
  391. }
  392. // udp service <- frpc <- frps <- frpc visitor <- user
  393. workConnSenderFn := func(conn net.Conn) {
  394. defer func() {
  395. conn.Close()
  396. wg.Done()
  397. }()
  398. var errRet error
  399. if firstPacket != nil {
  400. if errRet = msg.WriteMsg(conn, firstPacket); errRet != nil {
  401. xl.Warn("sender goroutine for udp work connection closed: %v", errRet)
  402. return
  403. }
  404. xl.Trace("send udp package to workConn: %s", firstPacket.Content)
  405. }
  406. for {
  407. select {
  408. case udpMsg, ok := <-sv.sendCh:
  409. if !ok {
  410. xl.Info("sender goroutine for udp work connection closed")
  411. return
  412. }
  413. if errRet = msg.WriteMsg(conn, udpMsg); errRet != nil {
  414. xl.Warn("sender goroutine for udp work connection closed: %v", errRet)
  415. return
  416. }
  417. xl.Trace("send udp package to workConn: %s", udpMsg.Content)
  418. case <-closeCh:
  419. return
  420. }
  421. }
  422. }
  423. go workConnReaderFn(workConn)
  424. go workConnSenderFn(workConn)
  425. wg.Wait()
  426. xl.Info("sudp worker is closed")
  427. }
  428. func (sv *SUDPVisitor) getNewVisitorConn() (net.Conn, error) {
  429. xl := xlog.FromContextSafe(sv.ctx)
  430. visitorConn, err := sv.ctl.connectServer()
  431. if err != nil {
  432. return nil, fmt.Errorf("frpc connect frps error: %v", err)
  433. }
  434. now := time.Now().Unix()
  435. newVisitorConnMsg := &msg.NewVisitorConn{
  436. ProxyName: sv.cfg.ServerName,
  437. SignKey: util.GetAuthKey(sv.cfg.Sk, now),
  438. Timestamp: now,
  439. UseEncryption: sv.cfg.UseEncryption,
  440. UseCompression: sv.cfg.UseCompression,
  441. }
  442. err = msg.WriteMsg(visitorConn, newVisitorConnMsg)
  443. if err != nil {
  444. return nil, fmt.Errorf("frpc send newVisitorConnMsg to frps error: %v", err)
  445. }
  446. var newVisitorConnRespMsg msg.NewVisitorConnResp
  447. _ = visitorConn.SetReadDeadline(time.Now().Add(10 * time.Second))
  448. err = msg.ReadMsgInto(visitorConn, &newVisitorConnRespMsg)
  449. if err != nil {
  450. return nil, fmt.Errorf("frpc read newVisitorConnRespMsg error: %v", err)
  451. }
  452. _ = visitorConn.SetReadDeadline(time.Time{})
  453. if newVisitorConnRespMsg.Error != "" {
  454. return nil, fmt.Errorf("start new visitor connection error: %s", newVisitorConnRespMsg.Error)
  455. }
  456. var remote io.ReadWriteCloser
  457. remote = visitorConn
  458. if sv.cfg.UseEncryption {
  459. remote, err = frpIo.WithEncryption(remote, []byte(sv.cfg.Sk))
  460. if err != nil {
  461. xl.Error("create encryption stream error: %v", err)
  462. return nil, err
  463. }
  464. }
  465. if sv.cfg.UseCompression {
  466. remote = frpIo.WithCompression(remote)
  467. }
  468. return frpNet.WrapReadWriteCloserToConn(remote, visitorConn), nil
  469. }
  470. func (sv *SUDPVisitor) Close() {
  471. sv.mu.Lock()
  472. defer sv.mu.Unlock()
  473. select {
  474. case <-sv.checkCloseCh:
  475. return
  476. default:
  477. close(sv.checkCloseCh)
  478. }
  479. if sv.udpConn != nil {
  480. sv.udpConn.Close()
  481. }
  482. close(sv.readCh)
  483. close(sv.sendCh)
  484. }