vhost.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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. return
  104. }
  105. func (v *VhostMuxer) run() {
  106. for {
  107. conn, err := v.listener.Accept()
  108. if err != nil {
  109. return
  110. }
  111. go v.handle(conn)
  112. }
  113. }
  114. func (v *VhostMuxer) handle(c net.Conn) {
  115. if err := c.SetDeadline(time.Now().Add(v.timeout)); err != nil {
  116. c.Close()
  117. return
  118. }
  119. sConn, reqInfoMap, err := v.vhostFunc(c)
  120. if err != nil {
  121. log.Warn("get hostname from http/https request error: %v", err)
  122. c.Close()
  123. return
  124. }
  125. name := strings.ToLower(reqInfoMap["Host"])
  126. path := strings.ToLower(reqInfoMap["Path"])
  127. l, ok := v.getListener(name, path)
  128. if !ok {
  129. res := notFoundResponse()
  130. res.Write(c)
  131. log.Debug("http request for host [%s] path [%s] not found", name, path)
  132. c.Close()
  133. return
  134. }
  135. xl := xlog.FromContextSafe(l.ctx)
  136. if v.successFunc != nil {
  137. if err := v.successFunc(c); err != nil {
  138. xl.Info("success func failure on vhost connection: %v", err)
  139. c.Close()
  140. return
  141. }
  142. }
  143. // if authFunc is exist and userName/password is set
  144. // then verify user access
  145. if l.mux.authFunc != nil && l.userName != "" && l.passWord != "" {
  146. bAccess, err := l.mux.authFunc(c, l.userName, l.passWord, reqInfoMap["Authorization"])
  147. if bAccess == false || err != nil {
  148. xl.Debug("check http Authorization failed")
  149. res := noAuthResponse()
  150. res.Write(c)
  151. c.Close()
  152. return
  153. }
  154. }
  155. if err = sConn.SetDeadline(time.Time{}); err != nil {
  156. c.Close()
  157. return
  158. }
  159. c = sConn
  160. xl.Debug("get new http request host [%s] path [%s]", name, path)
  161. err = errors.PanicToError(func() {
  162. l.accept <- c
  163. })
  164. if err != nil {
  165. xl.Warn("listener is already closed, ignore this request")
  166. }
  167. }
  168. type Listener struct {
  169. name string
  170. location string
  171. rewriteHost string
  172. userName string
  173. passWord string
  174. mux *VhostMuxer // for closing VhostMuxer
  175. accept chan net.Conn
  176. ctx context.Context
  177. }
  178. func (l *Listener) Accept() (net.Conn, error) {
  179. xl := xlog.FromContextSafe(l.ctx)
  180. conn, ok := <-l.accept
  181. if !ok {
  182. return nil, fmt.Errorf("Listener closed")
  183. }
  184. // if rewriteFunc is exist
  185. // rewrite http requests with a modified host header
  186. // if l.rewriteHost is empty, nothing to do
  187. if l.mux.rewriteFunc != nil {
  188. sConn, err := l.mux.rewriteFunc(conn, l.rewriteHost)
  189. if err != nil {
  190. xl.Warn("host header rewrite failed: %v", err)
  191. return nil, fmt.Errorf("host header rewrite failed")
  192. }
  193. xl.Debug("rewrite host to [%s] success", l.rewriteHost)
  194. conn = sConn
  195. }
  196. return frpNet.NewContextConn(conn, l.ctx), nil
  197. }
  198. func (l *Listener) Close() error {
  199. l.mux.registryRouter.Del(l.name, l.location)
  200. close(l.accept)
  201. return nil
  202. }
  203. func (l *Listener) Name() string {
  204. return l.name
  205. }
  206. func (l *Listener) Addr() net.Addr {
  207. return (*net.TCPAddr)(nil)
  208. }