vhost.go 5.2 KB

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