| // |
| 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 server |
| 16 |
| 17 | import ( |
| 18 | "context" |
| 19 | "fmt" |
| 20 | "runtime/debug" |
| 21 | "sync" |
| 22 | "sync/atomic" |
| 23 | "time" |
| 24 |
| 25 | "github.com/samber/lo" |
| 26 |
| 27 | "github.com/fatedier/frp/pkg/auth" |
| 28 | "github.com/fatedier/frp/pkg/config" |
| 29 | v1 "github.com/fatedier/frp/pkg/config/v1" |
| 30 | pkgerr "github.com/fatedier/frp/pkg/errors" |
| 31 | "github.com/fatedier/frp/pkg/msg" |
| 32 | plugin "github.com/fatedier/frp/pkg/plugin/server" |
| 33 | "github.com/fatedier/frp/pkg/transport" |
| 34 | "github.com/fatedier/frp/pkg/util/util" |
| 35 | "github.com/fatedier/frp/pkg/util/wait" |
| 36 | "github.com/fatedier/frp/pkg/util/xlog" |
| 37 | "github.com/fatedier/frp/server/controller" |
| 38 | "github.com/fatedier/frp/server/metrics" |
| 39 | "github.com/fatedier/frp/server/proxy" |
| 40 | "github.com/fatedier/frp/server/registry" |
| 41 | ) |
| 42 |
| 43 | type ControlManager struct { |
| 44 | // controls indexed by run id |
| 45 | ctlsByRunID map[string]*Control |
| 46 |
| 47 | mu sync.RWMutex |
| 48 | } |
| 49 |
| 50 | func NewControlManager() *ControlManager { |
| 51 | return &ControlManager{ |
| 52 | ctlsByRunID: make(map[string]*Control), |
| 53 | } |
| 54 | } |
| 55 |
| 56 | func (cm *ControlManager) Add(runID string, ctl *Control) (old *Control) { |
| 57 | cm.mu.Lock() |
| 58 | defer cm.mu.Unlock() |
| 59 |
| 60 | var ok bool |
| 61 | old, ok = cm.ctlsByRunID[runID] |
| 62 | if ok { |
| 63 | old.Replaced(ctl) |
| 64 | } |
| 65 | cm.ctlsByRunID[runID] = ctl |
| 66 | return |
| 67 | } |
| 68 |
| 69 | // we should make sure if it's the same control to prevent delete a new one |
| 70 | func (cm *ControlManager) Del(runID string, ctl *Control) { |
| 71 | cm.mu.Lock() |
| 72 | defer cm.mu.Unlock() |
| 73 | if c, ok := cm.ctlsByRunID[runID]; ok && c == ctl { |
| 74 | delete(cm.ctlsByRunID, runID) |
| 75 | } |
| 76 | } |
| 77 |
| 78 | func (cm *ControlManager) GetByID(runID string) (ctl *Control, ok bool) { |
| 79 | cm.mu.RLock() |
| 80 | defer cm.mu.RUnlock() |
| 81 | ctl, ok = cm.ctlsByRunID[runID] |
| 82 | return |
| 83 | } |
| 84 |
| 85 | func (cm *ControlManager) Close() error { |
| 86 | cm.mu.Lock() |
| 87 | defer cm.mu.Unlock() |
| 88 | for _, ctl := range cm.ctlsByRunID { |
| 89 | ctl.Close() |
| 90 | } |
| 91 | cm.ctlsByRunID = make(map[string]*Control) |
| 92 | return nil |
| 93 | } |
| 94 |
| 95 | // SessionContext encapsulates the input parameters for creating a new Control. |
| 96 | type SessionContext struct { |
| 97 | // all resource managers and controllers |
| 98 | RC *controller.ResourceController |
| 99 | // proxy manager |
| 100 | PxyManager *proxy.Manager |
| 101 | // plugin manager |
| 102 | PluginManager *plugin.Manager |
| 103 | // verifies authentication based on selected method |
| 104 | AuthVerifier auth.Verifier |
| 105 | // key used for connection encryption |
| 106 | EncryptionKey []byte |
| 107 | // control connection |
| 108 | Conn *msg.Conn |
| 109 | // login message |
| 110 | LoginMsg *msg.Login |
| 111 | // server configuration |
| 112 | ServerCfg *v1.ServerConfig |
| 113 | // client registry |
| 114 | ClientRegistry *registry.ClientRegistry |
| 115 | // negotiated wire protocol for this client session |
| 116 | WireProtocol string |
| 117 | } |
| 118 |
| 119 | type Control struct { |
| 120 | // session context |
| 121 | sessionCtx *SessionContext |
| 122 |
| 123 | // other components can use this to communicate with client |
| 124 | msgTransporter transport.MessageTransporter |
| 125 |
| 126 | // msgDispatcher is a wrapper for control connection. |
| 127 | // It provides a channel for sending messages, and you can register handlers to process messages based on their respective types. |
| 128 | msgDispatcher *msg.Dispatcher |
| 129 |
| 130 | // work connections |
| 131 | workConnCh chan *proxy.WorkConn |
| 132 |
| 133 | // proxies in one client |
| 134 | proxies map[string]proxy.Proxy |
| 135 |
| 136 | // pool count |
| 137 | poolCount int |
| 138 |
| 139 | // ports used, for limitations |
| 140 | portsUsedNum int |
| 141 |
| 142 | // last time got the Ping message |
| 143 | lastPing atomic.Value |
| 144 |
| 145 | // A new run id will be generated when a new client login. |
| 146 | // If run id got from login message has same run id, it means it's the same client, so we can |
| 147 | // replace old controller instantly. |
| 148 | runID string |
| 149 |
| 150 | mu sync.RWMutex |
| 151 |
| 152 | xl *xlog.Logger |
| 153 | ctx context.Context |
| 154 | doneCh chan struct{} |
| 155 | } |
| 156 |
| 157 | func NewControl(ctx context.Context, sessionCtx *SessionContext) (*Control, error) { |
| 158 | poolCount := min(sessionCtx.LoginMsg.PoolCount, int(sessionCtx.ServerCfg.Transport.MaxPoolCount)) |
| 159 | ctl := &Control{ |
| 160 | sessionCtx: sessionCtx, |
| 161 | workConnCh: make(chan *proxy.WorkConn, poolCount+10), |
| 162 | proxies: make(map[string]proxy.Proxy), |
| 163 | poolCount: poolCount, |
| 164 | portsUsedNum: 0, |
| 165 | runID: sessionCtx.LoginMsg.RunID, |
| 166 | xl: xlog.FromContextSafe(ctx), |
| 167 | ctx: ctx, |
| 168 | doneCh: make(chan struct{}), |
| 169 | } |
| 170 | ctl.lastPing.Store(time.Now()) |
| 171 |
| 172 | ctl.msgDispatcher = msg.NewDispatcher(sessionCtx.Conn) |
| 173 | ctl.registerMsgHandlers() |
| 174 | ctl.msgTransporter = transport.NewMessageTransporter(ctl.msgDispatcher) |
| 175 | return ctl, nil |
| 176 | } |
| 177 |
| 178 | // Start starts the control session workers after login succeeds. |
| 179 | func (ctl *Control) Start() { |
| 180 | go func() { |
| 181 | for i := 0; i < ctl.poolCount; i++ { |
| 182 | // ignore error here, that means that this control is closed |
| 183 | _ = ctl.msgDispatcher.Send(&msg.ReqWorkConn{}) |
| 184 | } |
| 185 | }() |
| 186 | go ctl.worker() |
| 187 | } |
| 188 |
| 189 | func (ctl *Control) Close() error { |
| 190 | ctl.sessionCtx.Conn.Close() |
| 191 | return nil |
| 192 | } |
| 193 |
| 194 | func (ctl *Control) Replaced(newCtl *Control) { |
| 195 | xl := ctl.xl |
| 196 | xl.Infof("replaced by client [%s]", newCtl.runID) |
| 197 | ctl.runID = "" |
| 198 | ctl.sessionCtx.Conn.Close() |
| 199 | } |
| 200 |
| 201 | func (ctl *Control) RegisterWorkConn(conn *proxy.WorkConn) error { |
| 202 | xl := ctl.xl |
| 203 | defer func() { |
| 204 | if err := recover(); err != nil { |
| 205 | xl.Errorf("panic error: %v", err) |
| 206 | xl.Errorf(string(debug.Stack())) |
| 207 | } |
| 208 | }() |
| 209 |
| 210 | select { |
| 211 | case ctl.workConnCh <- conn: |
| 212 | xl.Debugf("new work connection registered") |
| 213 | return nil |
| 214 | default: |
| 215 | xl.Debugf("work connection pool is full, discarding") |
| 216 | return fmt.Errorf("work connection pool is full, discarding") |
| 217 | } |
| 218 | } |
| 219 |
| 220 | // When frps get one user connection, we get one work connection from the pool and return it. |
| 221 | // If no workConn available in the pool, send message to frpc to get one or more |
| 222 | // and wait until it is available. |
| 223 | // return an error if wait timeout |
| 224 | func (ctl *Control) GetWorkConn() (workConn *proxy.WorkConn, err error) { |
| 225 | xl := ctl.xl |
| 226 | defer func() { |
| 227 | if err := recover(); err != nil { |
| 228 | xl.Errorf("panic error: %v", err) |
| 229 | xl.Errorf(string(debug.Stack())) |
| 230 | } |
| 231 | }() |
| 232 |
| 233 | var ok bool |
| 234 | // get a work connection from the pool |
| 235 | select { |
| 236 | case workConn, ok = <-ctl.workConnCh: |
| 237 | if !ok { |
| 238 | err = pkgerr.ErrCtlClosed |
| 239 | return |
| 240 | } |
| 241 | xl.Debugf("get work connection from pool") |
| 242 | default: |
| 243 | // no work connections available in the poll, send message to frpc to get more |
| 244 | if err := ctl.msgDispatcher.Send(&msg.ReqWorkConn{}); err != nil { |
| 245 | return nil, fmt.Errorf("control is already closed") |
| 246 | } |
| 247 |
| 248 | select { |
| 249 | case workConn, ok = <-ctl.workConnCh: |
| 250 | if !ok { |
| 251 | err = pkgerr.ErrCtlClosed |
| 252 | xl.Warnf("no work connections available, %v", err) |
| 253 | return |
| 254 | } |
| 255 |
| 256 | case <-time.After(time.Duration(ctl.sessionCtx.ServerCfg.UserConnTimeout) * time.Second): |
| 257 | err = fmt.Errorf("timeout trying to get work connection") |
| 258 | xl.Warnf("%v", err) |
| 259 | return |
| 260 | } |
| 261 | } |
| 262 |
| 263 | // When we get a work connection from pool, replace it with a new one. |
| 264 | _ = ctl.msgDispatcher.Send(&msg.ReqWorkConn{}) |
| 265 | return |
| 266 | } |
| 267 |
| 268 | func (ctl *Control) heartbeatWorker() { |
| 269 | if ctl.sessionCtx.ServerCfg.Transport.HeartbeatTimeout <= 0 { |
| 270 | return |
| 271 | } |
| 272 |
| 273 | xl := ctl.xl |
| 274 | go wait.Until(func() { |
| 275 | if time.Since(ctl.lastPing.Load().(time.Time)) > time.Duration(ctl.sessionCtx.ServerCfg.Transport.HeartbeatTimeout)*time.Second { |
| 276 | xl.Warnf("heartbeat timeout") |
| 277 | ctl.sessionCtx.Conn.Close() |
| 278 | return |
| 279 | } |
| 280 | }, time.Second, ctl.doneCh) |
| 281 | } |
| 282 |
| 283 | // block until Control closed |
| 284 | func (ctl *Control) WaitClosed() { |
| 285 | <-ctl.doneCh |
| 286 | } |
| 287 |
| 288 | func (ctl *Control) loginUserInfo() plugin.UserInfo { |
| 289 | return plugin.UserInfo{ |
| 290 | User: ctl.sessionCtx.LoginMsg.User, |
| 291 | Metas: ctl.sessionCtx.LoginMsg.Metas, |
| 292 | RunID: ctl.sessionCtx.LoginMsg.RunID, |
| 293 | } |
| 294 | } |
| 295 |
| 296 | func (ctl *Control) closeProxy(pxy proxy.Proxy) { |
| 297 | pxy.Close() |
| 298 | ctl.sessionCtx.PxyManager.Del(pxy.GetName()) |
| 299 | metrics.Server.CloseProxy(pxy.GetName(), pxy.GetConfigurer().GetBaseConfig().Type) |
| 300 |
| 301 | notifyContent := &plugin.CloseProxyContent{ |
| 302 | User: ctl.loginUserInfo(), |
| 303 | CloseProxy: msg.CloseProxy{ |
| 304 | ProxyName: pxy.GetName(), |
| 305 | }, |
| 306 | } |
| 307 | go func() { |
| 308 | _ = ctl.sessionCtx.PluginManager.CloseProxy(notifyContent) |
| 309 | }() |
| 310 | } |
| 311 |
| 312 | func (ctl *Control) worker() { |
| 313 | xl := ctl.xl |
| 314 |
| 315 | go ctl.heartbeatWorker() |
| 316 | go ctl.msgDispatcher.Run() |
| 317 |
| 318 | <-ctl.msgDispatcher.Done() |
| 319 | ctl.sessionCtx.Conn.Close() |
| 320 |
| 321 | ctl.mu.Lock() |
| 322 | close(ctl.workConnCh) |
| 323 | for workConn := range ctl.workConnCh { |
| 324 | workConn.Close() |
| 325 | } |
| 326 | proxies := ctl.proxies |
| 327 | ctl.proxies = make(map[string]proxy.Proxy) |
| 328 | ctl.mu.Unlock() |
| 329 |
| 330 | for _, pxy := range proxies { |
| 331 | ctl.closeProxy(pxy) |
| 332 | } |
| 333 |
| 334 | metrics.Server.CloseClient() |
| 335 | ctl.sessionCtx.ClientRegistry.MarkOfflineByRunID(ctl.runID) |
| 336 | xl.Infof("client exit success") |
| 337 | close(ctl.doneCh) |
| 338 | } |
| 339 |
| 340 | func (ctl *Control) registerMsgHandlers() { |
| 341 | ctl.msgDispatcher.RegisterHandler(&msg.NewProxy{}, ctl.handleNewProxy) |
| 342 | ctl.msgDispatcher.RegisterHandler(&msg.Ping{}, ctl.handlePing) |
| 343 | ctl.msgDispatcher.RegisterHandler(&msg.NatHoleVisitor{}, msg.AsyncHandler(ctl.handleNatHoleVisitor)) |
| 344 | ctl.msgDispatcher.RegisterHandler(&msg.NatHoleClient{}, msg.AsyncHandler(ctl.handleNatHoleClient)) |
| 345 | ctl.msgDispatcher.RegisterHandler(&msg.NatHoleReport{}, msg.AsyncHandler(ctl.handleNatHoleReport)) |
| 346 | ctl.msgDispatcher.RegisterHandler(&msg.CloseProxy{}, ctl.handleCloseProxy) |
| 347 | } |
| 348 |
| 349 | func (ctl *Control) handleNewProxy(m msg.Message) { |
| 350 | xl := ctl.xl |
| 351 | inMsg := m.(*msg.NewProxy) |
| 352 |
| 353 | content := &plugin.NewProxyContent{ |
| 354 | User: ctl.loginUserInfo(), |
| 355 | NewProxy: *inMsg, |
| 356 | } |
| 357 | var remoteAddr string |
| 358 | retContent, err := ctl.sessionCtx.PluginManager.NewProxy(content) |
| 359 | if err == nil { |
| 360 | inMsg = &retContent.NewProxy |
| 361 | remoteAddr, err = ctl.RegisterProxy(inMsg) |
| 362 | } |
| 363 |
| 364 | // register proxy in this control |
| 365 | resp := &msg.NewProxyResp{ |
| 366 | ProxyName: inMsg.ProxyName, |
| 367 | } |
| 368 | if err != nil { |
| 369 | xl.Warnf("new proxy [%s] type [%s] error: %v", inMsg.ProxyName, inMsg.ProxyType, err) |
| 370 | resp.Error = util.GenerateResponseErrorString(fmt.Sprintf("new proxy [%s] error", inMsg.ProxyName), |
| 371 | err, lo.FromPtr(ctl.sessionCtx.ServerCfg.DetailedErrorsToClient)) |
| 372 | } else { |
| 373 | resp.RemoteAddr = remoteAddr |
| 374 | xl.Infof("new proxy [%s] type [%s] success", inMsg.ProxyName, inMsg.ProxyType) |
| 375 | clientID := ctl.sessionCtx.LoginMsg.ClientID |
| 376 | if clientID == "" { |
| 377 | clientID = ctl.sessionCtx.LoginMsg.RunID |
| 378 | } |
| 379 | metrics.Server.NewProxy(inMsg.ProxyName, inMsg.ProxyType, ctl.sessionCtx.LoginMsg.User, clientID) |
| 380 | } |
| 381 | _ = ctl.msgDispatcher.Send(resp) |
| 382 | } |
| 383 |
| 384 | func (ctl *Control) handlePing(m msg.Message) { |
| 385 | xl := ctl.xl |
| 386 | inMsg := m.(*msg.Ping) |
| 387 |
| 388 | content := &plugin.PingContent{ |
| 389 | User: ctl.loginUserInfo(), |
| 390 | Ping: *inMsg, |
| 391 | } |
| 392 | retContent, err := ctl.sessionCtx.PluginManager.Ping(content) |
| 393 | if err == nil { |
| 394 | inMsg = &retContent.Ping |
| 395 | err = ctl.sessionCtx.AuthVerifier.VerifyPing(inMsg) |
| 396 | } |
| 397 | if err != nil { |
| 398 | xl.Warnf("received invalid ping: %v", err) |
| 399 | _ = ctl.msgDispatcher.Send(&msg.Pong{ |
| 400 | Error: util.GenerateResponseErrorString("invalid ping", err, lo.FromPtr(ctl.sessionCtx.ServerCfg.DetailedErrorsToClient)), |
| 401 | }) |
| 402 | return |
| 403 | } |
| 404 | ctl.lastPing.Store(time.Now()) |
| 405 | xl.Debugf("receive heartbeat") |
| 406 | _ = ctl.msgDispatcher.Send(&msg.Pong{}) |
| 407 | } |
| 408 |
| 409 | func (ctl *Control) handleNatHoleVisitor(m msg.Message) { |
| 410 | inMsg := m.(*msg.NatHoleVisitor) |
| 411 | ctl.sessionCtx.RC.NatHoleController.HandleVisitor(inMsg, ctl.msgTransporter, ctl.sessionCtx.LoginMsg.User) |
| 412 | } |
| 413 |
| 414 | func (ctl *Control) handleNatHoleClient(m msg.Message) { |
| 415 | inMsg := m.(*msg.NatHoleClient) |
| 416 | ctl.sessionCtx.RC.NatHoleController.HandleClient(inMsg, ctl.msgTransporter) |
| 417 | } |
| 418 |
| 419 | func (ctl *Control) handleNatHoleReport(m msg.Message) { |
| 420 | inMsg := m.(*msg.NatHoleReport) |
| 421 | ctl.sessionCtx.RC.NatHoleController.HandleReport(inMsg) |
| 422 | } |
| 423 |
| 424 | func (ctl *Control) handleCloseProxy(m msg.Message) { |
| 425 | xl := ctl.xl |
| 426 | inMsg := m.(*msg.CloseProxy) |
| 427 | _ = ctl.CloseProxy(inMsg) |
| 428 | xl.Infof("close proxy [%s] success", inMsg.ProxyName) |
| 429 | } |
| 430 |
| 431 | func (ctl *Control) RegisterProxy(pxyMsg *msg.NewProxy) (remoteAddr string, err error) { |
| 432 | var pxyConf v1.ProxyConfigurer |
| 433 | // Load configures from NewProxy message and validate. |
| 434 | pxyConf, err = config.NewProxyConfigurerFromMsg(pxyMsg, ctl.sessionCtx.ServerCfg) |
| 435 | if err != nil { |
| 436 | return |
| 437 | } |
| 438 |
| 439 | // User info |
| 440 | userInfo := plugin.UserInfo{ |
| 441 | User: ctl.sessionCtx.LoginMsg.User, |
| 442 | Metas: ctl.sessionCtx.LoginMsg.Metas, |
| 443 | RunID: ctl.runID, |
| 444 | } |
| 445 |
| 446 | // NewProxy will return an interface Proxy. |
| 447 | // In fact, it creates different proxies based on the proxy type. We just call run() here. |
| 448 | pxy, err := proxy.NewProxy(ctl.ctx, &proxy.Options{ |
| 449 | UserInfo: userInfo, |
| 450 | LoginMsg: ctl.sessionCtx.LoginMsg, |
| 451 | PoolCount: ctl.poolCount, |
| 452 | ResourceController: ctl.sessionCtx.RC, |
| 453 | GetWorkConnFn: ctl.GetWorkConn, |
| 454 | Configurer: pxyConf, |
| 455 | ServerCfg: ctl.sessionCtx.ServerCfg, |
| 456 | EncryptionKey: ctl.sessionCtx.EncryptionKey, |
| 457 | WireProtocol: ctl.sessionCtx.WireProtocol, |
| 458 | }) |
| 459 | if err != nil { |
| 460 | return remoteAddr, err |
| 461 | } |
| 462 |
| 463 | // Check ports used number in each client |
| 464 | if ctl.sessionCtx.ServerCfg.MaxPortsPerClient > 0 { |
| 465 | ctl.mu.Lock() |
| 466 | if ctl.portsUsedNum+pxy.GetUsedPortsNum() > int(ctl.sessionCtx.ServerCfg.MaxPortsPerClient) { |
| 467 | ctl.mu.Unlock() |
| 468 | err = fmt.Errorf("exceed the max_ports_per_client") |
| 469 | return |
| 470 | } |
| 471 | ctl.portsUsedNum += pxy.GetUsedPortsNum() |
| 472 | ctl.mu.Unlock() |
| 473 |
| 474 | defer func() { |
| 475 | if err != nil { |
| 476 | ctl.mu.Lock() |
| 477 | ctl.portsUsedNum -= pxy.GetUsedPortsNum() |
| 478 | ctl.mu.Unlock() |
| 479 | } |
| 480 | }() |
| 481 | } |
| 482 |
| 483 | if ctl.sessionCtx.PxyManager.Exist(pxyMsg.ProxyName) { |
| 484 | err = fmt.Errorf("proxy [%s] already exists", pxyMsg.ProxyName) |
| 485 | return |
| 486 | } |
| 487 |
| 488 | remoteAddr, err = pxy.Run() |
| 489 | if err != nil { |
| 490 | return |
| 491 | } |
| 492 | defer func() { |
| 493 | if err != nil { |
| 494 | pxy.Close() |
| 495 | } |
| 496 | }() |
| 497 |
| 498 | err = ctl.sessionCtx.PxyManager.Add(pxyMsg.ProxyName, pxy) |
| 499 | if err != nil { |
| 500 | return |
| 501 | } |
| 502 |
| 503 | ctl.mu.Lock() |
| 504 | ctl.proxies[pxy.GetName()] = pxy |
| 505 | ctl.mu.Unlock() |
| 506 | return |
| 507 | } |
| 508 |
| 509 | func (ctl *Control) CloseProxy(closeMsg *msg.CloseProxy) (err error) { |
| 510 | ctl.mu.Lock() |
| 511 | pxy, ok := ctl.proxies[closeMsg.ProxyName] |
| 512 | if !ok { |
| 513 | ctl.mu.Unlock() |
| 514 | return |
| 515 | } |
| 516 |
| 517 | if ctl.sessionCtx.ServerCfg.MaxPortsPerClient > 0 { |
| 518 | ctl.portsUsedNum -= pxy.GetUsedPortsNum() |
| 519 | } |
| 520 | delete(ctl.proxies, closeMsg.ProxyName) |
| 521 | ctl.mu.Unlock() |
| 522 |
| 523 | ctl.closeProxy(pxy) |
| 524 | return |
| 525 | } |