| // |
| 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 client |
| 16 |
| 17 | import ( |
| 18 | "context" |
| 19 | "errors" |
| 20 | "fmt" |
| 21 | "net" |
| 22 | "net/http" |
| 23 | "os" |
| 24 | "sync" |
| 25 | "time" |
| 26 |
| 27 | "github.com/fatedier/golib/crypto" |
| 28 | "github.com/samber/lo" |
| 29 |
| 30 | "github.com/fatedier/frp/client/proxy" |
| 31 | "github.com/fatedier/frp/pkg/auth" |
| 32 | "github.com/fatedier/frp/pkg/config" |
| 33 | "github.com/fatedier/frp/pkg/config/source" |
| 34 | v1 "github.com/fatedier/frp/pkg/config/v1" |
| 35 | "github.com/fatedier/frp/pkg/msg" |
| 36 | "github.com/fatedier/frp/pkg/policy/security" |
| 37 | httppkg "github.com/fatedier/frp/pkg/util/http" |
| 38 | "github.com/fatedier/frp/pkg/util/log" |
| 39 | netpkg "github.com/fatedier/frp/pkg/util/net" |
| 40 | "github.com/fatedier/frp/pkg/util/wait" |
| 41 | "github.com/fatedier/frp/pkg/util/xlog" |
| 42 | "github.com/fatedier/frp/pkg/vnet" |
| 43 | ) |
| 44 |
| 45 | func init() { |
| 46 | crypto.DefaultSalt = "frp" |
| 47 | // Disable quic-go's receive buffer warning. |
| 48 | os.Setenv("QUIC_GO_DISABLE_RECEIVE_BUFFER_WARNING", "true") |
| 49 | // Disable quic-go's ECN support by default. It may cause issues on certain operating systems. |
| 50 | if os.Getenv("QUIC_GO_DISABLE_ECN") == "" { |
| 51 | os.Setenv("QUIC_GO_DISABLE_ECN", "true") |
| 52 | } |
| 53 | } |
| 54 |
| 55 | type cancelErr struct { |
| 56 | Err error |
| 57 | } |
| 58 |
| 59 | func (e cancelErr) Error() string { |
| 60 | return e.Err.Error() |
| 61 | } |
| 62 |
| 63 | // ServiceOptions contains options for creating a new client service. |
| 64 | type ServiceOptions struct { |
| 65 | Common *v1.ClientCommonConfig |
| 66 |
| 67 | // ConfigSourceAggregator manages internal config and optional store sources. |
| 68 | // It is required for creating a Service. |
| 69 | ConfigSourceAggregator *source.Aggregator |
| 70 |
| 71 | UnsafeFeatures *security.UnsafeFeatures |
| 72 |
| 73 | // ConfigFilePath is the path to the configuration file used to initialize. |
| 74 | // If it is empty, it means that the configuration file is not used for initialization. |
| 75 | // It may be initialized using command line parameters or called directly. |
| 76 | ConfigFilePath string |
| 77 |
| 78 | // ClientSpec is the client specification that control the client behavior. |
| 79 | ClientSpec *msg.ClientSpec |
| 80 |
| 81 | // ConnectorCreator is a function that creates a new connector to make connections to the server. |
| 82 | // The Connector shields the underlying connection details, whether it is through TCP or QUIC connection, |
| 83 | // and regardless of whether multiplexing is used. |
| 84 | // |
| 85 | // If it is not set, the default frpc connector will be used. |
| 86 | // By using a custom Connector, it can be used to implement a VirtualClient, which connects to frps |
| 87 | // through a pipe instead of a real physical connection. |
| 88 | ConnectorCreator func(context.Context, *v1.ClientCommonConfig) Connector |
| 89 |
| 90 | // HandleWorkConnCb is a callback function that is called when a new work connection is created. |
| 91 | // |
| 92 | // If it is not set, the default frpc implementation will be used. |
| 93 | HandleWorkConnCb func(*v1.ProxyBaseConfig, net.Conn, *msg.StartWorkConn) bool |
| 94 | } |
| 95 |
| 96 | // setServiceOptionsDefault sets the default values for ServiceOptions. |
| 97 | func setServiceOptionsDefault(options *ServiceOptions) error { |
| 98 | if options.Common != nil { |
| 99 | if err := options.Common.Complete(); err != nil { |
| 100 | return err |
| 101 | } |
| 102 | } |
| 103 | if options.ConnectorCreator == nil { |
| 104 | options.ConnectorCreator = NewConnector |
| 105 | } |
| 106 | return nil |
| 107 | } |
| 108 |
| 109 | // Service is the client service that connects to frps and provides proxy services. |
| 110 | type Service struct { |
| 111 | ctlMu sync.RWMutex |
| 112 | // manager control connection with server |
| 113 | ctl *Control |
| 114 | // Uniq id got from frps, it will be attached to loginMsg. |
| 115 | runID string |
| 116 |
| 117 | // Auth runtime and encryption materials |
| 118 | auth *auth.ClientAuth |
| 119 |
| 120 | // web server for admin UI and apis |
| 121 | webServer *httppkg.Server |
| 122 |
| 123 | vnetController *vnet.Controller |
| 124 |
| 125 | cfgMu sync.RWMutex |
| 126 | // reloadMu serializes reload transactions to keep reloadCommon and applied |
| 127 | // config in sync across concurrent API operations. |
| 128 | reloadMu sync.Mutex |
| 129 | common *v1.ClientCommonConfig |
| 130 | // reloadCommon is used for filtering/defaulting during config-source reloads. |
| 131 | // It can be updated by /api/reload without mutating startup-only common behavior. |
| 132 | reloadCommon *v1.ClientCommonConfig |
| 133 | proxyCfgs []v1.ProxyConfigurer |
| 134 | visitorCfgs []v1.VisitorConfigurer |
| 135 | clientSpec *msg.ClientSpec |
| 136 |
| 137 | // aggregator manages multiple configuration sources. |
| 138 | // When set, the service watches for config changes and reloads automatically. |
| 139 | aggregator *source.Aggregator |
| 140 | configSource *source.ConfigSource |
| 141 | storeSource *source.StoreSource |
| 142 |
| 143 | unsafeFeatures *security.UnsafeFeatures |
| 144 |
| 145 | // The configuration file used to initialize this client, or an empty |
| 146 | // string if no configuration file was used. |
| 147 | configFilePath string |
| 148 |
| 149 | // service context |
| 150 | ctx context.Context |
| 151 | // call cancel to stop service |
| 152 | cancel context.CancelCauseFunc |
| 153 | gracefulShutdownDuration time.Duration |
| 154 |
| 155 | connectorCreator func(context.Context, *v1.ClientCommonConfig) Connector |
| 156 | handleWorkConnCb func(*v1.ProxyBaseConfig, net.Conn, *msg.StartWorkConn) bool |
| 157 | } |
| 158 |
| 159 | func NewService(options ServiceOptions) (*Service, error) { |
| 160 | if err := setServiceOptionsDefault(&options); err != nil { |
| 161 | return nil, err |
| 162 | } |
| 163 |
| 164 | authRuntime, err := auth.BuildClientAuth(&options.Common.Auth) |
| 165 | if err != nil { |
| 166 | return nil, err |
| 167 | } |
| 168 |
| 169 | if options.ConfigSourceAggregator == nil { |
| 170 | return nil, fmt.Errorf("config source aggregator is required") |
| 171 | } |
| 172 |
| 173 | configSource := options.ConfigSourceAggregator.ConfigSource() |
| 174 | storeSource := options.ConfigSourceAggregator.StoreSource() |
| 175 |
| 176 | proxyCfgs, visitorCfgs, loadErr := options.ConfigSourceAggregator.Load() |
| 177 | if loadErr != nil { |
| 178 | return nil, fmt.Errorf("failed to load config from aggregator: %w", loadErr) |
| 179 | } |
| 180 | proxyCfgs, visitorCfgs = config.FilterClientConfigurers(options.Common, proxyCfgs, visitorCfgs) |
| 181 | proxyCfgs = config.CompleteProxyConfigurers(proxyCfgs) |
| 182 | visitorCfgs = config.CompleteVisitorConfigurers(visitorCfgs) |
| 183 |
| 184 | // Create the web server after all fallible steps so its listener is not |
| 185 | // leaked when an earlier error causes NewService to return. |
| 186 | var webServer *httppkg.Server |
| 187 | if options.Common.WebServer.Port > 0 { |
| 188 | ws, err := httppkg.NewServer(options.Common.WebServer) |
| 189 | if err != nil { |
| 190 | return nil, err |
| 191 | } |
| 192 | webServer = ws |
| 193 | } |
| 194 |
| 195 | s := &Service{ |
| 196 | ctx: context.Background(), |
| 197 | auth: authRuntime, |
| 198 | webServer: webServer, |
| 199 | common: options.Common, |
| 200 | reloadCommon: options.Common, |
| 201 | configFilePath: options.ConfigFilePath, |
| 202 | unsafeFeatures: options.UnsafeFeatures, |
| 203 | proxyCfgs: proxyCfgs, |
| 204 | visitorCfgs: visitorCfgs, |
| 205 | clientSpec: options.ClientSpec, |
| 206 | aggregator: options.ConfigSourceAggregator, |
| 207 | configSource: configSource, |
| 208 | storeSource: storeSource, |
| 209 | connectorCreator: options.ConnectorCreator, |
| 210 | handleWorkConnCb: options.HandleWorkConnCb, |
| 211 | } |
| 212 |
| 213 | if webServer != nil { |
| 214 | webServer.RouteRegister(s.registerRouteHandlers) |
| 215 | } |
| 216 | if options.Common.VirtualNet.Address != "" { |
| 217 | s.vnetController = vnet.NewController(options.Common.VirtualNet) |
| 218 | } |
| 219 | return s, nil |
| 220 | } |
| 221 |
| 222 | func (svr *Service) Run(ctx context.Context) error { |
| 223 | ctx, cancel := context.WithCancelCause(ctx) |
| 224 | svr.ctx = xlog.NewContext(ctx, xlog.FromContextSafe(ctx)) |
| 225 | svr.cancel = cancel |
| 226 |
| 227 | // set custom DNSServer |
| 228 | if svr.common.DNSServer != "" { |
| 229 | netpkg.SetDefaultDNSAddress(svr.common.DNSServer) |
| 230 | } |
| 231 |
| 232 | if svr.vnetController != nil { |
| 233 | vnetController := svr.vnetController |
| 234 | if err := svr.vnetController.Init(); err != nil { |
| 235 | log.Errorf("init virtual network controller error: %v", err) |
| 236 | svr.stop() |
| 237 | return err |
| 238 | } |
| 239 | go func() { |
| 240 | log.Infof("virtual network controller start...") |
| 241 | if err := vnetController.Run(); err != nil && !errors.Is(err, net.ErrClosed) { |
| 242 | log.Warnf("virtual network controller exit with error: %v", err) |
| 243 | } |
| 244 | }() |
| 245 | } |
| 246 |
| 247 | if svr.webServer != nil { |
| 248 | webServer := svr.webServer |
| 249 | go func() { |
| 250 | log.Infof("admin server listen on %s", webServer.Address()) |
| 251 | if err := webServer.Run(); err != nil && !errors.Is(err, http.ErrServerClosed) { |
| 252 | log.Warnf("admin server exit with error: %v", err) |
| 253 | } |
| 254 | }() |
| 255 | } |
| 256 |
| 257 | // first login to frps |
| 258 | svr.loopLoginUntilSuccess(10*time.Second, lo.FromPtr(svr.common.LoginFailExit)) |
| 259 | if svr.ctl == nil { |
| 260 | cancelCause := cancelErr{} |
| 261 | _ = errors.As(context.Cause(svr.ctx), &cancelCause) |
| 262 | svr.stop() |
| 263 | return fmt.Errorf("login to the server failed: %v. With loginFailExit enabled, no additional retries will be attempted", cancelCause.Err) |
| 264 | } |
| 265 |
| 266 | go svr.keepControllerWorking() |
| 267 |
| 268 | <-svr.ctx.Done() |
| 269 | svr.stop() |
| 270 | return nil |
| 271 | } |
| 272 |
| 273 | func (svr *Service) keepControllerWorking() { |
| 274 | <-svr.ctl.Done() |
| 275 |
| 276 | // There is a situation where the login is successful but due to certain reasons, |
| 277 | // the control immediately exits. It is necessary to limit the frequency of reconnection in this case. |
| 278 | // The interval for the first three retries in 1 minute will be very short, and then it will increase exponentially. |
| 279 | // The maximum interval is 20 seconds. |
| 280 | wait.BackoffUntil(func() (bool, error) { |
| 281 | // loopLoginUntilSuccess is another layer of loop that will continuously attempt to |
| 282 | // login to the server until successful. |
| 283 | svr.loopLoginUntilSuccess(20*time.Second, false) |
| 284 | if svr.ctl != nil { |
| 285 | <-svr.ctl.Done() |
| 286 | return false, errors.New("control is closed and try another loop") |
| 287 | } |
| 288 | // If the control is nil, it means that the login failed and the service is also closed. |
| 289 | return false, nil |
| 290 | }, wait.NewFastBackoffManager( |
| 291 | wait.FastBackoffOptions{ |
| 292 | Duration: time.Second, |
| 293 | Factor: 2, |
| 294 | Jitter: 0.1, |
| 295 | MaxDuration: 20 * time.Second, |
| 296 | FastRetryCount: 3, |
| 297 | FastRetryDelay: 200 * time.Millisecond, |
| 298 | FastRetryWindow: time.Minute, |
| 299 | FastRetryJitter: 0.5, |
| 300 | }, |
| 301 | ), true, svr.ctx.Done()) |
| 302 | } |
| 303 |
| 304 | func (svr *Service) loopLoginUntilSuccess(maxInterval time.Duration, firstLoginExit bool) { |
| 305 | xl := xlog.FromContextSafe(svr.ctx) |
| 306 |
| 307 | loginFunc := func() (bool, error) { |
| 308 | xl.Infof("try to connect to server...") |
| 309 | dialer := &controlSessionDialer{ |
| 310 | ctx: svr.ctx, |
| 311 | common: svr.common, |
| 312 | auth: svr.auth, |
| 313 | clientSpec: svr.clientSpec, |
| 314 | vnetController: svr.vnetController, |
| 315 | connectorCreator: svr.connectorCreator, |
| 316 | } |
| 317 | sessionCtx, err := dialer.Dial(svr.runID) |
| 318 | if err != nil { |
| 319 | xl.Warnf("connect to server error: %v", err) |
| 320 | if firstLoginExit { |
| 321 | svr.cancel(cancelErr{Err: err}) |
| 322 | } |
| 323 | return false, err |
| 324 | } |
| 325 |
| 326 | svr.runID = sessionCtx.RunID |
| 327 | xl.AddPrefix(xlog.LogPrefix{Name: "runID", Value: svr.runID}) |
| 328 | xl.Infof("login to server success, get run id [%s]", svr.runID) |
| 329 |
| 330 | svr.cfgMu.RLock() |
| 331 | proxyCfgs := svr.proxyCfgs |
| 332 | visitorCfgs := svr.visitorCfgs |
| 333 | svr.cfgMu.RUnlock() |
| 334 |
| 335 | ctl, err := NewControl(svr.ctx, sessionCtx) |
| 336 | if err != nil { |
| 337 | sessionCtx.Conn.Close() |
| 338 | sessionCtx.Connector.Close() |
| 339 | xl.Errorf("new control error: %v", err) |
| 340 | return false, err |
| 341 | } |
| 342 | ctl.SetInWorkConnCallback(svr.handleWorkConnCb) |
| 343 |
| 344 | ctl.Run(proxyCfgs, visitorCfgs) |
| 345 | // close and replace previous control |
| 346 | svr.ctlMu.Lock() |
| 347 | if svr.ctl != nil { |
| 348 | svr.ctl.Close() |
| 349 | } |
| 350 | svr.ctl = ctl |
| 351 | svr.ctlMu.Unlock() |
| 352 | return true, nil |
| 353 | } |
| 354 |
| 355 | // try to reconnect to server until success |
| 356 | wait.BackoffUntil(loginFunc, wait.NewFastBackoffManager( |
| 357 | wait.FastBackoffOptions{ |
| 358 | Duration: time.Second, |
| 359 | Factor: 2, |
| 360 | Jitter: 0.1, |
| 361 | MaxDuration: maxInterval, |
| 362 | }), true, svr.ctx.Done()) |
| 363 | } |
| 364 |
| 365 | func (svr *Service) UpdateAllConfigurer(proxyCfgs []v1.ProxyConfigurer, visitorCfgs []v1.VisitorConfigurer) error { |
| 366 | svr.cfgMu.Lock() |
| 367 | svr.proxyCfgs = proxyCfgs |
| 368 | svr.visitorCfgs = visitorCfgs |
| 369 | svr.cfgMu.Unlock() |
| 370 |
| 371 | svr.ctlMu.RLock() |
| 372 | ctl := svr.ctl |
| 373 | svr.ctlMu.RUnlock() |
| 374 |
| 375 | if ctl != nil { |
| 376 | return svr.ctl.UpdateAllConfigurer(proxyCfgs, visitorCfgs) |
| 377 | } |
| 378 | return nil |
| 379 | } |
| 380 |
| 381 | func (svr *Service) UpdateConfigSource( |
| 382 | common *v1.ClientCommonConfig, |
| 383 | proxyCfgs []v1.ProxyConfigurer, |
| 384 | visitorCfgs []v1.VisitorConfigurer, |
| 385 | ) error { |
| 386 | svr.reloadMu.Lock() |
| 387 | defer svr.reloadMu.Unlock() |
| 388 |
| 389 | cfgSource := svr.configSource |
| 390 | if cfgSource == nil { |
| 391 | return fmt.Errorf("config source is not available") |
| 392 | } |
| 393 |
| 394 | if err := cfgSource.ReplaceAll(proxyCfgs, visitorCfgs); err != nil { |
| 395 | return err |
| 396 | } |
| 397 |
| 398 | // Non-atomic update semantics: source has been updated at this point. |
| 399 | // Even if reload fails below, keep this common config for subsequent reloads. |
| 400 | svr.cfgMu.Lock() |
| 401 | svr.reloadCommon = common |
| 402 | svr.cfgMu.Unlock() |
| 403 |
| 404 | if err := svr.reloadConfigFromSourcesLocked(); err != nil { |
| 405 | return err |
| 406 | } |
| 407 | return nil |
| 408 | } |
| 409 |
| 410 | func (svr *Service) Close() { |
| 411 | svr.GracefulClose(time.Duration(0)) |
| 412 | } |
| 413 |
| 414 | func (svr *Service) GracefulClose(d time.Duration) { |
| 415 | svr.gracefulShutdownDuration = d |
| 416 | svr.cancel(nil) |
| 417 | } |
| 418 |
| 419 | func (svr *Service) stop() { |
| 420 | // Coordinate shutdown with reload/update paths that read source pointers. |
| 421 | svr.reloadMu.Lock() |
| 422 | if svr.aggregator != nil { |
| 423 | svr.aggregator = nil |
| 424 | } |
| 425 | svr.configSource = nil |
| 426 | svr.storeSource = nil |
| 427 | svr.reloadMu.Unlock() |
| 428 |
| 429 | svr.ctlMu.Lock() |
| 430 | defer svr.ctlMu.Unlock() |
| 431 | if svr.ctl != nil { |
| 432 | svr.ctl.GracefulClose(svr.gracefulShutdownDuration) |
| 433 | svr.ctl = nil |
| 434 | } |
| 435 | if svr.webServer != nil { |
| 436 | svr.webServer.Close() |
| 437 | svr.webServer = nil |
| 438 | } |
| 439 | if svr.vnetController != nil { |
| 440 | _ = svr.vnetController.Stop() |
| 441 | svr.vnetController = nil |
| 442 | } |
| 443 | } |
| 444 |
| 445 | func (svr *Service) getProxyStatus(name string) (*proxy.WorkingStatus, bool) { |
| 446 | svr.ctlMu.RLock() |
| 447 | ctl := svr.ctl |
| 448 | svr.ctlMu.RUnlock() |
| 449 |
| 450 | if ctl == nil { |
| 451 | return nil, false |
| 452 | } |
| 453 | return ctl.pm.GetProxyStatus(name) |
| 454 | } |
| 455 |
| 456 | func (svr *Service) getVisitorCfg(name string) (v1.VisitorConfigurer, bool) { |
| 457 | svr.ctlMu.RLock() |
| 458 | ctl := svr.ctl |
| 459 | svr.ctlMu.RUnlock() |
| 460 |
| 461 | if ctl == nil { |
| 462 | return nil, false |
| 463 | } |
| 464 | return ctl.vm.GetVisitorCfg(name) |
| 465 | } |
| 466 |
| 467 | func (svr *Service) StatusExporter() StatusExporter { |
| 468 | return &statusExporterImpl{ |
| 469 | getProxyStatusFunc: svr.getProxyStatus, |
| 470 | } |
| 471 | } |
| 472 |
| 473 | type StatusExporter interface { |
| 474 | GetProxyStatus(name string) (*proxy.WorkingStatus, bool) |
| 475 | } |
| 476 |
| 477 | type statusExporterImpl struct { |
| 478 | getProxyStatusFunc func(name string) (*proxy.WorkingStatus, bool) |
| 479 | } |
| 480 |
| 481 | func (s *statusExporterImpl) GetProxyStatus(name string) (*proxy.WorkingStatus, bool) { |
| 482 | return s.getProxyStatusFunc(name) |
| 483 | } |
| 484 |
| 485 | func (svr *Service) reloadConfigFromSources() error { |
| 486 | svr.reloadMu.Lock() |
| 487 | defer svr.reloadMu.Unlock() |
| 488 | return svr.reloadConfigFromSourcesLocked() |
| 489 | } |
| 490 |
| 491 | func (svr *Service) reloadConfigFromSourcesLocked() error { |
| 492 | aggregator := svr.aggregator |
| 493 | if aggregator == nil { |
| 494 | return errors.New("config aggregator is not initialized") |
| 495 | } |
| 496 |
| 497 | svr.cfgMu.RLock() |
| 498 | reloadCommon := svr.reloadCommon |
| 499 | svr.cfgMu.RUnlock() |
| 500 |
| 501 | proxies, visitors, err := aggregator.Load() |
| 502 | if err != nil { |
| 503 | return fmt.Errorf("reload config from sources failed: %w", err) |
| 504 | } |
| 505 |
| 506 | proxies, visitors = config.FilterClientConfigurers(reloadCommon, proxies, visitors) |
| 507 | proxies = config.CompleteProxyConfigurers(proxies) |
| 508 | visitors = config.CompleteVisitorConfigurers(visitors) |
| 509 |
| 510 | // Atomically replace the entire configuration |
| 511 | if err := svr.UpdateAllConfigurer(proxies, visitors); err != nil { |
| 512 | return err |
| 513 | } |
| 514 | return nil |
| 515 | } |