proxy.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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. "fmt"
  18. "io"
  19. "net"
  20. "sync"
  21. "time"
  22. "github.com/fatedier/frp/models/config"
  23. "github.com/fatedier/frp/models/msg"
  24. "github.com/fatedier/frp/models/plugin"
  25. "github.com/fatedier/frp/models/proto/udp"
  26. "github.com/fatedier/frp/utils/errors"
  27. frpIo "github.com/fatedier/frp/utils/io"
  28. "github.com/fatedier/frp/utils/log"
  29. frpNet "github.com/fatedier/frp/utils/net"
  30. "github.com/fatedier/frp/utils/pool"
  31. )
  32. // Proxy defines how to deal with work connections for different proxy type.
  33. type Proxy interface {
  34. Run() error
  35. // InWorkConn accept work connections registered to server.
  36. InWorkConn(conn frpNet.Conn)
  37. Close()
  38. log.Logger
  39. }
  40. func NewProxy(pxyConf config.ProxyConf) (pxy Proxy) {
  41. baseProxy := BaseProxy{
  42. Logger: log.NewPrefixLogger(pxyConf.GetName()),
  43. }
  44. switch cfg := pxyConf.(type) {
  45. case *config.TcpProxyConf:
  46. pxy = &TcpProxy{
  47. BaseProxy: baseProxy,
  48. cfg: cfg,
  49. }
  50. case *config.UdpProxyConf:
  51. pxy = &UdpProxy{
  52. BaseProxy: baseProxy,
  53. cfg: cfg,
  54. }
  55. case *config.HttpProxyConf:
  56. pxy = &HttpProxy{
  57. BaseProxy: baseProxy,
  58. cfg: cfg,
  59. }
  60. case *config.HttpsProxyConf:
  61. pxy = &HttpsProxy{
  62. BaseProxy: baseProxy,
  63. cfg: cfg,
  64. }
  65. case *config.StcpProxyConf:
  66. pxy = &StcpProxy{
  67. BaseProxy: baseProxy,
  68. cfg: cfg,
  69. }
  70. case *config.XtcpProxyConf:
  71. pxy = &XtcpProxy{
  72. BaseProxy: baseProxy,
  73. cfg: cfg,
  74. }
  75. }
  76. return
  77. }
  78. type BaseProxy struct {
  79. closed bool
  80. mu sync.RWMutex
  81. log.Logger
  82. }
  83. // TCP
  84. type TcpProxy struct {
  85. BaseProxy
  86. cfg *config.TcpProxyConf
  87. proxyPlugin plugin.Plugin
  88. }
  89. func (pxy *TcpProxy) Run() (err error) {
  90. if pxy.cfg.Plugin != "" {
  91. pxy.proxyPlugin, err = plugin.Create(pxy.cfg.Plugin, pxy.cfg.PluginParams)
  92. if err != nil {
  93. return
  94. }
  95. }
  96. return
  97. }
  98. func (pxy *TcpProxy) Close() {
  99. if pxy.proxyPlugin != nil {
  100. pxy.proxyPlugin.Close()
  101. }
  102. }
  103. func (pxy *TcpProxy) InWorkConn(conn frpNet.Conn) {
  104. HandleTcpWorkConnection(&pxy.cfg.LocalSvrConf, pxy.proxyPlugin, &pxy.cfg.BaseProxyConf, conn,
  105. []byte(config.ClientCommonCfg.PrivilegeToken))
  106. }
  107. // HTTP
  108. type HttpProxy struct {
  109. BaseProxy
  110. cfg *config.HttpProxyConf
  111. proxyPlugin plugin.Plugin
  112. }
  113. func (pxy *HttpProxy) Run() (err error) {
  114. if pxy.cfg.Plugin != "" {
  115. pxy.proxyPlugin, err = plugin.Create(pxy.cfg.Plugin, pxy.cfg.PluginParams)
  116. if err != nil {
  117. return
  118. }
  119. }
  120. return
  121. }
  122. func (pxy *HttpProxy) Close() {
  123. if pxy.proxyPlugin != nil {
  124. pxy.proxyPlugin.Close()
  125. }
  126. }
  127. func (pxy *HttpProxy) InWorkConn(conn frpNet.Conn) {
  128. HandleTcpWorkConnection(&pxy.cfg.LocalSvrConf, pxy.proxyPlugin, &pxy.cfg.BaseProxyConf, conn,
  129. []byte(config.ClientCommonCfg.PrivilegeToken))
  130. }
  131. // HTTPS
  132. type HttpsProxy struct {
  133. BaseProxy
  134. cfg *config.HttpsProxyConf
  135. proxyPlugin plugin.Plugin
  136. }
  137. func (pxy *HttpsProxy) Run() (err error) {
  138. if pxy.cfg.Plugin != "" {
  139. pxy.proxyPlugin, err = plugin.Create(pxy.cfg.Plugin, pxy.cfg.PluginParams)
  140. if err != nil {
  141. return
  142. }
  143. }
  144. return
  145. }
  146. func (pxy *HttpsProxy) Close() {
  147. if pxy.proxyPlugin != nil {
  148. pxy.proxyPlugin.Close()
  149. }
  150. }
  151. func (pxy *HttpsProxy) InWorkConn(conn frpNet.Conn) {
  152. HandleTcpWorkConnection(&pxy.cfg.LocalSvrConf, pxy.proxyPlugin, &pxy.cfg.BaseProxyConf, conn,
  153. []byte(config.ClientCommonCfg.PrivilegeToken))
  154. }
  155. // STCP
  156. type StcpProxy struct {
  157. BaseProxy
  158. cfg *config.StcpProxyConf
  159. proxyPlugin plugin.Plugin
  160. }
  161. func (pxy *StcpProxy) Run() (err error) {
  162. if pxy.cfg.Plugin != "" {
  163. pxy.proxyPlugin, err = plugin.Create(pxy.cfg.Plugin, pxy.cfg.PluginParams)
  164. if err != nil {
  165. return
  166. }
  167. }
  168. return
  169. }
  170. func (pxy *StcpProxy) Close() {
  171. if pxy.proxyPlugin != nil {
  172. pxy.proxyPlugin.Close()
  173. }
  174. }
  175. func (pxy *StcpProxy) InWorkConn(conn frpNet.Conn) {
  176. HandleTcpWorkConnection(&pxy.cfg.LocalSvrConf, pxy.proxyPlugin, &pxy.cfg.BaseProxyConf, conn,
  177. []byte(config.ClientCommonCfg.PrivilegeToken))
  178. }
  179. // XTCP
  180. type XtcpProxy struct {
  181. BaseProxy
  182. cfg *config.XtcpProxyConf
  183. proxyPlugin plugin.Plugin
  184. }
  185. func (pxy *XtcpProxy) Run() (err error) {
  186. if pxy.cfg.Plugin != "" {
  187. pxy.proxyPlugin, err = plugin.Create(pxy.cfg.Plugin, pxy.cfg.PluginParams)
  188. if err != nil {
  189. return
  190. }
  191. }
  192. return
  193. }
  194. func (pxy *XtcpProxy) Close() {
  195. if pxy.proxyPlugin != nil {
  196. pxy.proxyPlugin.Close()
  197. }
  198. }
  199. func (pxy *XtcpProxy) InWorkConn(conn frpNet.Conn) {
  200. defer conn.Close()
  201. var natHoleSidMsg msg.NatHoleSid
  202. err := msg.ReadMsgInto(conn, &natHoleSidMsg)
  203. if err != nil {
  204. pxy.Error("xtcp read from workConn error: %v", err)
  205. return
  206. }
  207. natHoleClientMsg := &msg.NatHoleClient{
  208. ProxyName: pxy.cfg.ProxyName,
  209. Sid: natHoleSidMsg.Sid,
  210. }
  211. raddr, _ := net.ResolveUDPAddr("udp",
  212. fmt.Sprintf("%s:%d", config.ClientCommonCfg.ServerAddr, config.ClientCommonCfg.ServerUdpPort))
  213. clientConn, err := net.DialUDP("udp", nil, raddr)
  214. defer clientConn.Close()
  215. err = msg.WriteMsg(clientConn, natHoleClientMsg)
  216. if err != nil {
  217. pxy.Error("send natHoleClientMsg to server error: %v", err)
  218. return
  219. }
  220. // Wait for client address at most 5 seconds.
  221. var natHoleRespMsg msg.NatHoleResp
  222. clientConn.SetReadDeadline(time.Now().Add(5 * time.Second))
  223. buf := pool.GetBuf(1024)
  224. n, err := clientConn.Read(buf)
  225. if err != nil {
  226. pxy.Error("get natHoleRespMsg error: %v", err)
  227. return
  228. }
  229. err = msg.ReadMsgInto(bytes.NewReader(buf[:n]), &natHoleRespMsg)
  230. if err != nil {
  231. pxy.Error("get natHoleRespMsg error: %v", err)
  232. return
  233. }
  234. clientConn.SetReadDeadline(time.Time{})
  235. clientConn.Close()
  236. pxy.Trace("get natHoleRespMsg, sid [%s], client address [%s]", natHoleRespMsg.Sid, natHoleRespMsg.ClientAddr)
  237. // Send sid to visitor udp address.
  238. time.Sleep(time.Second)
  239. laddr, _ := net.ResolveUDPAddr("udp", clientConn.LocalAddr().String())
  240. daddr, err := net.ResolveUDPAddr("udp", natHoleRespMsg.VisitorAddr)
  241. if err != nil {
  242. pxy.Error("resolve visitor udp address error: %v", err)
  243. return
  244. }
  245. lConn, err := net.DialUDP("udp", laddr, daddr)
  246. if err != nil {
  247. pxy.Error("dial visitor udp address error: %v", err)
  248. return
  249. }
  250. lConn.Write([]byte(natHoleRespMsg.Sid))
  251. kcpConn, err := frpNet.NewKcpConnFromUdp(lConn, true, natHoleRespMsg.VisitorAddr)
  252. if err != nil {
  253. pxy.Error("create kcp connection from udp connection error: %v", err)
  254. return
  255. }
  256. HandleTcpWorkConnection(&pxy.cfg.LocalSvrConf, pxy.proxyPlugin, &pxy.cfg.BaseProxyConf,
  257. frpNet.WrapConn(kcpConn), []byte(pxy.cfg.Sk))
  258. }
  259. // UDP
  260. type UdpProxy struct {
  261. BaseProxy
  262. cfg *config.UdpProxyConf
  263. localAddr *net.UDPAddr
  264. readCh chan *msg.UdpPacket
  265. // include msg.UdpPacket and msg.Ping
  266. sendCh chan msg.Message
  267. workConn frpNet.Conn
  268. }
  269. func (pxy *UdpProxy) Run() (err error) {
  270. pxy.localAddr, err = net.ResolveUDPAddr("udp", fmt.Sprintf("%s:%d", pxy.cfg.LocalIp, pxy.cfg.LocalPort))
  271. if err != nil {
  272. return
  273. }
  274. return
  275. }
  276. func (pxy *UdpProxy) Close() {
  277. pxy.mu.Lock()
  278. defer pxy.mu.Unlock()
  279. if !pxy.closed {
  280. pxy.closed = true
  281. if pxy.workConn != nil {
  282. pxy.workConn.Close()
  283. }
  284. if pxy.readCh != nil {
  285. close(pxy.readCh)
  286. }
  287. if pxy.sendCh != nil {
  288. close(pxy.sendCh)
  289. }
  290. }
  291. }
  292. func (pxy *UdpProxy) InWorkConn(conn frpNet.Conn) {
  293. pxy.Info("incoming a new work connection for udp proxy, %s", conn.RemoteAddr().String())
  294. // close resources releated with old workConn
  295. pxy.Close()
  296. pxy.mu.Lock()
  297. pxy.workConn = conn
  298. pxy.readCh = make(chan *msg.UdpPacket, 1024)
  299. pxy.sendCh = make(chan msg.Message, 1024)
  300. pxy.closed = false
  301. pxy.mu.Unlock()
  302. workConnReaderFn := func(conn net.Conn, readCh chan *msg.UdpPacket) {
  303. for {
  304. var udpMsg msg.UdpPacket
  305. if errRet := msg.ReadMsgInto(conn, &udpMsg); errRet != nil {
  306. pxy.Warn("read from workConn for udp error: %v", errRet)
  307. return
  308. }
  309. if errRet := errors.PanicToError(func() {
  310. pxy.Trace("get udp package from workConn: %s", udpMsg.Content)
  311. readCh <- &udpMsg
  312. }); errRet != nil {
  313. pxy.Info("reader goroutine for udp work connection closed: %v", errRet)
  314. return
  315. }
  316. }
  317. }
  318. workConnSenderFn := func(conn net.Conn, sendCh chan msg.Message) {
  319. defer func() {
  320. pxy.Info("writer goroutine for udp work connection closed")
  321. }()
  322. var errRet error
  323. for rawMsg := range sendCh {
  324. switch m := rawMsg.(type) {
  325. case *msg.UdpPacket:
  326. pxy.Trace("send udp package to workConn: %s", m.Content)
  327. case *msg.Ping:
  328. pxy.Trace("send ping message to udp workConn")
  329. }
  330. if errRet = msg.WriteMsg(conn, rawMsg); errRet != nil {
  331. pxy.Error("udp work write error: %v", errRet)
  332. return
  333. }
  334. }
  335. }
  336. heartbeatFn := func(conn net.Conn, sendCh chan msg.Message) {
  337. var errRet error
  338. for {
  339. time.Sleep(time.Duration(30) * time.Second)
  340. if errRet = errors.PanicToError(func() {
  341. sendCh <- &msg.Ping{}
  342. }); errRet != nil {
  343. pxy.Trace("heartbeat goroutine for udp work connection closed")
  344. break
  345. }
  346. }
  347. }
  348. go workConnSenderFn(pxy.workConn, pxy.sendCh)
  349. go workConnReaderFn(pxy.workConn, pxy.readCh)
  350. go heartbeatFn(pxy.workConn, pxy.sendCh)
  351. udp.Forwarder(pxy.localAddr, pxy.readCh, pxy.sendCh)
  352. }
  353. // Common handler for tcp work connections.
  354. func HandleTcpWorkConnection(localInfo *config.LocalSvrConf, proxyPlugin plugin.Plugin,
  355. baseInfo *config.BaseProxyConf, workConn frpNet.Conn, encKey []byte) {
  356. var (
  357. remote io.ReadWriteCloser
  358. err error
  359. )
  360. remote = workConn
  361. if baseInfo.UseEncryption {
  362. remote, err = frpIo.WithEncryption(remote, encKey)
  363. if err != nil {
  364. workConn.Close()
  365. workConn.Error("create encryption stream error: %v", err)
  366. return
  367. }
  368. }
  369. if baseInfo.UseCompression {
  370. remote = frpIo.WithCompression(remote)
  371. }
  372. if proxyPlugin != nil {
  373. // if plugin is set, let plugin handle connections first
  374. workConn.Debug("handle by plugin: %s", proxyPlugin.Name())
  375. proxyPlugin.Handle(remote, workConn)
  376. workConn.Debug("handle by plugin finished")
  377. return
  378. } else {
  379. localConn, err := frpNet.ConnectServer("tcp", fmt.Sprintf("%s:%d", localInfo.LocalIp, localInfo.LocalPort))
  380. if err != nil {
  381. workConn.Close()
  382. workConn.Error("connect to local service [%s:%d] error: %v", localInfo.LocalIp, localInfo.LocalPort, err)
  383. return
  384. }
  385. workConn.Debug("join connections, localConn(l[%s] r[%s]) workConn(l[%s] r[%s])", localConn.LocalAddr().String(),
  386. localConn.RemoteAddr().String(), workConn.LocalAddr().String(), workConn.RemoteAddr().String())
  387. frpIo.Join(localConn, remote)
  388. workConn.Debug("join connections closed")
  389. }
  390. }