vhost.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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. "time"
  17. "github.com/fatedier/frp/utils/log"
  18. frpNet "github.com/fatedier/frp/utils/net"
  19. "github.com/fatedier/golib/errors"
  20. )
  21. type muxFunc func(frpNet.Conn) (frpNet.Conn, map[string]string, error)
  22. type httpAuthFunc func(frpNet.Conn, string, string, string) (bool, error)
  23. type hostRewriteFunc func(frpNet.Conn, string) (frpNet.Conn, error)
  24. type VhostMuxer struct {
  25. listener frpNet.Listener
  26. timeout time.Duration
  27. vhostFunc muxFunc
  28. authFunc httpAuthFunc
  29. rewriteFunc hostRewriteFunc
  30. registryRouter *VhostRouters
  31. }
  32. func NewVhostMuxer(listener frpNet.Listener, vhostFunc muxFunc, authFunc httpAuthFunc, rewriteFunc hostRewriteFunc, timeout time.Duration) (mux *VhostMuxer, err error) {
  33. mux = &VhostMuxer{
  34. listener: listener,
  35. timeout: timeout,
  36. vhostFunc: vhostFunc,
  37. authFunc: authFunc,
  38. rewriteFunc: rewriteFunc,
  39. registryRouter: NewVhostRouters(),
  40. }
  41. go mux.run()
  42. return mux, nil
  43. }
  44. type CreateConnFunc func(remoteAddr string) (frpNet.Conn, error)
  45. // VhostRouteConfig is the params used to match HTTP requests
  46. type VhostRouteConfig struct {
  47. Domain string
  48. Location string
  49. RewriteHost string
  50. Username string
  51. Password string
  52. Headers map[string]string
  53. CreateConnFn CreateConnFunc
  54. }
  55. // listen for a new domain name, if rewriteHost is not empty and rewriteFunc is not nil
  56. // then rewrite the host header to rewriteHost
  57. func (v *VhostMuxer) Listen(cfg *VhostRouteConfig) (l *Listener, err error) {
  58. l = &Listener{
  59. name: cfg.Domain,
  60. location: cfg.Location,
  61. rewriteHost: cfg.RewriteHost,
  62. userName: cfg.Username,
  63. passWord: cfg.Password,
  64. mux: v,
  65. accept: make(chan frpNet.Conn),
  66. Logger: log.NewPrefixLogger(""),
  67. }
  68. err = v.registryRouter.Add(cfg.Domain, cfg.Location, l)
  69. if err != nil {
  70. return
  71. }
  72. return l, nil
  73. }
  74. func (v *VhostMuxer) getListener(name, path string) (l *Listener, exist bool) {
  75. // first we check the full hostname
  76. // if not exist, then check the wildcard_domain such as *.example.com
  77. vr, found := v.registryRouter.Get(name, path)
  78. if found {
  79. return vr.payload.(*Listener), true
  80. }
  81. domainSplit := strings.Split(name, ".")
  82. if len(domainSplit) < 3 {
  83. return
  84. }
  85. for {
  86. if len(domainSplit) < 3 {
  87. return
  88. }
  89. domainSplit[0] = "*"
  90. name = strings.Join(domainSplit, ".")
  91. vr, found = v.registryRouter.Get(name, path)
  92. if found {
  93. return vr.payload.(*Listener), true
  94. }
  95. domainSplit = domainSplit[1:]
  96. }
  97. return
  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. }