1
0

proxy.go 11 KB

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