frp/pkg/util/vhost/vhost.go

246 lines
5.9 KiB
Go
Raw Normal View History

2016-04-18 09:16:40 +02:00
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package vhost
import (
2019-10-12 14:13:12 +02:00
"context"
2016-04-18 09:16:40 +02:00
"fmt"
2019-10-12 14:13:12 +02:00
"net"
2016-04-18 09:16:40 +02:00
"strings"
"time"
2020-09-23 07:49:14 +02:00
"github.com/fatedier/frp/pkg/util/log"
frpNet "github.com/fatedier/frp/pkg/util/net"
"github.com/fatedier/frp/pkg/util/xlog"
2018-05-07 20:13:30 +02:00
"github.com/fatedier/golib/errors"
2016-04-18 09:16:40 +02:00
)
2020-05-24 11:48:37 +02:00
type RouteInfo string
const (
RouteInfoURL RouteInfo = "url"
RouteInfoHost RouteInfo = "host"
RouteInfoRemote RouteInfo = "remote"
)
2019-10-12 14:13:12 +02:00
type muxFunc func(net.Conn) (net.Conn, map[string]string, error)
type httpAuthFunc func(net.Conn, string, string, string) (bool, error)
type hostRewriteFunc func(net.Conn, string) (net.Conn, error)
type successFunc func(net.Conn) error
2016-04-18 09:16:40 +02:00
2020-05-24 11:48:37 +02:00
type Muxer struct {
2019-10-12 14:13:12 +02:00
listener net.Listener
timeout time.Duration
vhostFunc muxFunc
authFunc httpAuthFunc
successFunc successFunc
rewriteFunc hostRewriteFunc
2020-05-24 11:48:37 +02:00
registryRouter *Routers
2016-04-18 09:16:40 +02:00
}
2020-05-24 11:48:37 +02:00
func NewMuxer(listener net.Listener, vhostFunc muxFunc, authFunc httpAuthFunc, successFunc successFunc, rewriteFunc hostRewriteFunc, timeout time.Duration) (mux *Muxer, err error) {
mux = &Muxer{
listener: listener,
timeout: timeout,
vhostFunc: vhostFunc,
authFunc: authFunc,
successFunc: successFunc,
rewriteFunc: rewriteFunc,
2020-05-24 11:48:37 +02:00
registryRouter: NewRouters(),
2016-04-18 09:16:40 +02:00
}
go mux.run()
return mux, nil
}
2019-10-12 14:13:12 +02:00
type CreateConnFunc func(remoteAddr string) (net.Conn, error)
2017-12-13 16:44:27 +01:00
2020-05-24 11:48:37 +02:00
// RouteConfig is the params used to match HTTP requests
type RouteConfig struct {
2017-03-09 19:01:17 +01:00
Domain string
Location string
RewriteHost string
Username string
Password string
2018-05-20 17:22:07 +02:00
Headers map[string]string
2017-12-13 16:44:27 +01:00
CreateConnFn CreateConnFunc
2017-03-09 19:01:17 +01:00
}
// listen for a new domain name, if rewriteHost is not empty and rewriteFunc is not nil
// then rewrite the host header to rewriteHost
2020-05-24 11:48:37 +02:00
func (v *Muxer) Listen(ctx context.Context, cfg *RouteConfig) (l *Listener, err error) {
2016-12-24 18:53:23 +01:00
l = &Listener{
2017-03-09 19:01:17 +01:00
name: cfg.Domain,
location: cfg.Location,
rewriteHost: cfg.RewriteHost,
userName: cfg.Username,
passWord: cfg.Password,
2016-12-24 18:53:23 +01:00
mux: v,
2019-10-12 14:13:12 +02:00
accept: make(chan net.Conn),
ctx: ctx,
2016-04-18 09:16:40 +02:00
}
2019-07-30 18:41:58 +02:00
err = v.registryRouter.Add(cfg.Domain, cfg.Location, l)
if err != nil {
return
}
2016-12-24 18:53:23 +01:00
return l, nil
2016-04-18 09:16:40 +02:00
}
2020-05-24 11:48:37 +02:00
func (v *Muxer) getListener(name, path string) (l *Listener, exist bool) {
2016-12-24 18:53:23 +01:00
// first we check the full hostname
// if not exist, then check the wildcard_domain such as *.example.com
vr, found := v.registryRouter.Get(name, path)
if found {
2017-12-12 20:27:43 +01:00
return vr.payload.(*Listener), true
2016-08-22 18:58:51 +02:00
}
2016-08-22 18:58:51 +02:00
domainSplit := strings.Split(name, ".")
if len(domainSplit) < 3 {
return
}
for {
if len(domainSplit) < 3 {
return
}
domainSplit[0] = "*"
name = strings.Join(domainSplit, ".")
vr, found = v.registryRouter.Get(name, path)
if found {
return vr.payload.(*Listener), true
}
domainSplit = domainSplit[1:]
}
2016-04-18 09:16:40 +02:00
}
2020-05-24 11:48:37 +02:00
func (v *Muxer) run() {
2016-04-18 09:16:40 +02:00
for {
conn, err := v.listener.Accept()
if err != nil {
return
}
go v.handle(conn)
}
}
2020-05-24 11:48:37 +02:00
func (v *Muxer) handle(c net.Conn) {
2016-04-18 09:16:40 +02:00
if err := c.SetDeadline(time.Now().Add(v.timeout)); err != nil {
2016-08-22 18:58:51 +02:00
c.Close()
2016-04-18 09:16:40 +02:00
return
}
sConn, reqInfoMap, err := v.vhostFunc(c)
2016-04-18 09:16:40 +02:00
if err != nil {
log.Warn("get hostname from http/https request error: %v", err)
2016-08-22 18:58:51 +02:00
c.Close()
2016-04-18 09:16:40 +02:00
return
}
2016-12-24 18:53:23 +01:00
name := strings.ToLower(reqInfoMap["Host"])
path := strings.ToLower(reqInfoMap["Path"])
l, ok := v.getListener(name, path)
2016-04-18 09:16:40 +02:00
if !ok {
res := notFoundResponse()
res.Write(c)
2017-03-11 19:03:24 +01:00
log.Debug("http request for host [%s] path [%s] not found", name, path)
2016-08-22 18:58:51 +02:00
c.Close()
2016-04-18 09:16:40 +02:00
return
}
2019-10-12 14:13:12 +02:00
xl := xlog.FromContextSafe(l.ctx)
if v.successFunc != nil {
if err := v.successFunc(c); err != nil {
xl.Info("success func failure on vhost connection: %v", err)
c.Close()
return
}
}
2016-04-18 09:16:40 +02:00
// if authFunc is exist and userName/password is set
// then verify user access
2017-03-11 19:03:24 +01:00
if l.mux.authFunc != nil && l.userName != "" && l.passWord != "" {
bAccess, err := l.mux.authFunc(c, l.userName, l.passWord, reqInfoMap["Authorization"])
if bAccess == false || err != nil {
2019-10-12 14:13:12 +02:00
xl.Debug("check http Authorization failed")
res := noAuthResponse()
2017-03-08 19:03:47 +01:00
res.Write(c)
c.Close()
return
}
}
2016-04-18 09:16:40 +02:00
if err = sConn.SetDeadline(time.Time{}); err != nil {
2016-08-22 18:58:51 +02:00
c.Close()
2016-04-18 09:16:40 +02:00
return
}
2017-03-08 19:03:47 +01:00
c = sConn
2016-04-18 09:16:40 +02:00
2019-10-12 14:13:12 +02:00
xl.Debug("get new http request host [%s] path [%s]", name, path)
err = errors.PanicToError(func() {
l.accept <- c
})
if err != nil {
2019-10-12 14:13:12 +02:00
xl.Warn("listener is already closed, ignore this request")
}
2016-04-18 09:16:40 +02:00
}
type Listener struct {
name string
location string
rewriteHost string
userName string
passWord string
2020-05-24 11:48:37 +02:00
mux *Muxer // for closing Muxer
2019-10-12 14:13:12 +02:00
accept chan net.Conn
ctx context.Context
2016-04-18 09:16:40 +02:00
}
2019-10-12 14:13:12 +02:00
func (l *Listener) Accept() (net.Conn, error) {
xl := xlog.FromContextSafe(l.ctx)
2016-04-18 09:16:40 +02:00
conn, ok := <-l.accept
if !ok {
return nil, fmt.Errorf("Listener closed")
}
// if rewriteFunc is exist
// rewrite http requests with a modified host header
// if l.rewriteHost is empty, nothing to do
if l.mux.rewriteFunc != nil {
sConn, err := l.mux.rewriteFunc(conn, l.rewriteHost)
if err != nil {
2019-10-12 14:13:12 +02:00
xl.Warn("host header rewrite failed: %v", err)
2017-03-11 19:03:24 +01:00
return nil, fmt.Errorf("host header rewrite failed")
}
2019-10-12 14:13:12 +02:00
xl.Debug("rewrite host to [%s] success", l.rewriteHost)
2017-03-08 19:03:47 +01:00
conn = sConn
}
2020-05-24 11:48:37 +02:00
return frpNet.NewContextConn(l.ctx, conn), nil
2016-04-18 09:16:40 +02:00
}
func (l *Listener) Close() error {
l.mux.registryRouter.Del(l.name, l.location)
2016-04-18 09:16:40 +02:00
close(l.accept)
return nil
}
func (l *Listener) Name() string {
return l.name
}
2019-10-12 14:13:12 +02:00
func (l *Listener) Addr() net.Addr {
return (*net.TCPAddr)(nil)
}