vhost.go 5.9 KB

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