| 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 |
| // 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 |
| 13 | package vhost |
| 14 |
| 15 | import ( |
| 16 | "context" |
| 17 | "fmt" |
| 18 | "net" |
| 19 | "strings" |
| 20 | "time" |
| 21 |
| 22 | "github.com/fatedier/golib/errors" |
| 23 |
| 24 | "github.com/fatedier/frp/pkg/util/log" |
| 25 | netpkg "github.com/fatedier/frp/pkg/util/net" |
| 26 | "github.com/fatedier/frp/pkg/util/xlog" |
| 27 | ) |
| 28 |
| 29 | type RouteInfo string |
| 30 |
| 31 | const ( |
| 32 | RouteInfoKey RouteInfo = "routeInfo" |
| 33 | RouteConfigKey RouteInfo = "routeConfig" |
| 34 | ) |
| 35 |
| 36 | type RequestRouteInfo struct { |
| 37 | URL string |
| 38 | Host string |
| 39 | HTTPUser string |
| 40 | RemoteAddr string |
| 41 | URLHost string |
| 42 | Endpoint string |
| 43 | } |
| 44 |
| 45 | type ( |
| 46 | muxFunc func(net.Conn) (net.Conn, map[string]string, error) |
| 47 | authFunc func(conn net.Conn, username, password string, reqInfoMap map[string]string) (bool, error) |
| 48 | hostRewriteFunc func(net.Conn, string) (net.Conn, error) |
| 49 | successHookFunc func(net.Conn, map[string]string) error |
| 50 | failHookFunc func(net.Conn) |
| 51 | ) |
| 52 |
| 53 | // Muxer is a functional component used for https and tcpmux proxies. |
| 54 | // It accepts connections and extracts vhost information from the beginning of the connection data. |
| 55 | // It then routes the connection to its appropriate listener. |
| 56 | type Muxer struct { |
| 57 | listener net.Listener |
| 58 | timeout time.Duration |
| 59 |
| 60 | vhostFunc muxFunc |
| 61 | checkAuth authFunc |
| 62 | successHook successHookFunc |
| 63 | failHook failHookFunc |
| 64 | rewriteHost hostRewriteFunc |
| 65 | registryRouter *Routers |
| 66 | } |
| 67 |
| 68 | func NewMuxer( |
| 69 | listener net.Listener, |
| 70 | vhostFunc muxFunc, |
| 71 | timeout time.Duration, |
| 72 | ) (mux *Muxer, err error) { |
| 73 | mux = &Muxer{ |
| 74 | listener: listener, |
| 75 | timeout: timeout, |
| 76 | vhostFunc: vhostFunc, |
| 77 | registryRouter: NewRouters(), |
| 78 | } |
| 79 | go mux.run() |
| 80 | return mux, nil |
| 81 | } |
| 82 |
| 83 | func (v *Muxer) SetCheckAuthFunc(f authFunc) *Muxer { |
| 84 | v.checkAuth = f |
| 85 | return v |
| 86 | } |
| 87 |
| 88 | func (v *Muxer) SetSuccessHookFunc(f successHookFunc) *Muxer { |
| 89 | v.successHook = f |
| 90 | return v |
| 91 | } |
| 92 |
| 93 | func (v *Muxer) SetFailHookFunc(f failHookFunc) *Muxer { |
| 94 | v.failHook = f |
| 95 | return v |
| 96 | } |
| 97 |
| 98 | func (v *Muxer) SetRewriteHostFunc(f hostRewriteFunc) *Muxer { |
| 99 | v.rewriteHost = f |
| 100 | return v |
| 101 | } |
| 102 |
| 103 | func (v *Muxer) Close() error { |
| 104 | return v.listener.Close() |
| 105 | } |
| 106 |
| 107 | type ChooseEndpointFunc func() (string, error) |
| 108 |
| 109 | type CreateConnFunc func(remoteAddr string) (net.Conn, error) |
| 110 |
| 111 | type CreateConnByEndpointFunc func(endpoint, remoteAddr string) (net.Conn, error) |
| 112 |
| 113 | // RouteConfig is the params used to match HTTP requests |
| 114 | type RouteConfig struct { |
| 115 | Domain string |
| 116 | Location string |
| 117 | RewriteHost string |
| 118 | Username string |
| 119 | Password string |
| 120 | Headers map[string]string |
| 121 | ResponseHeaders map[string]string |
| 122 | RouteByHTTPUser string |
| 123 |
| 124 | CreateConnFn CreateConnFunc |
| 125 | ChooseEndpointFn ChooseEndpointFunc |
| 126 | CreateConnByEndpointFn CreateConnByEndpointFunc |
| 127 | } |
| 128 |
| 129 | // listen for a new domain name, if rewriteHost is not empty and rewriteHost func is not nil, |
| 130 | // then rewrite the host header to rewriteHost |
| 131 | func (v *Muxer) Listen(ctx context.Context, cfg *RouteConfig) (l *Listener, err error) { |
| 132 | l = &Listener{ |
| 133 | name: cfg.Domain, |
| 134 | location: cfg.Location, |
| 135 | routeByHTTPUser: cfg.RouteByHTTPUser, |
| 136 | rewriteHost: cfg.RewriteHost, |
| 137 | username: cfg.Username, |
| 138 | password: cfg.Password, |
| 139 | mux: v, |
| 140 | accept: make(chan net.Conn), |
| 141 | ctx: ctx, |
| 142 | } |
| 143 | err = v.registryRouter.Add(cfg.Domain, cfg.Location, cfg.RouteByHTTPUser, l) |
| 144 | if err != nil { |
| 145 | return |
| 146 | } |
| 147 | return l, nil |
| 148 | } |
| 149 |
| 150 | func (v *Muxer) getListener(name, path, httpUser string) (*Listener, bool) { |
| 151 | vr, ok := v.registryRouter.getByRoute(name, path, httpUser) |
| 152 | if ok { |
| 153 | return vr.payload.(*Listener), true |
| 154 | } |
| 155 | return nil, false |
| 156 | } |
| 157 |
| 158 | func (v *Muxer) run() { |
| 159 | for { |
| 160 | conn, err := v.listener.Accept() |
| 161 | if err != nil { |
| 162 | return |
| 163 | } |
| 164 | go v.handle(conn) |
| 165 | } |
| 166 | } |
| 167 |
| 168 | func (v *Muxer) handle(c net.Conn) { |
| 169 | if err := c.SetDeadline(time.Now().Add(v.timeout)); err != nil { |
| 170 | _ = c.Close() |
| 171 | return |
| 172 | } |
| 173 |
| 174 | sConn, reqInfoMap, err := v.vhostFunc(c) |
| 175 | if err != nil { |
| 176 | log.Debugf("get hostname from http/https request error: %v", err) |
| 177 | _ = c.Close() |
| 178 | return |
| 179 | } |
| 180 |
| 181 | name := strings.ToLower(reqInfoMap["Host"]) |
| 182 | path := strings.ToLower(reqInfoMap["Path"]) |
| 183 | httpUser := reqInfoMap["HTTPUser"] |
| 184 | l, ok := v.getListener(name, path, httpUser) |
| 185 | if !ok { |
| 186 | log.Debugf("http request for host [%s] path [%s] httpUser [%s] not found", name, path, httpUser) |
| 187 | v.failHook(sConn) |
| 188 | return |
| 189 | } |
| 190 |
| 191 | xl := xlog.FromContextSafe(l.ctx) |
| 192 | if v.successHook != nil { |
| 193 | if err := v.successHook(c, reqInfoMap); err != nil { |
| 194 | xl.Infof("success func failure on vhost connection: %v", err) |
| 195 | _ = c.Close() |
| 196 | return |
| 197 | } |
| 198 | } |
| 199 |
| 200 | // if checkAuth func is exist and username/password is set |
| 201 | // then verify user access |
| 202 | if l.mux.checkAuth != nil && l.username != "" { |
| 203 | ok, err := l.mux.checkAuth(c, l.username, l.password, reqInfoMap) |
| 204 | if !ok || err != nil { |
| 205 | xl.Debugf("auth failed for user: %s", l.username) |
| 206 | _ = c.Close() |
| 207 | return |
| 208 | } |
| 209 | } |
| 210 |
| 211 | if err = sConn.SetDeadline(time.Time{}); err != nil { |
| 212 | _ = c.Close() |
| 213 | return |
| 214 | } |
| 215 | c = sConn |
| 216 |
| 217 | xl.Debugf("new request host [%s] path [%s] httpUser [%s]", name, path, httpUser) |
| 218 | err = errors.PanicToError(func() { |
| 219 | l.accept <- c |
| 220 | }) |
| 221 | if err != nil { |
| 222 | xl.Warnf("listener is already closed, ignore this request") |
| 223 | } |
| 224 | } |
| 225 |
| 226 | type Listener struct { |
| 227 | name string |
| 228 | location string |
| 229 | routeByHTTPUser string |
| 230 | rewriteHost string |
| 231 | username string |
| 232 | password string |
| 233 | mux *Muxer // for closing Muxer |
| 234 | accept chan net.Conn |
| 235 | ctx context.Context |
| 236 | } |
| 237 |
| 238 | func (l *Listener) Accept() (net.Conn, error) { |
| 239 | xl := xlog.FromContextSafe(l.ctx) |
| 240 | conn, ok := <-l.accept |
| 241 | if !ok { |
| 242 | return nil, fmt.Errorf("listener closed") |
| 243 | } |
| 244 |
| 245 | // if rewriteHost func is exist |
| 246 | // rewrite http requests with a modified host header |
| 247 | // if l.rewriteHost is empty, nothing to do |
| 248 | if l.mux.rewriteHost != nil { |
| 249 | sConn, err := l.mux.rewriteHost(conn, l.rewriteHost) |
| 250 | if err != nil { |
| 251 | xl.Warnf("host header rewrite failed: %v", err) |
| 252 | return nil, fmt.Errorf("host header rewrite failed") |
| 253 | } |
| 254 | xl.Debugf("rewrite host to [%s] success", l.rewriteHost) |
| 255 | conn = sConn |
| 256 | } |
| 257 | return netpkg.NewContextConn(l.ctx, conn), nil |
| 258 | } |
| 259 |
| 260 | func (l *Listener) Close() error { |
| 261 | l.mux.registryRouter.Del(l.name, l.location, l.routeByHTTPUser) |
| 262 | close(l.accept) |
| 263 | return nil |
| 264 | } |
| 265 |
| 266 | func (l *Listener) Name() string { |
| 267 | return l.name |
| 268 | } |
| 269 |
| 270 | func (l *Listener) Addr() net.Addr { |
| 271 | return (*net.TCPAddr)(nil) |
| 272 | } |