| // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 |
| 15 | package vhost |
| 16 |
| 17 | import ( |
| 18 | "context" |
| 19 | "encoding/base64" |
| 20 | "errors" |
| 21 | "fmt" |
| 22 | stdlog "log" |
| 23 | "net" |
| 24 | "net/http" |
| 25 | "net/http/httputil" |
| 26 | "net/url" |
| 27 | "time" |
| 28 |
| 29 | libio "github.com/fatedier/golib/io" |
| 30 | "github.com/fatedier/golib/pool" |
| 31 | "golang.org/x/net/http2" |
| 32 | "golang.org/x/net/http2/h2c" |
| 33 |
| 34 | httppkg "github.com/fatedier/frp/pkg/util/http" |
| 35 | "github.com/fatedier/frp/pkg/util/log" |
| 36 | ) |
| 37 |
| 38 | var ErrNoRouteFound = errors.New("no route found") |
| 39 |
| 40 | type HTTPReverseProxyOptions struct { |
| 41 | ResponseHeaderTimeoutS int64 |
| 42 | } |
| 43 |
| 44 | type HTTPReverseProxy struct { |
| 45 | proxy http.Handler |
| 46 | vhostRouter *Routers |
| 47 |
| 48 | responseHeaderTimeout time.Duration |
| 49 | } |
| 50 |
| 51 | func NewHTTPReverseProxy(option HTTPReverseProxyOptions, vhostRouter *Routers) *HTTPReverseProxy { |
| 52 | if option.ResponseHeaderTimeoutS <= 0 { |
| 53 | option.ResponseHeaderTimeoutS = 60 |
| 54 | } |
| 55 | rp := &HTTPReverseProxy{ |
| 56 | responseHeaderTimeout: time.Duration(option.ResponseHeaderTimeoutS) * time.Second, |
| 57 | vhostRouter: vhostRouter, |
| 58 | } |
| 59 | proxy := &httputil.ReverseProxy{ |
| 60 | // Modify incoming requests by route policies. |
| 61 | Rewrite: func(r *httputil.ProxyRequest) { |
| 62 | r.Out.Header["X-Forwarded-For"] = r.In.Header["X-Forwarded-For"] |
| 63 | r.SetXForwarded() |
| 64 | req := r.Out |
| 65 | req.URL.Scheme = "http" |
| 66 | reqRouteInfo := req.Context().Value(RouteInfoKey).(*RequestRouteInfo) |
| 67 | originalHost, _ := httppkg.CanonicalHost(reqRouteInfo.Host) |
| 68 |
| 69 | rc := req.Context().Value(RouteConfigKey).(*RouteConfig) |
| 70 | if rc != nil { |
| 71 | if rc.RewriteHost != "" { |
| 72 | req.Host = rc.RewriteHost |
| 73 | } |
| 74 |
| 75 | var endpoint string |
| 76 | if rc.ChooseEndpointFn != nil { |
| 77 | // ignore error here, it will use CreateConnFn instead later |
| 78 | endpoint, _ = rc.ChooseEndpointFn() |
| 79 | reqRouteInfo.Endpoint = endpoint |
| 80 | log.Tracef("choose endpoint name [%s] for http request host [%s] path [%s] httpuser [%s]", |
| 81 | endpoint, originalHost, reqRouteInfo.URL, reqRouteInfo.HTTPUser) |
| 82 | } |
| 83 | // Set {domain}.{location}.{routeByHTTPUser}.{endpoint} as URL host here to let http transport reuse connections. |
| 84 | req.URL.Host = rc.Domain + "." + |
| 85 | base64.StdEncoding.EncodeToString([]byte(rc.Location)) + "." + |
| 86 | base64.StdEncoding.EncodeToString([]byte(rc.RouteByHTTPUser)) + "." + |
| 87 | base64.StdEncoding.EncodeToString([]byte(endpoint)) |
| 88 |
| 89 | for k, v := range rc.Headers { |
| 90 | req.Header.Set(k, v) |
| 91 | } |
| 92 | } else { |
| 93 | req.URL.Host = req.Host |
| 94 | } |
| 95 | }, |
| 96 | ModifyResponse: func(r *http.Response) error { |
| 97 | rc := r.Request.Context().Value(RouteConfigKey).(*RouteConfig) |
| 98 | if rc != nil { |
| 99 | for k, v := range rc.ResponseHeaders { |
| 100 | r.Header.Set(k, v) |
| 101 | } |
| 102 | } |
| 103 | return nil |
| 104 | }, |
| 105 | // Create a connection to one proxy routed by route policy. |
| 106 | Transport: &http.Transport{ |
| 107 | ResponseHeaderTimeout: rp.responseHeaderTimeout, |
| 108 | IdleConnTimeout: 60 * time.Second, |
| 109 | MaxIdleConnsPerHost: 5, |
| 110 | DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) { |
| 111 | return rp.CreateConnection(ctx.Value(RouteInfoKey).(*RequestRouteInfo), true) |
| 112 | }, |
| 113 | Proxy: func(req *http.Request) (*url.URL, error) { |
| 114 | // Use proxy mode if there is host in HTTP first request line. |
| 115 | // GET http://example.com/ HTTP/1.1 |
| 116 | // Host: example.com |
| 117 | // |
| 118 | // Normal: |
| 119 | // GET / HTTP/1.1 |
| 120 | // Host: example.com |
| 121 | urlHost := req.Context().Value(RouteInfoKey).(*RequestRouteInfo).URLHost |
| 122 | if urlHost != "" { |
| 123 | return req.URL, nil |
| 124 | } |
| 125 | return nil, nil |
| 126 | }, |
| 127 | }, |
| 128 | BufferPool: pool.NewBuffer(32 * 1024), |
| 129 | ErrorLog: stdlog.New(log.NewWriteLogger(log.WarnLevel, 2), "", 0), |
| 130 | ErrorHandler: func(rw http.ResponseWriter, req *http.Request, err error) { |
| 131 | log.Logf(log.WarnLevel, 1, "do http proxy request [host: %s] error: %v", req.Host, err) |
| 132 | if err != nil { |
| 133 | if e, ok := err.(net.Error); ok && e.Timeout() { |
| 134 | rw.WriteHeader(http.StatusGatewayTimeout) |
| 135 | return |
| 136 | } |
| 137 | } |
| 138 | rw.WriteHeader(http.StatusNotFound) |
| 139 | _, _ = rw.Write(getNotFoundPageContent()) |
| 140 | }, |
| 141 | } |
| 142 | rp.proxy = h2c.NewHandler(proxy, &http2.Server{}) |
| 143 | return rp |
| 144 | } |
| 145 |
| 146 | // Register register the route config to reverse proxy |
| 147 | // reverse proxy will use CreateConnFn from routeCfg to create a connection to the remote service |
| 148 | func (rp *HTTPReverseProxy) Register(routeCfg RouteConfig) error { |
| 149 | err := rp.vhostRouter.Add(routeCfg.Domain, routeCfg.Location, routeCfg.RouteByHTTPUser, &routeCfg) |
| 150 | if err != nil { |
| 151 | return err |
| 152 | } |
| 153 | return nil |
| 154 | } |
| 155 |
| 156 | // UnRegister unregister route config by domain and location |
| 157 | func (rp *HTTPReverseProxy) UnRegister(routeCfg RouteConfig) { |
| 158 | rp.vhostRouter.Del(routeCfg.Domain, routeCfg.Location, routeCfg.RouteByHTTPUser) |
| 159 | } |
| 160 |
| 161 | func (rp *HTTPReverseProxy) GetRouteConfig(domain, location, routeByHTTPUser string) *RouteConfig { |
| 162 | vr, ok := rp.vhostRouter.getByRoute(domain, location, routeByHTTPUser) |
| 163 | if ok { |
| 164 | log.Debugf("get new http request host [%s] path [%s] httpuser [%s]", domain, location, routeByHTTPUser) |
| 165 | return vr.payload.(*RouteConfig) |
| 166 | } |
| 167 | return nil |
| 168 | } |
| 169 |
| 170 | // CreateConnection create a new connection by route config |
| 171 | func (rp *HTTPReverseProxy) CreateConnection(reqRouteInfo *RequestRouteInfo, byEndpoint bool) (net.Conn, error) { |
| 172 | host, _ := httppkg.CanonicalHost(reqRouteInfo.Host) |
| 173 | vr, ok := rp.vhostRouter.getByRoute(host, reqRouteInfo.URL, reqRouteInfo.HTTPUser) |
| 174 | if ok { |
| 175 | if byEndpoint { |
| 176 | fn := vr.payload.(*RouteConfig).CreateConnByEndpointFn |
| 177 | if fn != nil { |
| 178 | return fn(reqRouteInfo.Endpoint, reqRouteInfo.RemoteAddr) |
| 179 | } |
| 180 | } |
| 181 | fn := vr.payload.(*RouteConfig).CreateConnFn |
| 182 | if fn != nil { |
| 183 | return fn(reqRouteInfo.RemoteAddr) |
| 184 | } |
| 185 | } |
| 186 | return nil, fmt.Errorf("%v: %s %s %s", ErrNoRouteFound, host, reqRouteInfo.URL, reqRouteInfo.HTTPUser) |
| 187 | } |
| 188 |
| 189 | func checkRouteAuthByRequest(req *http.Request, rc *RouteConfig) bool { |
| 190 | if rc == nil { |
| 191 | return true |
| 192 | } |
| 193 | if rc.Username == "" && rc.Password == "" { |
| 194 | return true |
| 195 | } |
| 196 |
| 197 | if req.URL.Host != "" { |
| 198 | proxyAuth := req.Header.Get("Proxy-Authorization") |
| 199 | if proxyAuth == "" { |
| 200 | return false |
| 201 | } |
| 202 | user, passwd, ok := httppkg.ParseBasicAuth(proxyAuth) |
| 203 | return ok && user == rc.Username && passwd == rc.Password |
| 204 | } |
| 205 |
| 206 | user, passwd, ok := req.BasicAuth() |
| 207 | return ok && user == rc.Username && passwd == rc.Password |
| 208 | } |
| 209 |
| 210 | func (rp *HTTPReverseProxy) connectHandler(rw http.ResponseWriter, req *http.Request) { |
| 211 | hj, ok := rw.(http.Hijacker) |
| 212 | if !ok { |
| 213 | rw.WriteHeader(http.StatusInternalServerError) |
| 214 | return |
| 215 | } |
| 216 |
| 217 | client, _, err := hj.Hijack() |
| 218 | if err != nil { |
| 219 | rw.WriteHeader(http.StatusInternalServerError) |
| 220 | return |
| 221 | } |
| 222 |
| 223 | remote, err := rp.CreateConnection(req.Context().Value(RouteInfoKey).(*RequestRouteInfo), false) |
| 224 | if err != nil { |
| 225 | _ = NotFoundResponse().Write(client) |
| 226 | client.Close() |
| 227 | return |
| 228 | } |
| 229 | _ = req.Write(remote) |
| 230 | go libio.Join(remote, client) |
| 231 | } |
| 232 |
| 233 | func getRequestRouteUser(req *http.Request) string { |
| 234 | if req.URL.Host != "" { |
| 235 | proxyAuth := req.Header.Get("Proxy-Authorization") |
| 236 | if proxyAuth == "" { |
| 237 | // Preserve legacy proxy-mode routing when clients send only Authorization, |
| 238 | // so requests still hit the matched route and return 407 instead of 404. |
| 239 | // Auth validation intentionally does not share this fallback. |
| 240 | user, _, _ := req.BasicAuth() |
| 241 | return user |
| 242 | } |
| 243 | user, _, _ := httppkg.ParseBasicAuth(proxyAuth) |
| 244 | return user |
| 245 | } |
| 246 | user, _, _ := req.BasicAuth() |
| 247 | return user |
| 248 | } |
| 249 |
| 250 | func (rp *HTTPReverseProxy) injectRequestInfoToCtx(req *http.Request) *http.Request { |
| 251 | user := getRequestRouteUser(req) |
| 252 |
| 253 | reqRouteInfo := &RequestRouteInfo{ |
| 254 | URL: req.URL.Path, |
| 255 | Host: req.Host, |
| 256 | HTTPUser: user, |
| 257 | RemoteAddr: req.RemoteAddr, |
| 258 | URLHost: req.URL.Host, |
| 259 | } |
| 260 |
| 261 | originalHost, _ := httppkg.CanonicalHost(reqRouteInfo.Host) |
| 262 | rc := rp.GetRouteConfig(originalHost, reqRouteInfo.URL, reqRouteInfo.HTTPUser) |
| 263 |
| 264 | newctx := req.Context() |
| 265 | newctx = context.WithValue(newctx, RouteInfoKey, reqRouteInfo) |
| 266 | newctx = context.WithValue(newctx, RouteConfigKey, rc) |
| 267 | return req.Clone(newctx) |
| 268 | } |
| 269 |
| 270 | func (rp *HTTPReverseProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) { |
| 271 | newreq := rp.injectRequestInfoToCtx(req) |
| 272 | rc := newreq.Context().Value(RouteConfigKey).(*RouteConfig) |
| 273 | if !checkRouteAuthByRequest(req, rc) { |
| 274 | if req.URL.Host != "" { |
| 275 | rw.Header().Set("Proxy-Authenticate", `Basic realm="Restricted"`) |
| 276 | http.Error(rw, http.StatusText(http.StatusProxyAuthRequired), http.StatusProxyAuthRequired) |
| 277 | } else { |
| 278 | rw.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`) |
| 279 | http.Error(rw, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) |
| 280 | } |
| 281 | return |
| 282 | } |
| 283 |
| 284 | if req.Method == http.MethodConnect { |
| 285 | rp.connectHandler(rw, newreq) |
| 286 | } else { |
| 287 | rp.proxy.ServeHTTP(rw, newreq) |
| 288 | } |
| 289 | } |