1
0

vhost.go 5.4 KB

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