vhost.go 5.6 KB

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