1
0

vhost.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  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. "context"
  15. "fmt"
  16. "net"
  17. "strings"
  18. "time"
  19. "github.com/fatedier/frp/utils/log"
  20. frpNet "github.com/fatedier/frp/utils/net"
  21. "github.com/fatedier/frp/utils/xlog"
  22. "github.com/fatedier/golib/errors"
  23. )
  24. type muxFunc func(net.Conn) (net.Conn, map[string]string, error)
  25. type httpAuthFunc func(net.Conn, string, string, string) (bool, error)
  26. type hostRewriteFunc func(net.Conn, string) (net.Conn, error)
  27. type VhostMuxer struct {
  28. listener net.Listener
  29. timeout time.Duration
  30. vhostFunc muxFunc
  31. authFunc httpAuthFunc
  32. rewriteFunc hostRewriteFunc
  33. registryRouter *VhostRouters
  34. }
  35. func NewVhostMuxer(listener net.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 CreateConnFunc func(remoteAddr string) (net.Conn, error)
  48. // VhostRouteConfig is the params used to match HTTP requests
  49. type VhostRouteConfig struct {
  50. Domain string
  51. Location string
  52. RewriteHost string
  53. Username string
  54. Password string
  55. Headers map[string]string
  56. CreateConnFn CreateConnFunc
  57. }
  58. // listen for a new domain name, if rewriteHost is not empty and rewriteFunc is not nil
  59. // then rewrite the host header to rewriteHost
  60. func (v *VhostMuxer) Listen(ctx context.Context, cfg *VhostRouteConfig) (l *Listener, err error) {
  61. l = &Listener{
  62. name: cfg.Domain,
  63. location: cfg.Location,
  64. rewriteHost: cfg.RewriteHost,
  65. userName: cfg.Username,
  66. passWord: cfg.Password,
  67. mux: v,
  68. accept: make(chan net.Conn),
  69. ctx: ctx,
  70. }
  71. err = v.registryRouter.Add(cfg.Domain, cfg.Location, l)
  72. if err != nil {
  73. return
  74. }
  75. return l, nil
  76. }
  77. func (v *VhostMuxer) getListener(name, path string) (l *Listener, exist bool) {
  78. // first we check the full hostname
  79. // if not exist, then check the wildcard_domain such as *.example.com
  80. vr, found := v.registryRouter.Get(name, path)
  81. if found {
  82. return vr.payload.(*Listener), true
  83. }
  84. domainSplit := strings.Split(name, ".")
  85. if len(domainSplit) < 3 {
  86. return
  87. }
  88. for {
  89. if len(domainSplit) < 3 {
  90. return
  91. }
  92. domainSplit[0] = "*"
  93. name = strings.Join(domainSplit, ".")
  94. vr, found = v.registryRouter.Get(name, path)
  95. if found {
  96. return vr.payload.(*Listener), true
  97. }
  98. domainSplit = domainSplit[1:]
  99. }
  100. return
  101. }
  102. func (v *VhostMuxer) run() {
  103. for {
  104. conn, err := v.listener.Accept()
  105. if err != nil {
  106. return
  107. }
  108. go v.handle(conn)
  109. }
  110. }
  111. func (v *VhostMuxer) handle(c net.Conn) {
  112. if err := c.SetDeadline(time.Now().Add(v.timeout)); err != nil {
  113. c.Close()
  114. return
  115. }
  116. sConn, reqInfoMap, err := v.vhostFunc(c)
  117. if err != nil {
  118. log.Warn("get hostname from http/https request error: %v", err)
  119. c.Close()
  120. return
  121. }
  122. name := strings.ToLower(reqInfoMap["Host"])
  123. path := strings.ToLower(reqInfoMap["Path"])
  124. l, ok := v.getListener(name, path)
  125. if !ok {
  126. res := notFoundResponse()
  127. res.Write(c)
  128. log.Debug("http request for host [%s] path [%s] not found", name, path)
  129. c.Close()
  130. return
  131. }
  132. xl := xlog.FromContextSafe(l.ctx)
  133. // if authFunc is exist and userName/password is set
  134. // then verify user access
  135. if l.mux.authFunc != nil && l.userName != "" && l.passWord != "" {
  136. bAccess, err := l.mux.authFunc(c, l.userName, l.passWord, reqInfoMap["Authorization"])
  137. if bAccess == false || err != nil {
  138. xl.Debug("check http Authorization failed")
  139. res := noAuthResponse()
  140. res.Write(c)
  141. c.Close()
  142. return
  143. }
  144. }
  145. if err = sConn.SetDeadline(time.Time{}); err != nil {
  146. c.Close()
  147. return
  148. }
  149. c = sConn
  150. xl.Debug("get new http request host [%s] path [%s]", name, path)
  151. err = errors.PanicToError(func() {
  152. l.accept <- c
  153. })
  154. if err != nil {
  155. xl.Warn("listener is already closed, ignore this request")
  156. }
  157. }
  158. type Listener struct {
  159. name string
  160. location string
  161. rewriteHost string
  162. userName string
  163. passWord string
  164. mux *VhostMuxer // for closing VhostMuxer
  165. accept chan net.Conn
  166. ctx context.Context
  167. }
  168. func (l *Listener) Accept() (net.Conn, error) {
  169. xl := xlog.FromContextSafe(l.ctx)
  170. conn, ok := <-l.accept
  171. if !ok {
  172. return nil, fmt.Errorf("Listener closed")
  173. }
  174. // if rewriteFunc is exist
  175. // rewrite http requests with a modified host header
  176. // if l.rewriteHost is empty, nothing to do
  177. if l.mux.rewriteFunc != nil {
  178. sConn, err := l.mux.rewriteFunc(conn, l.rewriteHost)
  179. if err != nil {
  180. xl.Warn("host header rewrite failed: %v", err)
  181. return nil, fmt.Errorf("host header rewrite failed")
  182. }
  183. xl.Debug("rewrite host to [%s] success", l.rewriteHost)
  184. conn = sConn
  185. }
  186. return frpNet.NewContextConn(conn, l.ctx), nil
  187. }
  188. func (l *Listener) Close() error {
  189. l.mux.registryRouter.Del(l.name, l.location)
  190. close(l.accept)
  191. return nil
  192. }
  193. func (l *Listener) Name() string {
  194. return l.name
  195. }
  196. func (l *Listener) Addr() net.Addr {
  197. return (*net.TCPAddr)(nil)
  198. }