1
0

vhost.go 7.0 KB

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