vhost.go 5.2 KB

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