proxy.go 11 KB

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