vhost.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  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. "fmt"
  15. "strings"
  16. "sync"
  17. "time"
  18. "github.com/fatedier/frp/utils/errors"
  19. "github.com/fatedier/frp/utils/log"
  20. frpNet "github.com/fatedier/frp/utils/net"
  21. )
  22. type muxFunc func(frpNet.Conn) (frpNet.Conn, map[string]string, error)
  23. type httpAuthFunc func(frpNet.Conn, string, string, string) (bool, error)
  24. type hostRewriteFunc func(frpNet.Conn, string) (frpNet.Conn, error)
  25. type VhostMuxer struct {
  26. listener frpNet.Listener
  27. timeout time.Duration
  28. vhostFunc muxFunc
  29. authFunc httpAuthFunc
  30. rewriteFunc hostRewriteFunc
  31. registryRouter *VhostRouters
  32. mutex sync.RWMutex
  33. }
  34. func NewVhostMuxer(listener frpNet.Listener, vhostFunc muxFunc, authFunc httpAuthFunc, rewriteFunc hostRewriteFunc, timeout time.Duration) (mux *VhostMuxer, err error) {
  35. mux = &VhostMuxer{
  36. listener: listener,
  37. timeout: timeout,
  38. vhostFunc: vhostFunc,
  39. authFunc: authFunc,
  40. rewriteFunc: rewriteFunc,
  41. registryRouter: NewVhostRouters(),
  42. }
  43. go mux.run()
  44. return mux, nil
  45. }
  46. type VhostRouteConfig struct {
  47. Domain string
  48. Location string
  49. RewriteHost string
  50. Username string
  51. Password string
  52. }
  53. // listen for a new domain name, if rewriteHost is not empty and rewriteFunc is not nil
  54. // then rewrite the host header to rewriteHost
  55. func (v *VhostMuxer) Listen(cfg *VhostRouteConfig) (l *Listener, err error) {
  56. v.mutex.Lock()
  57. defer v.mutex.Unlock()
  58. _, ok := v.registryRouter.Exist(cfg.Domain, cfg.Location)
  59. if ok {
  60. return nil, fmt.Errorf("hostname [%s] location [%s] is already registered", cfg.Domain, cfg.Location)
  61. }
  62. l = &Listener{
  63. name: cfg.Domain,
  64. location: cfg.Location,
  65. rewriteHost: cfg.RewriteHost,
  66. userName: cfg.Username,
  67. passWord: cfg.Password,
  68. mux: v,
  69. accept: make(chan frpNet.Conn),
  70. Logger: log.NewPrefixLogger(""),
  71. }
  72. v.registryRouter.Add(cfg.Domain, cfg.Location, l)
  73. return l, nil
  74. }
  75. func (v *VhostMuxer) getListener(name, path string) (l *Listener, exist bool) {
  76. v.mutex.RLock()
  77. defer v.mutex.RUnlock()
  78. // first we check the full hostname
  79. // if not exist, then check the wildcard_domain such as *.example.com
  80. vr, found := v.registryRouter.Get(name, path)
  81. if found {
  82. return vr.payload.(*Listener), true
  83. }
  84. domainSplit := strings.Split(name, ".")
  85. if len(domainSplit) < 3 {
  86. return l, false
  87. }
  88. domainSplit[0] = "*"
  89. name = strings.Join(domainSplit, ".")
  90. vr, found = v.registryRouter.Get(name, path)
  91. if !found {
  92. return
  93. }
  94. return vr.payload.(*Listener), true
  95. }
  96. func (v *VhostMuxer) run() {
  97. for {
  98. conn, err := v.listener.Accept()
  99. if err != nil {
  100. return
  101. }
  102. go v.handle(conn)
  103. }
  104. }
  105. func (v *VhostMuxer) handle(c frpNet.Conn) {
  106. if err := c.SetDeadline(time.Now().Add(v.timeout)); err != nil {
  107. c.Close()
  108. return
  109. }
  110. sConn, reqInfoMap, err := v.vhostFunc(c)
  111. if err != nil {
  112. log.Warn("get hostname from http/https request error: %v", err)
  113. c.Close()
  114. return
  115. }
  116. name := strings.ToLower(reqInfoMap["Host"])
  117. path := strings.ToLower(reqInfoMap["Path"])
  118. l, ok := v.getListener(name, path)
  119. if !ok {
  120. res := notFoundResponse()
  121. res.Write(c)
  122. log.Debug("http request for host [%s] path [%s] not found", name, path)
  123. c.Close()
  124. return
  125. }
  126. // if authFunc is exist and userName/password is set
  127. // then verify user access
  128. if l.mux.authFunc != nil && l.userName != "" && l.passWord != "" {
  129. bAccess, err := l.mux.authFunc(c, l.userName, l.passWord, reqInfoMap["Authorization"])
  130. if bAccess == false || err != nil {
  131. l.Debug("check http Authorization failed")
  132. res := noAuthResponse()
  133. res.Write(c)
  134. c.Close()
  135. return
  136. }
  137. }
  138. if err = sConn.SetDeadline(time.Time{}); err != nil {
  139. c.Close()
  140. return
  141. }
  142. c = sConn
  143. l.Debug("get new http request host [%s] path [%s]", name, path)
  144. err = errors.PanicToError(func() {
  145. l.accept <- c
  146. })
  147. if err != nil {
  148. l.Warn("listener is already closed, ignore this request")
  149. }
  150. }
  151. type Listener struct {
  152. name string
  153. location string
  154. rewriteHost string
  155. userName string
  156. passWord string
  157. mux *VhostMuxer // for closing VhostMuxer
  158. accept chan frpNet.Conn
  159. log.Logger
  160. }
  161. func (l *Listener) Accept() (frpNet.Conn, error) {
  162. conn, ok := <-l.accept
  163. if !ok {
  164. return nil, fmt.Errorf("Listener closed")
  165. }
  166. // if rewriteFunc is exist
  167. // rewrite http requests with a modified host header
  168. // if l.rewriteHost is empty, nothing to do
  169. if l.mux.rewriteFunc != nil {
  170. sConn, err := l.mux.rewriteFunc(conn, l.rewriteHost)
  171. if err != nil {
  172. l.Warn("host header rewrite failed: %v", err)
  173. return nil, fmt.Errorf("host header rewrite failed")
  174. }
  175. l.Debug("rewrite host to [%s] success", l.rewriteHost)
  176. conn = sConn
  177. }
  178. for _, prefix := range l.GetAllPrefix() {
  179. conn.AddLogPrefix(prefix)
  180. }
  181. return conn, nil
  182. }
  183. func (l *Listener) Close() error {
  184. l.mux.registryRouter.Del(l.name, l.location)
  185. close(l.accept)
  186. return nil
  187. }
  188. func (l *Listener) Name() string {
  189. return l.name
  190. }