vhost.go 5.8 KB

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