1
0

vhost.go 7.4 KB

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