frp/client/service.go

411 lines
11 KiB
Go
Raw Normal View History

2017-03-08 18:03:47 +00:00
// Copyright 2017 fatedier, fatedier@gmail.com
2016-12-18 17:22:21 +00: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.
2017-03-08 18:03:47 +00:00
package client
2016-12-18 17:22:21 +00:00
import (
2019-10-12 12:13:12 +00:00
"context"
"errors"
2018-11-06 10:35:05 +00:00
"fmt"
2019-10-12 12:13:12 +00:00
"net"
"os"
2018-11-06 10:35:05 +00:00
"runtime"
"sync"
"time"
2022-08-28 17:02:53 +00:00
"github.com/fatedier/golib/crypto"
"github.com/samber/lo"
2022-08-28 17:02:53 +00:00
2023-11-27 07:47:49 +00:00
"github.com/fatedier/frp/client/proxy"
2020-09-23 05:49:14 +00:00
"github.com/fatedier/frp/pkg/auth"
v1 "github.com/fatedier/frp/pkg/config/v1"
2020-09-23 05:49:14 +00:00
"github.com/fatedier/frp/pkg/msg"
2023-11-27 07:47:49 +00:00
httppkg "github.com/fatedier/frp/pkg/util/http"
2020-09-23 05:49:14 +00:00
"github.com/fatedier/frp/pkg/util/log"
2023-11-27 07:47:49 +00:00
netpkg "github.com/fatedier/frp/pkg/util/net"
2020-09-23 05:49:14 +00:00
"github.com/fatedier/frp/pkg/util/version"
"github.com/fatedier/frp/pkg/util/wait"
2020-09-23 05:49:14 +00:00
"github.com/fatedier/frp/pkg/util/xlog"
)
2016-12-18 17:22:21 +00:00
2022-03-28 04:12:35 +00:00
func init() {
crypto.DefaultSalt = "frp"
// Disable quic-go's receive buffer warning.
os.Setenv("QUIC_GO_DISABLE_RECEIVE_BUFFER_WARNING", "true")
// Disable quic-go's ECN support by default. It may cause issues on certain operating systems.
if os.Getenv("QUIC_GO_DISABLE_ECN") == "" {
os.Setenv("QUIC_GO_DISABLE_ECN", "true")
}
2022-03-28 04:12:35 +00:00
}
type cancelErr struct {
Err error
}
func (e cancelErr) Error() string {
return e.Err.Error()
}
2023-11-27 07:47:49 +00:00
// ServiceOptions contains options for creating a new client service.
type ServiceOptions struct {
Common *v1.ClientCommonConfig
ProxyCfgs []v1.ProxyConfigurer
VisitorCfgs []v1.VisitorConfigurer
// ConfigFilePath is the path to the configuration file used to initialize.
// If it is empty, it means that the configuration file is not used for initialization.
// It may be initialized using command line parameters or called directly.
ConfigFilePath string
// ClientSpec is the client specification that control the client behavior.
ClientSpec *msg.ClientSpec
// ConnectorCreator is a function that creates a new connector to make connections to the server.
// The Connector shields the underlying connection details, whether it is through TCP or QUIC connection,
// and regardless of whether multiplexing is used.
//
// If it is not set, the default frpc connector will be used.
// By using a custom Connector, it can be used to implement a VirtualClient, which connects to frps
// through a pipe instead of a real physical connection.
ConnectorCreator func(context.Context, *v1.ClientCommonConfig) Connector
// HandleWorkConnCb is a callback function that is called when a new work connection is created.
//
// If it is not set, the default frpc implementation will be used.
HandleWorkConnCb func(*v1.ProxyBaseConfig, net.Conn, *msg.StartWorkConn) bool
}
2018-11-06 10:35:05 +00:00
2023-11-27 07:47:49 +00:00
// setServiceOptionsDefault sets the default values for ServiceOptions.
func setServiceOptionsDefault(options *ServiceOptions) {
if options.Common != nil {
options.Common.Complete()
}
if options.ConnectorCreator == nil {
options.ConnectorCreator = NewConnector
}
}
// Service is the client service that connects to frps and provides proxy services.
type Service struct {
2018-11-06 10:35:05 +00:00
ctlMu sync.RWMutex
2023-11-27 07:47:49 +00:00
// manager control connection with server
ctl *Control
// Uniq id got from frps, it will be attached to loginMsg.
runID string
2017-03-08 18:03:47 +00:00
// Sets authentication based on selected method
authSetter auth.Setter
2023-11-27 07:47:49 +00:00
// web server for admin UI and apis
webServer *httppkg.Server
2018-11-06 10:35:05 +00:00
cfgMu sync.RWMutex
2023-11-27 07:47:49 +00:00
common *v1.ClientCommonConfig
proxyCfgs []v1.ProxyConfigurer
visitorCfgs []v1.VisitorConfigurer
clientSpec *msg.ClientSpec
2018-11-06 10:35:05 +00:00
// The configuration file used to initialize this client, or an empty
// string if no configuration file was used.
2023-11-27 07:47:49 +00:00
configFilePath string
2019-10-12 12:13:12 +00:00
// service context
ctx context.Context
// call cancel to stop service
cancel context.CancelCauseFunc
2023-11-27 07:47:49 +00:00
gracefulShutdownDuration time.Duration
2023-11-21 03:19:35 +00:00
2023-11-27 07:47:49 +00:00
connectorCreator func(context.Context, *v1.ClientCommonConfig) Connector
handleWorkConnCb func(*v1.ProxyBaseConfig, net.Conn, *msg.StartWorkConn) bool
2017-03-08 18:03:47 +00:00
}
2023-11-27 07:47:49 +00:00
func NewService(options ServiceOptions) (*Service, error) {
setServiceOptionsDefault(&options)
var webServer *httppkg.Server
if options.Common.WebServer.Port > 0 {
ws, err := httppkg.NewServer(options.Common.WebServer)
if err != nil {
return nil, err
}
webServer = ws
}
s := &Service{
2023-11-21 03:19:35 +00:00
ctx: context.Background(),
2023-11-27 07:47:49 +00:00
authSetter: auth.NewAuthSetter(options.Common.Auth),
webServer: webServer,
common: options.Common,
configFilePath: options.ConfigFilePath,
proxyCfgs: options.ProxyCfgs,
visitorCfgs: options.VisitorCfgs,
clientSpec: options.ClientSpec,
connectorCreator: options.ConnectorCreator,
handleWorkConnCb: options.HandleWorkConnCb,
2016-12-18 17:22:21 +00:00
}
2023-11-27 07:47:49 +00:00
if webServer != nil {
webServer.RouteRegister(s.registerRouteHandlers)
}
return s, nil
2018-11-06 10:35:05 +00:00
}
func (svr *Service) Run(ctx context.Context) error {
ctx, cancel := context.WithCancelCause(ctx)
2023-11-21 03:19:35 +00:00
svr.ctx = xlog.NewContext(ctx, xlog.FromContextSafe(ctx))
svr.cancel = cancel
2022-03-28 04:12:35 +00:00
// set custom DNSServer
2023-11-27 07:47:49 +00:00
if svr.common.DNSServer != "" {
netpkg.SetDefaultDNSAddress(svr.common.DNSServer)
2022-03-28 04:12:35 +00:00
}
2023-11-27 07:47:49 +00:00
// first login to frps
svr.loopLoginUntilSuccess(10*time.Second, lo.FromPtr(svr.common.LoginFailExit))
if svr.ctl == nil {
cancelCause := cancelErr{}
_ = errors.As(context.Cause(svr.ctx), &cancelCause)
return fmt.Errorf("login to the server failed: %v. With loginFailExit enabled, no additional retries will be attempted", cancelCause.Err)
2017-03-08 18:03:47 +00:00
}
2018-11-06 10:35:05 +00:00
go svr.keepControllerWorking()
2023-11-27 07:47:49 +00:00
if svr.webServer != nil {
go func() {
2024-03-12 05:58:53 +00:00
log.Infof("admin server listen on %s", svr.webServer.Address())
2023-11-27 07:47:49 +00:00
if err := svr.webServer.Run(); err != nil {
2024-03-12 05:58:53 +00:00
log.Warnf("admin server exit with error: %v", err)
2023-11-27 07:47:49 +00:00
}
}()
}
2019-10-12 12:13:12 +00:00
<-svr.ctx.Done()
svr.stop()
2017-03-08 18:03:47 +00:00
return nil
}
2017-06-26 17:59:30 +00:00
2018-11-06 10:35:05 +00:00
func (svr *Service) keepControllerWorking() {
<-svr.ctl.Done()
// There is a situation where the login is successful but due to certain reasons,
// the control immediately exits. It is necessary to limit the frequency of reconnection in this case.
// The interval for the first three retries in 1 minute will be very short, and then it will increase exponentially.
// The maximum interval is 20 seconds.
wait.BackoffUntil(func() (bool, error) {
// loopLoginUntilSuccess is another layer of loop that will continuously attempt to
// login to the server until successful.
svr.loopLoginUntilSuccess(20*time.Second, false)
2023-11-27 07:47:49 +00:00
if svr.ctl != nil {
<-svr.ctl.Done()
return false, errors.New("control is closed and try another loop")
2023-11-27 07:47:49 +00:00
}
// If the control is nil, it means that the login failed and the service is also closed.
return false, nil
}, wait.NewFastBackoffManager(
wait.FastBackoffOptions{
Duration: time.Second,
Factor: 2,
Jitter: 0.1,
MaxDuration: 20 * time.Second,
FastRetryCount: 3,
FastRetryDelay: 200 * time.Millisecond,
FastRetryWindow: time.Minute,
FastRetryJitter: 0.5,
},
), true, svr.ctx.Done())
2018-11-06 10:35:05 +00:00
}
// login creates a connection to frps and registers it self as a client
// conn: control connection
// session: if it's not nil, using tcp mux
2023-11-21 03:19:35 +00:00
func (svr *Service) login() (conn net.Conn, connector Connector, err error) {
2019-10-12 12:13:12 +00:00
xl := xlog.FromContextSafe(svr.ctx)
2023-11-27 07:47:49 +00:00
connector = svr.connectorCreator(svr.ctx, svr.common)
2023-11-21 03:19:35 +00:00
if err = connector.Open(); err != nil {
return nil, nil, err
2018-11-06 10:35:05 +00:00
}
defer func() {
if err != nil {
2023-11-21 03:19:35 +00:00
connector.Close()
2018-11-06 10:35:05 +00:00
}
}()
2023-11-21 03:19:35 +00:00
conn, err = connector.Connect()
if err != nil {
return
2018-11-06 10:35:05 +00:00
}
loginMsg := &msg.Login{
Arch: runtime.GOARCH,
Os: runtime.GOOS,
2023-11-27 07:47:49 +00:00
PoolCount: svr.common.Transport.PoolCount,
User: svr.common.User,
Version: version.Full(),
Timestamp: time.Now().Unix(),
2020-05-24 09:48:37 +00:00
RunID: svr.runID,
2023-11-27 07:47:49 +00:00
Metas: svr.common.Metadatas,
}
if svr.clientSpec != nil {
loginMsg.ClientSpec = *svr.clientSpec
}
// Add auth
if err = svr.authSetter.SetLogin(loginMsg); err != nil {
return
2018-11-06 10:35:05 +00:00
}
if err = msg.WriteMsg(conn, loginMsg); err != nil {
return
}
var loginRespMsg msg.LoginResp
2022-08-28 17:02:53 +00:00
_ = conn.SetReadDeadline(time.Now().Add(10 * time.Second))
2018-11-06 10:35:05 +00:00
if err = msg.ReadMsgInto(conn, &loginRespMsg); err != nil {
return
}
2022-08-28 17:02:53 +00:00
_ = conn.SetReadDeadline(time.Time{})
2018-11-06 10:35:05 +00:00
if loginRespMsg.Error != "" {
err = fmt.Errorf("%s", loginRespMsg.Error)
2024-03-12 05:58:53 +00:00
xl.Errorf("%s", loginRespMsg.Error)
2018-11-06 10:35:05 +00:00
return
}
2020-05-24 09:48:37 +00:00
svr.runID = loginRespMsg.RunID
2023-11-21 03:19:35 +00:00
xl.AddPrefix(xlog.LogPrefix{Name: "runID", Value: svr.runID})
2019-10-12 12:13:12 +00:00
2024-03-12 05:58:53 +00:00
xl.Infof("login to server success, get run id [%s]", loginRespMsg.RunID)
2018-11-06 10:35:05 +00:00
return
}
func (svr *Service) loopLoginUntilSuccess(maxInterval time.Duration, firstLoginExit bool) {
xl := xlog.FromContextSafe(svr.ctx)
loginFunc := func() (bool, error) {
2024-03-12 05:58:53 +00:00
xl.Infof("try to connect to server...")
2023-11-21 03:19:35 +00:00
conn, connector, err := svr.login()
if err != nil {
2024-03-12 05:58:53 +00:00
xl.Warnf("connect to server error: %v", err)
if firstLoginExit {
svr.cancel(cancelErr{Err: err})
}
return false, err
}
2023-11-27 07:47:49 +00:00
svr.cfgMu.RLock()
proxyCfgs := svr.proxyCfgs
visitorCfgs := svr.visitorCfgs
svr.cfgMu.RUnlock()
connEncrypted := true
if svr.clientSpec != nil && svr.clientSpec.Type == "ssh-tunnel" {
connEncrypted = false
}
sessionCtx := &SessionContext{
Common: svr.common,
RunID: svr.runID,
Conn: conn,
ConnEncrypted: connEncrypted,
AuthSetter: svr.authSetter,
Connector: connector,
}
ctl, err := NewControl(svr.ctx, sessionCtx)
if err != nil {
conn.Close()
2024-03-12 05:58:53 +00:00
xl.Errorf("NewControl error: %v", err)
return false, err
}
2023-11-27 07:47:49 +00:00
ctl.SetInWorkConnCallback(svr.handleWorkConnCb)
2023-11-27 07:47:49 +00:00
ctl.Run(proxyCfgs, visitorCfgs)
// close and replace previous control
svr.ctlMu.Lock()
if svr.ctl != nil {
svr.ctl.Close()
}
svr.ctl = ctl
svr.ctlMu.Unlock()
return true, nil
}
// try to reconnect to server until success
wait.BackoffUntil(loginFunc, wait.NewFastBackoffManager(
wait.FastBackoffOptions{
2023-12-21 13:38:32 +00:00
Duration: time.Second,
Factor: 2,
Jitter: 0.1,
MaxDuration: maxInterval,
}), true, svr.ctx.Done())
}
2023-11-27 07:47:49 +00:00
func (svr *Service) UpdateAllConfigurer(proxyCfgs []v1.ProxyConfigurer, visitorCfgs []v1.VisitorConfigurer) error {
2018-11-06 10:35:05 +00:00
svr.cfgMu.Lock()
2023-11-27 07:47:49 +00:00
svr.proxyCfgs = proxyCfgs
2018-11-06 10:35:05 +00:00
svr.visitorCfgs = visitorCfgs
svr.cfgMu.Unlock()
svr.ctlMu.RLock()
2022-04-14 03:24:36 +00:00
ctl := svr.ctl
svr.ctlMu.RUnlock()
if ctl != nil {
2023-11-27 07:47:49 +00:00
return svr.ctl.UpdateAllConfigurer(proxyCfgs, visitorCfgs)
2022-04-14 03:24:36 +00:00
}
return nil
2018-11-06 10:35:05 +00:00
}
2021-10-19 07:02:45 +00:00
func (svr *Service) Close() {
svr.GracefulClose(time.Duration(0))
}
func (svr *Service) GracefulClose(d time.Duration) {
2023-11-27 07:47:49 +00:00
svr.gracefulShutdownDuration = d
svr.cancel(nil)
}
func (svr *Service) stop() {
svr.ctlMu.Lock()
defer svr.ctlMu.Unlock()
2020-09-07 07:45:44 +00:00
if svr.ctl != nil {
2023-11-27 07:47:49 +00:00
svr.ctl.GracefulClose(svr.gracefulShutdownDuration)
svr.ctl = nil
2020-09-07 07:45:44 +00:00
}
2017-06-26 17:59:30 +00:00
}
2023-11-27 07:47:49 +00:00
func (svr *Service) getProxyStatus(name string) (*proxy.WorkingStatus, bool) {
2023-11-27 07:47:49 +00:00
svr.ctlMu.RLock()
ctl := svr.ctl
svr.ctlMu.RUnlock()
if ctl == nil {
return nil, false
2023-11-27 07:47:49 +00:00
}
return ctl.pm.GetProxyStatus(name)
}
func (svr *Service) StatusExporter() StatusExporter {
return &statusExporterImpl{
getProxyStatusFunc: svr.getProxyStatus,
2023-11-27 07:47:49 +00:00
}
}
type StatusExporter interface {
GetProxyStatus(name string) (*proxy.WorkingStatus, bool)
}
type statusExporterImpl struct {
getProxyStatusFunc func(name string) (*proxy.WorkingStatus, bool)
}
func (s *statusExporterImpl) GetProxyStatus(name string) (*proxy.WorkingStatus, bool) {
return s.getProxyStatusFunc(name)
2023-11-27 07:47:49 +00:00
}