vhost.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. // Licensed under the Apache License, Version 2.0 (the "License");
  2. // you may not use this file except in compliance with the License.
  3. // You may obtain a copy of the License at
  4. //
  5. // http://www.apache.org/licenses/LICENSE-2.0
  6. //
  7. // Unless required by applicable law or agreed to in writing, software
  8. // distributed under the License is distributed on an "AS IS" BASIS,
  9. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. // See the License for the specific language governing permissions and
  11. // limitations under the License.
  12. package vhost
  13. import (
  14. "context"
  15. "fmt"
  16. "net"
  17. "strings"
  18. "time"
  19. "github.com/fatedier/golib/errors"
  20. "github.com/fatedier/frp/pkg/util/log"
  21. netpkg "github.com/fatedier/frp/pkg/util/net"
  22. "github.com/fatedier/frp/pkg/util/xlog"
  23. )
  24. type RouteInfo string
  25. const (
  26. RouteInfoKey RouteInfo = "routeInfo"
  27. RouteConfigKey RouteInfo = "routeConfig"
  28. )
  29. type RequestRouteInfo struct {
  30. URL string
  31. Host string
  32. HTTPUser string
  33. RemoteAddr string
  34. URLHost string
  35. Endpoint string
  36. }
  37. type (
  38. muxFunc func(net.Conn) (net.Conn, map[string]string, error)
  39. authFunc func(conn net.Conn, username, password string, reqInfoMap map[string]string) (bool, error)
  40. hostRewriteFunc func(net.Conn, string) (net.Conn, error)
  41. successHookFunc func(net.Conn, map[string]string) error
  42. failHookFunc func(net.Conn)
  43. )
  44. // Muxer is a functional component used for https and tcpmux proxies.
  45. // It accepts connections and extracts vhost information from the beginning of the connection data.
  46. // It then routes the connection to its appropriate listener.
  47. type Muxer struct {
  48. listener net.Listener
  49. timeout time.Duration
  50. vhostFunc muxFunc
  51. checkAuth authFunc
  52. successHook successHookFunc
  53. failHook failHookFunc
  54. rewriteHost hostRewriteFunc
  55. registryRouter *Routers
  56. }
  57. func NewMuxer(
  58. listener net.Listener,
  59. vhostFunc muxFunc,
  60. timeout time.Duration,
  61. ) (mux *Muxer, err error) {
  62. mux = &Muxer{
  63. listener: listener,
  64. timeout: timeout,
  65. vhostFunc: vhostFunc,
  66. registryRouter: NewRouters(),
  67. }
  68. go mux.run()
  69. return mux, nil
  70. }
  71. func (v *Muxer) SetCheckAuthFunc(f authFunc) *Muxer {
  72. v.checkAuth = f
  73. return v
  74. }
  75. func (v *Muxer) SetSuccessHookFunc(f successHookFunc) *Muxer {
  76. v.successHook = f
  77. return v
  78. }
  79. func (v *Muxer) SetFailHookFunc(f failHookFunc) *Muxer {
  80. v.failHook = f
  81. return v
  82. }
  83. func (v *Muxer) SetRewriteHostFunc(f hostRewriteFunc) *Muxer {
  84. v.rewriteHost = f
  85. return v
  86. }
  87. func (v *Muxer) Close() error {
  88. return v.listener.Close()
  89. }
  90. type ChooseEndpointFunc func() (string, error)
  91. type CreateConnFunc func(remoteAddr string) (net.Conn, error)
  92. type CreateConnByEndpointFunc func(endpoint, remoteAddr string) (net.Conn, error)
  93. // RouteConfig is the params used to match HTTP requests
  94. type RouteConfig struct {
  95. Domain string
  96. Location string
  97. RewriteHost string
  98. Username string
  99. Password string
  100. Headers map[string]string
  101. ResponseHeaders map[string]string
  102. RouteByHTTPUser string
  103. CreateConnFn CreateConnFunc
  104. ChooseEndpointFn ChooseEndpointFunc
  105. CreateConnByEndpointFn CreateConnByEndpointFunc
  106. }
  107. // listen for a new domain name, if rewriteHost is not empty and rewriteHost func is not nil,
  108. // then rewrite the host header to rewriteHost
  109. func (v *Muxer) Listen(ctx context.Context, cfg *RouteConfig) (l *Listener, err error) {
  110. l = &Listener{
  111. name: cfg.Domain,
  112. location: cfg.Location,
  113. routeByHTTPUser: cfg.RouteByHTTPUser,
  114. rewriteHost: cfg.RewriteHost,
  115. username: cfg.Username,
  116. password: cfg.Password,
  117. mux: v,
  118. accept: make(chan net.Conn),
  119. ctx: ctx,
  120. }
  121. err = v.registryRouter.Add(cfg.Domain, cfg.Location, cfg.RouteByHTTPUser, l)
  122. if err != nil {
  123. return
  124. }
  125. return l, nil
  126. }
  127. func (v *Muxer) getListener(name, path, httpUser string) (*Listener, bool) {
  128. findRouter := func(inName, inPath, inHTTPUser string) (*Listener, bool) {
  129. vr, ok := v.registryRouter.Get(inName, inPath, inHTTPUser)
  130. if ok {
  131. return vr.payload.(*Listener), true
  132. }
  133. // Try to check if there is one proxy that doesn't specify routerByHTTPUser, it means match all.
  134. vr, ok = v.registryRouter.Get(inName, inPath, "")
  135. if ok {
  136. return vr.payload.(*Listener), true
  137. }
  138. return nil, false
  139. }
  140. // first we check the full hostname
  141. // if not exist, then check the wildcard_domain such as *.example.com
  142. l, ok := findRouter(name, path, httpUser)
  143. if ok {
  144. return l, true
  145. }
  146. domainSplit := strings.Split(name, ".")
  147. for {
  148. if len(domainSplit) < 3 {
  149. break
  150. }
  151. domainSplit[0] = "*"
  152. name = strings.Join(domainSplit, ".")
  153. l, ok = findRouter(name, path, httpUser)
  154. if ok {
  155. return l, true
  156. }
  157. domainSplit = domainSplit[1:]
  158. }
  159. // Finally, try to check if there is one proxy that domain is "*" means match all domains.
  160. l, ok = findRouter("*", path, httpUser)
  161. if ok {
  162. return l, true
  163. }
  164. return nil, false
  165. }
  166. func (v *Muxer) run() {
  167. for {
  168. conn, err := v.listener.Accept()
  169. if err != nil {
  170. return
  171. }
  172. go v.handle(conn)
  173. }
  174. }
  175. func (v *Muxer) handle(c net.Conn) {
  176. if err := c.SetDeadline(time.Now().Add(v.timeout)); err != nil {
  177. _ = c.Close()
  178. return
  179. }
  180. sConn, reqInfoMap, err := v.vhostFunc(c)
  181. if err != nil {
  182. log.Debugf("get hostname from http/https request error: %v", err)
  183. _ = c.Close()
  184. return
  185. }
  186. name := strings.ToLower(reqInfoMap["Host"])
  187. path := strings.ToLower(reqInfoMap["Path"])
  188. httpUser := reqInfoMap["HTTPUser"]
  189. l, ok := v.getListener(name, path, httpUser)
  190. if !ok {
  191. log.Debugf("http request for host [%s] path [%s] httpUser [%s] not found", name, path, httpUser)
  192. v.failHook(sConn)
  193. return
  194. }
  195. xl := xlog.FromContextSafe(l.ctx)
  196. if v.successHook != nil {
  197. if err := v.successHook(c, reqInfoMap); err != nil {
  198. xl.Infof("success func failure on vhost connection: %v", err)
  199. _ = c.Close()
  200. return
  201. }
  202. }
  203. // if checkAuth func is exist and username/password is set
  204. // then verify user access
  205. if l.mux.checkAuth != nil && l.username != "" {
  206. ok, err := l.mux.checkAuth(c, l.username, l.password, reqInfoMap)
  207. if !ok || err != nil {
  208. xl.Debugf("auth failed for user: %s", l.username)
  209. _ = c.Close()
  210. return
  211. }
  212. }
  213. if err = sConn.SetDeadline(time.Time{}); err != nil {
  214. _ = c.Close()
  215. return
  216. }
  217. c = sConn
  218. xl.Debugf("new request host [%s] path [%s] httpUser [%s]", name, path, httpUser)
  219. err = errors.PanicToError(func() {
  220. l.accept <- c
  221. })
  222. if err != nil {
  223. xl.Warnf("listener is already closed, ignore this request")
  224. }
  225. }
  226. type Listener struct {
  227. name string
  228. location string
  229. routeByHTTPUser string
  230. rewriteHost string
  231. username string
  232. password string
  233. mux *Muxer // for closing Muxer
  234. accept chan net.Conn
  235. ctx context.Context
  236. }
  237. func (l *Listener) Accept() (net.Conn, error) {
  238. xl := xlog.FromContextSafe(l.ctx)
  239. conn, ok := <-l.accept
  240. if !ok {
  241. return nil, fmt.Errorf("Listener closed")
  242. }
  243. // if rewriteHost func is exist
  244. // rewrite http requests with a modified host header
  245. // if l.rewriteHost is empty, nothing to do
  246. if l.mux.rewriteHost != nil {
  247. sConn, err := l.mux.rewriteHost(conn, l.rewriteHost)
  248. if err != nil {
  249. xl.Warnf("host header rewrite failed: %v", err)
  250. return nil, fmt.Errorf("host header rewrite failed")
  251. }
  252. xl.Debugf("rewrite host to [%s] success", l.rewriteHost)
  253. conn = sConn
  254. }
  255. return netpkg.NewContextConn(l.ctx, conn), nil
  256. }
  257. func (l *Listener) Close() error {
  258. l.mux.registryRouter.Del(l.name, l.location, l.routeByHTTPUser)
  259. close(l.accept)
  260. return nil
  261. }
  262. func (l *Listener) Name() string {
  263. return l.name
  264. }
  265. func (l *Listener) Addr() net.Addr {
  266. return (*net.TCPAddr)(nil)
  267. }