vistor.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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. "fmt"
  17. "io"
  18. "net"
  19. "strings"
  20. "sync"
  21. "time"
  22. "golang.org/x/net/ipv4"
  23. "github.com/fatedier/frp/models/config"
  24. "github.com/fatedier/frp/models/msg"
  25. frpIo "github.com/fatedier/frp/utils/io"
  26. "github.com/fatedier/frp/utils/log"
  27. frpNet "github.com/fatedier/frp/utils/net"
  28. "github.com/fatedier/frp/utils/pool"
  29. "github.com/fatedier/frp/utils/util"
  30. )
  31. // Vistor is used for forward traffics from local port tot remote service.
  32. type Vistor interface {
  33. Run() error
  34. Close()
  35. log.Logger
  36. }
  37. func NewVistor(ctl *Control, pxyConf config.ProxyConf) (vistor Vistor) {
  38. baseVistor := BaseVistor{
  39. ctl: ctl,
  40. Logger: log.NewPrefixLogger(pxyConf.GetName()),
  41. }
  42. switch cfg := pxyConf.(type) {
  43. case *config.StcpProxyConf:
  44. vistor = &StcpVistor{
  45. BaseVistor: baseVistor,
  46. cfg: cfg,
  47. }
  48. case *config.XtcpProxyConf:
  49. vistor = &XtcpVistor{
  50. BaseVistor: baseVistor,
  51. cfg: cfg,
  52. }
  53. }
  54. return
  55. }
  56. type BaseVistor struct {
  57. ctl *Control
  58. l frpNet.Listener
  59. closed bool
  60. mu sync.RWMutex
  61. log.Logger
  62. }
  63. type StcpVistor struct {
  64. BaseVistor
  65. cfg *config.StcpProxyConf
  66. }
  67. func (sv *StcpVistor) Run() (err error) {
  68. sv.l, err = frpNet.ListenTcp(sv.cfg.BindAddr, int64(sv.cfg.BindPort))
  69. if err != nil {
  70. return
  71. }
  72. go sv.worker()
  73. return
  74. }
  75. func (sv *StcpVistor) Close() {
  76. sv.l.Close()
  77. }
  78. func (sv *StcpVistor) worker() {
  79. for {
  80. conn, err := sv.l.Accept()
  81. if err != nil {
  82. sv.Warn("stcp local listener closed")
  83. return
  84. }
  85. go sv.handleConn(conn)
  86. }
  87. }
  88. func (sv *StcpVistor) handleConn(userConn frpNet.Conn) {
  89. defer userConn.Close()
  90. sv.Debug("get a new stcp user connection")
  91. vistorConn, err := sv.ctl.connectServer()
  92. if err != nil {
  93. return
  94. }
  95. defer vistorConn.Close()
  96. now := time.Now().Unix()
  97. newVistorConnMsg := &msg.NewVistorConn{
  98. ProxyName: sv.cfg.ServerName,
  99. SignKey: util.GetAuthKey(sv.cfg.Sk, now),
  100. Timestamp: now,
  101. UseEncryption: sv.cfg.UseEncryption,
  102. UseCompression: sv.cfg.UseCompression,
  103. }
  104. err = msg.WriteMsg(vistorConn, newVistorConnMsg)
  105. if err != nil {
  106. sv.Warn("send newVistorConnMsg to server error: %v", err)
  107. return
  108. }
  109. var newVistorConnRespMsg msg.NewVistorConnResp
  110. vistorConn.SetReadDeadline(time.Now().Add(10 * time.Second))
  111. err = msg.ReadMsgInto(vistorConn, &newVistorConnRespMsg)
  112. if err != nil {
  113. sv.Warn("get newVistorConnRespMsg error: %v", err)
  114. return
  115. }
  116. vistorConn.SetReadDeadline(time.Time{})
  117. if newVistorConnRespMsg.Error != "" {
  118. sv.Warn("start new vistor connection error: %s", newVistorConnRespMsg.Error)
  119. return
  120. }
  121. var remote io.ReadWriteCloser
  122. remote = vistorConn
  123. if sv.cfg.UseEncryption {
  124. remote, err = frpIo.WithEncryption(remote, []byte(sv.cfg.Sk))
  125. if err != nil {
  126. sv.Error("create encryption stream error: %v", err)
  127. return
  128. }
  129. }
  130. if sv.cfg.UseCompression {
  131. remote = frpIo.WithCompression(remote)
  132. }
  133. frpIo.Join(userConn, remote)
  134. }
  135. type XtcpVistor struct {
  136. BaseVistor
  137. cfg *config.XtcpProxyConf
  138. }
  139. func (sv *XtcpVistor) Run() (err error) {
  140. sv.l, err = frpNet.ListenTcp(sv.cfg.BindAddr, int64(sv.cfg.BindPort))
  141. if err != nil {
  142. return
  143. }
  144. go sv.worker()
  145. return
  146. }
  147. func (sv *XtcpVistor) Close() {
  148. sv.l.Close()
  149. }
  150. func (sv *XtcpVistor) worker() {
  151. for {
  152. conn, err := sv.l.Accept()
  153. if err != nil {
  154. sv.Warn("stcp local listener closed")
  155. return
  156. }
  157. go sv.handleConn(conn)
  158. }
  159. }
  160. func (sv *XtcpVistor) handleConn(userConn frpNet.Conn) {
  161. defer userConn.Close()
  162. sv.Debug("get a new xtcp user connection")
  163. if config.ClientCommonCfg.ServerUdpPort == 0 {
  164. sv.Error("xtcp is not supported by server")
  165. return
  166. }
  167. raddr, err := net.ResolveUDPAddr("udp",
  168. fmt.Sprintf("%s:%d", config.ClientCommonCfg.ServerAddr, config.ClientCommonCfg.ServerUdpPort))
  169. vistorConn, err := net.DialUDP("udp", nil, raddr)
  170. defer vistorConn.Close()
  171. now := time.Now().Unix()
  172. natHoleVistorMsg := &msg.NatHoleVistor{
  173. ProxyName: sv.cfg.ServerName,
  174. SignKey: util.GetAuthKey(sv.cfg.Sk, now),
  175. Timestamp: now,
  176. }
  177. err = msg.WriteMsg(vistorConn, natHoleVistorMsg)
  178. if err != nil {
  179. sv.Warn("send natHoleVistorMsg to server error: %v", err)
  180. return
  181. }
  182. // Wait for client address at most 10 seconds.
  183. var natHoleResp msg.NatHoleResp
  184. vistorConn.SetReadDeadline(time.Now().Add(10 * time.Second))
  185. err = msg.ReadMsgInto(vistorConn, &natHoleResp)
  186. if err != nil {
  187. sv.Warn("get natHoleRespMsg error: %v", err)
  188. return
  189. }
  190. vistorConn.SetReadDeadline(time.Time{})
  191. // Close vistorConn, so we can use it's local address.
  192. vistorConn.Close()
  193. // Send detect message for all ports of client in case different NAT type.
  194. array := strings.Split(natHoleResp.ClientAddr, ":")
  195. if len(array) <= 0 {
  196. sv.Error("get natHoleResp client address error: %s", natHoleResp.ClientAddr)
  197. return
  198. }
  199. laddr, _ := net.ResolveUDPAddr("udp", vistorConn.LocalAddr().String())
  200. for i := 1000; i < 65000; i++ {
  201. sv.sendDetectMsg(array[0], int64(i), laddr)
  202. }
  203. // Listen for vistorConn's address and wait for client connection.
  204. lConn, _ := net.ListenUDP("udp", laddr)
  205. lConn.SetReadDeadline(time.Now().Add(10 * time.Second))
  206. sidBuf := pool.GetBuf(1024)
  207. n, _, err := lConn.ReadFromUDP(sidBuf)
  208. if err != nil {
  209. sv.Warn("get sid from client error: %v", err)
  210. return
  211. }
  212. lConn.SetReadDeadline(time.Time{})
  213. if string(sidBuf[:n]) != natHoleResp.Sid {
  214. sv.Warn("incorrect sid from client")
  215. return
  216. }
  217. pool.PutBuf(sidBuf)
  218. var remote io.ReadWriteCloser
  219. remote, err = frpNet.NewKcpConnFromUdp(lConn, false, natHoleResp.ClientAddr)
  220. if err != nil {
  221. sv.Error("create kcp connection from udp connection error: %v", err)
  222. return
  223. }
  224. if sv.cfg.UseEncryption {
  225. remote, err = frpIo.WithEncryption(remote, []byte(sv.cfg.Sk))
  226. if err != nil {
  227. sv.Error("create encryption stream error: %v", err)
  228. return
  229. }
  230. }
  231. if sv.cfg.UseCompression {
  232. remote = frpIo.WithCompression(remote)
  233. }
  234. frpIo.Join(userConn, remote)
  235. }
  236. func (sv *XtcpVistor) sendDetectMsg(addr string, port int64, laddr *net.UDPAddr) (err error) {
  237. daddr, err := net.ResolveUDPAddr("udp", fmt.Sprintf("%s:%d", addr, port))
  238. if err != nil {
  239. return err
  240. }
  241. tConn, err := net.DialUDP("udp", laddr, daddr)
  242. if err != nil {
  243. return err
  244. }
  245. uConn := ipv4.NewConn(tConn)
  246. uConn.SetTTL(3)
  247. tConn.Write([]byte(fmt.Sprintf("%d", port)))
  248. tConn.Close()
  249. return nil
  250. }