vhost.go 5.4 KB

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