vhost.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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. type ChooseEndpointFunc func() (string, error)
  88. type CreateConnFunc func(remoteAddr string) (net.Conn, error)
  89. type CreateConnByEndpointFunc func(endpoint, remoteAddr string) (net.Conn, error)
  90. // RouteConfig is the params used to match HTTP requests
  91. type RouteConfig struct {
  92. Domain string
  93. Location string
  94. RewriteHost string
  95. Username string
  96. Password string
  97. Headers map[string]string
  98. ResponseHeaders map[string]string
  99. RouteByHTTPUser string
  100. CreateConnFn CreateConnFunc
  101. ChooseEndpointFn ChooseEndpointFunc
  102. CreateConnByEndpointFn CreateConnByEndpointFunc
  103. }
  104. // listen for a new domain name, if rewriteHost is not empty and rewriteHost func is not nil,
  105. // then rewrite the host header to rewriteHost
  106. func (v *Muxer) Listen(ctx context.Context, cfg *RouteConfig) (l *Listener, err error) {
  107. l = &Listener{
  108. name: cfg.Domain,
  109. location: cfg.Location,
  110. routeByHTTPUser: cfg.RouteByHTTPUser,
  111. rewriteHost: cfg.RewriteHost,
  112. username: cfg.Username,
  113. password: cfg.Password,
  114. mux: v,
  115. accept: make(chan net.Conn),
  116. ctx: ctx,
  117. }
  118. err = v.registryRouter.Add(cfg.Domain, cfg.Location, cfg.RouteByHTTPUser, l)
  119. if err != nil {
  120. return
  121. }
  122. return l, nil
  123. }
  124. func (v *Muxer) getListener(name, path, httpUser string) (*Listener, bool) {
  125. findRouter := func(inName, inPath, inHTTPUser string) (*Listener, bool) {
  126. vr, ok := v.registryRouter.Get(inName, inPath, inHTTPUser)
  127. if ok {
  128. return vr.payload.(*Listener), true
  129. }
  130. // Try to check if there is one proxy that doesn't specify routerByHTTPUser, it means match all.
  131. vr, ok = v.registryRouter.Get(inName, inPath, "")
  132. if ok {
  133. return vr.payload.(*Listener), true
  134. }
  135. return nil, false
  136. }
  137. // first we check the full hostname
  138. // if not exist, then check the wildcard_domain such as *.example.com
  139. l, ok := findRouter(name, path, httpUser)
  140. if ok {
  141. return l, true
  142. }
  143. domainSplit := strings.Split(name, ".")
  144. for {
  145. if len(domainSplit) < 3 {
  146. break
  147. }
  148. domainSplit[0] = "*"
  149. name = strings.Join(domainSplit, ".")
  150. l, ok = findRouter(name, path, httpUser)
  151. if ok {
  152. return l, true
  153. }
  154. domainSplit = domainSplit[1:]
  155. }
  156. // Finally, try to check if there is one proxy that domain is "*" means match all domains.
  157. l, ok = findRouter("*", path, httpUser)
  158. if ok {
  159. return l, true
  160. }
  161. return nil, false
  162. }
  163. func (v *Muxer) run() {
  164. for {
  165. conn, err := v.listener.Accept()
  166. if err != nil {
  167. return
  168. }
  169. go v.handle(conn)
  170. }
  171. }
  172. func (v *Muxer) handle(c net.Conn) {
  173. if err := c.SetDeadline(time.Now().Add(v.timeout)); err != nil {
  174. _ = c.Close()
  175. return
  176. }
  177. sConn, reqInfoMap, err := v.vhostFunc(c)
  178. if err != nil {
  179. log.Debugf("get hostname from http/https request error: %v", err)
  180. _ = c.Close()
  181. return
  182. }
  183. name := strings.ToLower(reqInfoMap["Host"])
  184. path := strings.ToLower(reqInfoMap["Path"])
  185. httpUser := reqInfoMap["HTTPUser"]
  186. l, ok := v.getListener(name, path, httpUser)
  187. if !ok {
  188. log.Debugf("http request for host [%s] path [%s] httpUser [%s] not found", name, path, httpUser)
  189. v.failHook(sConn)
  190. return
  191. }
  192. xl := xlog.FromContextSafe(l.ctx)
  193. if v.successHook != nil {
  194. if err := v.successHook(c, reqInfoMap); err != nil {
  195. xl.Infof("success func failure on vhost connection: %v", err)
  196. _ = c.Close()
  197. return
  198. }
  199. }
  200. // if checkAuth func is exist and username/password is set
  201. // then verify user access
  202. if l.mux.checkAuth != nil && l.username != "" {
  203. ok, err := l.mux.checkAuth(c, l.username, l.password, reqInfoMap)
  204. if !ok || err != nil {
  205. xl.Debugf("auth failed for user: %s", l.username)
  206. _ = c.Close()
  207. return
  208. }
  209. }
  210. if err = sConn.SetDeadline(time.Time{}); err != nil {
  211. _ = c.Close()
  212. return
  213. }
  214. c = sConn
  215. xl.Debugf("new request host [%s] path [%s] httpUser [%s]", name, path, httpUser)
  216. err = errors.PanicToError(func() {
  217. l.accept <- c
  218. })
  219. if err != nil {
  220. xl.Warnf("listener is already closed, ignore this request")
  221. }
  222. }
  223. type Listener struct {
  224. name string
  225. location string
  226. routeByHTTPUser string
  227. rewriteHost string
  228. username string
  229. password string
  230. mux *Muxer // for closing Muxer
  231. accept chan net.Conn
  232. ctx context.Context
  233. }
  234. func (l *Listener) Accept() (net.Conn, error) {
  235. xl := xlog.FromContextSafe(l.ctx)
  236. conn, ok := <-l.accept
  237. if !ok {
  238. return nil, fmt.Errorf("Listener closed")
  239. }
  240. // if rewriteHost func is exist
  241. // rewrite http requests with a modified host header
  242. // if l.rewriteHost is empty, nothing to do
  243. if l.mux.rewriteHost != nil {
  244. sConn, err := l.mux.rewriteHost(conn, l.rewriteHost)
  245. if err != nil {
  246. xl.Warnf("host header rewrite failed: %v", err)
  247. return nil, fmt.Errorf("host header rewrite failed")
  248. }
  249. xl.Debugf("rewrite host to [%s] success", l.rewriteHost)
  250. conn = sConn
  251. }
  252. return netpkg.NewContextConn(l.ctx, conn), nil
  253. }
  254. func (l *Listener) Close() error {
  255. l.mux.registryRouter.Del(l.name, l.location, l.routeByHTTPUser)
  256. close(l.accept)
  257. return nil
  258. }
  259. func (l *Listener) Name() string {
  260. return l.name
  261. }
  262. func (l *Listener) Addr() net.Addr {
  263. return (*net.TCPAddr)(nil)
  264. }