vhost.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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. "bytes"
  15. "fmt"
  16. "io"
  17. "strings"
  18. "sync"
  19. "time"
  20. "github.com/fatedier/frp/utils/log"
  21. frpNet "github.com/fatedier/frp/utils/net"
  22. )
  23. type muxFunc func(frpNet.Conn) (frpNet.Conn, map[string]string, error)
  24. type httpAuthFunc func(frpNet.Conn, string, string, string) (bool, error)
  25. type hostRewriteFunc func(frpNet.Conn, string) (frpNet.Conn, error)
  26. type VhostMuxer struct {
  27. listener frpNet.Listener
  28. timeout time.Duration
  29. vhostFunc muxFunc
  30. authFunc httpAuthFunc
  31. rewriteFunc hostRewriteFunc
  32. registryRouter *VhostRouters
  33. mutex sync.RWMutex
  34. }
  35. func NewVhostMuxer(listener frpNet.Listener, vhostFunc muxFunc, authFunc httpAuthFunc, rewriteFunc hostRewriteFunc, timeout time.Duration) (mux *VhostMuxer, err error) {
  36. mux = &VhostMuxer{
  37. listener: listener,
  38. timeout: timeout,
  39. vhostFunc: vhostFunc,
  40. authFunc: authFunc,
  41. rewriteFunc: rewriteFunc,
  42. registryRouter: NewVhostRouters(),
  43. }
  44. go mux.run()
  45. return mux, nil
  46. }
  47. type VhostRouteConfig struct {
  48. Domain string
  49. Location string
  50. RewriteHost string
  51. Username string
  52. Password string
  53. }
  54. // listen for a new domain name, if rewriteHost is not empty and rewriteFunc is not nil
  55. // then rewrite the host header to rewriteHost
  56. func (v *VhostMuxer) Listen(cfg *VhostRouteConfig) (l *Listener, err error) {
  57. v.mutex.Lock()
  58. defer v.mutex.Unlock()
  59. _, ok := v.registryRouter.Exist(cfg.Domain, cfg.Location)
  60. if ok {
  61. return nil, fmt.Errorf("hostname [%s] location [%s] is already registered", cfg.Domain, cfg.Location)
  62. }
  63. l = &Listener{
  64. name: cfg.Domain,
  65. location: cfg.Location,
  66. rewriteHost: cfg.RewriteHost,
  67. userName: cfg.Username,
  68. passWord: cfg.Password,
  69. mux: v,
  70. accept: make(chan frpNet.Conn),
  71. Logger: log.NewPrefixLogger(""),
  72. }
  73. v.registryRouter.Add(cfg.Domain, cfg.Location, l)
  74. return l, nil
  75. }
  76. func (v *VhostMuxer) getListener(name, path string) (l *Listener, exist bool) {
  77. v.mutex.RLock()
  78. defer v.mutex.RUnlock()
  79. // first we check the full hostname
  80. // if not exist, then check the wildcard_domain such as *.example.com
  81. vr, found := v.registryRouter.Get(name, path)
  82. if found {
  83. return vr.listener, true
  84. }
  85. domainSplit := strings.Split(name, ".")
  86. if len(domainSplit) < 3 {
  87. return l, false
  88. }
  89. domainSplit[0] = "*"
  90. name = strings.Join(domainSplit, ".")
  91. vr, found = v.registryRouter.Get(name, path)
  92. if !found {
  93. return
  94. }
  95. return vr.listener, true
  96. }
  97. func (v *VhostMuxer) run() {
  98. for {
  99. conn, err := v.listener.Accept()
  100. if err != nil {
  101. return
  102. }
  103. go v.handle(conn)
  104. }
  105. }
  106. func (v *VhostMuxer) handle(c frpNet.Conn) {
  107. if err := c.SetDeadline(time.Now().Add(v.timeout)); err != nil {
  108. c.Close()
  109. return
  110. }
  111. sConn, reqInfoMap, err := v.vhostFunc(c)
  112. if err != nil {
  113. log.Error("get hostname from http/https request error: %v", err)
  114. c.Close()
  115. return
  116. }
  117. name := strings.ToLower(reqInfoMap["Host"])
  118. path := strings.ToLower(reqInfoMap["Path"])
  119. l, ok := v.getListener(name, path)
  120. if !ok {
  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. // 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 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 and rewriteHost is set
  161. // rewrite http requests with a modified host header
  162. if l.mux.rewriteFunc != nil && l.rewriteHost != "" {
  163. sConn, err := l.mux.rewriteFunc(conn, l.rewriteHost)
  164. if err != nil {
  165. l.Warn("host header rewrite failed: %v", err)
  166. return nil, fmt.Errorf("host header rewrite failed")
  167. }
  168. l.Debug("rewrite host to [%s] success", l.rewriteHost)
  169. conn = sConn
  170. }
  171. for _, prefix := range l.GetAllPrefix() {
  172. conn.AddLogPrefix(prefix)
  173. }
  174. return conn, nil
  175. }
  176. func (l *Listener) Close() error {
  177. l.mux.registryRouter.Del(l.name, l.location)
  178. close(l.accept)
  179. return nil
  180. }
  181. func (l *Listener) Name() string {
  182. return l.name
  183. }
  184. type sharedConn struct {
  185. frpNet.Conn
  186. sync.Mutex
  187. buff *bytes.Buffer
  188. }
  189. // the bytes you read in io.Reader, will be reserved in sharedConn
  190. func newShareConn(conn frpNet.Conn) (*sharedConn, io.Reader) {
  191. sc := &sharedConn{
  192. Conn: conn,
  193. buff: bytes.NewBuffer(make([]byte, 0, 1024)),
  194. }
  195. return sc, io.TeeReader(conn, sc.buff)
  196. }
  197. func (sc *sharedConn) Read(p []byte) (n int, err error) {
  198. sc.Lock()
  199. if sc.buff == nil {
  200. sc.Unlock()
  201. return sc.Conn.Read(p)
  202. }
  203. sc.Unlock()
  204. n, err = sc.buff.Read(p)
  205. if err == io.EOF {
  206. sc.Lock()
  207. sc.buff = nil
  208. sc.Unlock()
  209. var n2 int
  210. n2, err = sc.Conn.Read(p[n:])
  211. n += n2
  212. }
  213. return
  214. }
  215. func (sc *sharedConn) WriteBuff(buffer []byte) (err error) {
  216. sc.buff.Reset()
  217. _, err = sc.buff.Write(buffer)
  218. return err
  219. }