1
0

vhost.go 7.2 KB

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