1
0

vhost.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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. utilnet "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. )
  28. type RequestRouteInfo struct {
  29. URL string
  30. Host string
  31. HTTPUser string
  32. RemoteAddr string
  33. URLHost string
  34. Endpoint string
  35. }
  36. type (
  37. muxFunc func(net.Conn) (net.Conn, map[string]string, error)
  38. authFunc func(conn net.Conn, username, password string, reqInfoMap map[string]string) (bool, error)
  39. hostRewriteFunc func(net.Conn, string) (net.Conn, error)
  40. successHookFunc func(net.Conn, map[string]string) error
  41. )
  42. // Muxer is a functional component used for https and tcpmux proxies.
  43. // It accepts connections and extracts vhost information from the beginning of the connection data.
  44. // It then routes the connection to its appropriate listener.
  45. type Muxer struct {
  46. listener net.Listener
  47. timeout time.Duration
  48. vhostFunc muxFunc
  49. checkAuth authFunc
  50. successHook successHookFunc
  51. rewriteHost hostRewriteFunc
  52. registryRouter *Routers
  53. }
  54. func NewMuxer(
  55. listener net.Listener,
  56. vhostFunc muxFunc,
  57. timeout time.Duration,
  58. ) (mux *Muxer, err error) {
  59. mux = &Muxer{
  60. listener: listener,
  61. timeout: timeout,
  62. vhostFunc: vhostFunc,
  63. registryRouter: NewRouters(),
  64. }
  65. go mux.run()
  66. return mux, nil
  67. }
  68. func (v *Muxer) SetCheckAuthFunc(f authFunc) *Muxer {
  69. v.checkAuth = f
  70. return v
  71. }
  72. func (v *Muxer) SetSuccessHookFunc(f successHookFunc) *Muxer {
  73. v.successHook = f
  74. return v
  75. }
  76. func (v *Muxer) SetRewriteHostFunc(f hostRewriteFunc) *Muxer {
  77. v.rewriteHost = f
  78. return v
  79. }
  80. type ChooseEndpointFunc func() (string, error)
  81. type CreateConnFunc func(remoteAddr string) (net.Conn, error)
  82. type CreateConnByEndpointFunc func(endpoint, remoteAddr string) (net.Conn, error)
  83. // RouteConfig is the params used to match HTTP requests
  84. type RouteConfig struct {
  85. Domain string
  86. Location string
  87. RewriteHost string
  88. Username string
  89. Password string
  90. Headers map[string]string
  91. RouteByHTTPUser string
  92. CreateConnFn CreateConnFunc
  93. ChooseEndpointFn ChooseEndpointFunc
  94. CreateConnByEndpointFn CreateConnByEndpointFunc
  95. }
  96. // listen for a new domain name, if rewriteHost is not empty and rewriteHost func is not nil,
  97. // then rewrite the host header to rewriteHost
  98. func (v *Muxer) Listen(ctx context.Context, cfg *RouteConfig) (l *Listener, err error) {
  99. l = &Listener{
  100. name: cfg.Domain,
  101. location: cfg.Location,
  102. routeByHTTPUser: cfg.RouteByHTTPUser,
  103. rewriteHost: cfg.RewriteHost,
  104. username: cfg.Username,
  105. password: cfg.Password,
  106. mux: v,
  107. accept: make(chan net.Conn),
  108. ctx: ctx,
  109. }
  110. err = v.registryRouter.Add(cfg.Domain, cfg.Location, cfg.RouteByHTTPUser, l)
  111. if err != nil {
  112. return
  113. }
  114. return l, nil
  115. }
  116. func (v *Muxer) getListener(name, path, httpUser string) (*Listener, bool) {
  117. findRouter := func(inName, inPath, inHTTPUser string) (*Listener, bool) {
  118. vr, ok := v.registryRouter.Get(inName, inPath, inHTTPUser)
  119. if ok {
  120. return vr.payload.(*Listener), true
  121. }
  122. // Try to check if there is one proxy that doesn't specify routerByHTTPUser, it means match all.
  123. vr, ok = v.registryRouter.Get(inName, inPath, "")
  124. if ok {
  125. return vr.payload.(*Listener), true
  126. }
  127. return nil, false
  128. }
  129. // first we check the full hostname
  130. // if not exist, then check the wildcard_domain such as *.example.com
  131. l, ok := findRouter(name, path, httpUser)
  132. if ok {
  133. return l, true
  134. }
  135. domainSplit := strings.Split(name, ".")
  136. for {
  137. if len(domainSplit) < 3 {
  138. break
  139. }
  140. domainSplit[0] = "*"
  141. name = strings.Join(domainSplit, ".")
  142. l, ok = findRouter(name, path, httpUser)
  143. if ok {
  144. return l, true
  145. }
  146. domainSplit = domainSplit[1:]
  147. }
  148. // Finally, try to check if there is one proxy that domain is "*" means match all domains.
  149. l, ok = findRouter("*", path, httpUser)
  150. if ok {
  151. return l, true
  152. }
  153. return nil, false
  154. }
  155. func (v *Muxer) run() {
  156. for {
  157. conn, err := v.listener.Accept()
  158. if err != nil {
  159. return
  160. }
  161. go v.handle(conn)
  162. }
  163. }
  164. func (v *Muxer) handle(c net.Conn) {
  165. if err := c.SetDeadline(time.Now().Add(v.timeout)); err != nil {
  166. _ = c.Close()
  167. return
  168. }
  169. sConn, reqInfoMap, err := v.vhostFunc(c)
  170. if err != nil {
  171. log.Debug("get hostname from http/https request error: %v", err)
  172. _ = c.Close()
  173. return
  174. }
  175. name := strings.ToLower(reqInfoMap["Host"])
  176. path := strings.ToLower(reqInfoMap["Path"])
  177. httpUser := reqInfoMap["HTTPUser"]
  178. l, ok := v.getListener(name, path, httpUser)
  179. if !ok {
  180. res := notFoundResponse()
  181. if res.Body != nil {
  182. defer res.Body.Close()
  183. }
  184. _ = res.Write(c)
  185. log.Debug("http request for host [%s] path [%s] httpUser [%s] not found", name, path, httpUser)
  186. _ = c.Close()
  187. return
  188. }
  189. xl := xlog.FromContextSafe(l.ctx)
  190. if v.successHook != nil {
  191. if err := v.successHook(c, reqInfoMap); err != nil {
  192. xl.Info("success func failure on vhost connection: %v", err)
  193. _ = c.Close()
  194. return
  195. }
  196. }
  197. // if checkAuth func is exist and username/password is set
  198. // then verify user access
  199. if l.mux.checkAuth != nil && l.username != "" {
  200. ok, err := l.mux.checkAuth(c, l.username, l.password, reqInfoMap)
  201. if !ok || err != nil {
  202. xl.Debug("auth failed for user: %s", l.username)
  203. _ = c.Close()
  204. return
  205. }
  206. }
  207. if err = sConn.SetDeadline(time.Time{}); err != nil {
  208. _ = c.Close()
  209. return
  210. }
  211. c = sConn
  212. xl.Debug("new request host [%s] path [%s] httpUser [%s]", name, path, httpUser)
  213. err = errors.PanicToError(func() {
  214. l.accept <- c
  215. })
  216. if err != nil {
  217. xl.Warn("listener is already closed, ignore this request")
  218. }
  219. }
  220. type Listener struct {
  221. name string
  222. location string
  223. routeByHTTPUser string
  224. rewriteHost string
  225. username string
  226. password string
  227. mux *Muxer // for closing Muxer
  228. accept chan net.Conn
  229. ctx context.Context
  230. }
  231. func (l *Listener) Accept() (net.Conn, error) {
  232. xl := xlog.FromContextSafe(l.ctx)
  233. conn, ok := <-l.accept
  234. if !ok {
  235. return nil, fmt.Errorf("Listener closed")
  236. }
  237. // if rewriteHost func is exist
  238. // rewrite http requests with a modified host header
  239. // if l.rewriteHost is empty, nothing to do
  240. if l.mux.rewriteHost != nil {
  241. sConn, err := l.mux.rewriteHost(conn, l.rewriteHost)
  242. if err != nil {
  243. xl.Warn("host header rewrite failed: %v", err)
  244. return nil, fmt.Errorf("host header rewrite failed")
  245. }
  246. xl.Debug("rewrite host to [%s] success", l.rewriteHost)
  247. conn = sConn
  248. }
  249. return utilnet.NewContextConn(l.ctx, conn), nil
  250. }
  251. func (l *Listener) Close() error {
  252. l.mux.registryRouter.Del(l.name, l.location, l.routeByHTTPUser)
  253. close(l.accept)
  254. return nil
  255. }
  256. func (l *Listener) Name() string {
  257. return l.name
  258. }
  259. func (l *Listener) Addr() net.Addr {
  260. return (*net.TCPAddr)(nil)
  261. }