vhost.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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 l, false
  90. }
  91. domainSplit[0] = "*"
  92. name = strings.Join(domainSplit, ".")
  93. vr, found = v.registryRouter.Get(name, path)
  94. if !found {
  95. return
  96. }
  97. return vr.payload.(*Listener), true
  98. }
  99. func (v *VhostMuxer) run() {
  100. for {
  101. conn, err := v.listener.Accept()
  102. if err != nil {
  103. return
  104. }
  105. go v.handle(conn)
  106. }
  107. }
  108. func (v *VhostMuxer) handle(c frpNet.Conn) {
  109. if err := c.SetDeadline(time.Now().Add(v.timeout)); err != nil {
  110. c.Close()
  111. return
  112. }
  113. sConn, reqInfoMap, err := v.vhostFunc(c)
  114. if err != nil {
  115. log.Warn("get hostname from http/https request error: %v", err)
  116. c.Close()
  117. return
  118. }
  119. name := strings.ToLower(reqInfoMap["Host"])
  120. path := strings.ToLower(reqInfoMap["Path"])
  121. l, ok := v.getListener(name, path)
  122. if !ok {
  123. res := notFoundResponse()
  124. res.Write(c)
  125. log.Debug("http request for host [%s] path [%s] not found", name, path)
  126. c.Close()
  127. return
  128. }
  129. // if authFunc is exist and userName/password is set
  130. // then verify user access
  131. if l.mux.authFunc != nil && l.userName != "" && l.passWord != "" {
  132. bAccess, err := l.mux.authFunc(c, l.userName, l.passWord, reqInfoMap["Authorization"])
  133. if bAccess == false || err != nil {
  134. l.Debug("check http Authorization failed")
  135. res := noAuthResponse()
  136. res.Write(c)
  137. c.Close()
  138. return
  139. }
  140. }
  141. if err = sConn.SetDeadline(time.Time{}); err != nil {
  142. c.Close()
  143. return
  144. }
  145. c = sConn
  146. l.Debug("get new http request host [%s] path [%s]", name, path)
  147. err = errors.PanicToError(func() {
  148. l.accept <- c
  149. })
  150. if err != nil {
  151. l.Warn("listener is already closed, ignore this request")
  152. }
  153. }
  154. type Listener struct {
  155. name string
  156. location string
  157. rewriteHost string
  158. userName string
  159. passWord string
  160. mux *VhostMuxer // for closing VhostMuxer
  161. accept chan frpNet.Conn
  162. log.Logger
  163. }
  164. func (l *Listener) Accept() (frpNet.Conn, error) {
  165. conn, ok := <-l.accept
  166. if !ok {
  167. return nil, fmt.Errorf("Listener closed")
  168. }
  169. // if rewriteFunc is exist
  170. // rewrite http requests with a modified host header
  171. // if l.rewriteHost is empty, nothing to do
  172. if l.mux.rewriteFunc != nil {
  173. sConn, err := l.mux.rewriteFunc(conn, l.rewriteHost)
  174. if err != nil {
  175. l.Warn("host header rewrite failed: %v", err)
  176. return nil, fmt.Errorf("host header rewrite failed")
  177. }
  178. l.Debug("rewrite host to [%s] success", l.rewriteHost)
  179. conn = sConn
  180. }
  181. for _, prefix := range l.GetAllPrefix() {
  182. conn.AddLogPrefix(prefix)
  183. }
  184. return conn, nil
  185. }
  186. func (l *Listener) Close() error {
  187. l.mux.registryRouter.Del(l.name, l.location)
  188. close(l.accept)
  189. return nil
  190. }
  191. func (l *Listener) Name() string {
  192. return l.name
  193. }