1
0

vhost.go 6.8 KB

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