proxy.go 10 KB

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