frp/client/service.go

391 lines
11 KiB
Go
Raw Normal View History

2017-03-09 02:03:47 +08:00
// Copyright 2017 fatedier, fatedier@gmail.com
2016-12-19 01:22:21 +08: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-09 02:03:47 +08:00
package client
2016-12-19 01:22:21 +08:00
import (
2019-10-12 20:13:12 +08:00
"context"
"errors"
2018-11-06 18:35:05 +08:00
"fmt"
2019-10-12 20:13:12 +08:00
"net"
2018-11-06 18:35:05 +08:00
"runtime"
"sync"
"time"
2022-08-29 01:02:53 +08:00
"github.com/fatedier/golib/crypto"
"github.com/samber/lo"
2022-08-29 01:02:53 +08:00
2023-11-27 15:47:49 +08:00
"github.com/fatedier/frp/client/proxy"
2020-09-23 13:49:14 +08:00
"github.com/fatedier/frp/pkg/auth"
v1 "github.com/fatedier/frp/pkg/config/v1"
2020-09-23 13:49:14 +08:00
"github.com/fatedier/frp/pkg/msg"
2023-11-27 15:47:49 +08:00
httppkg "github.com/fatedier/frp/pkg/util/http"
2020-09-23 13:49:14 +08:00
"github.com/fatedier/frp/pkg/util/log"
2023-11-27 15:47:49 +08:00
netpkg "github.com/fatedier/frp/pkg/util/net"
2020-09-23 13:49:14 +08:00
"github.com/fatedier/frp/pkg/util/version"
"github.com/fatedier/frp/pkg/util/wait"
2020-09-23 13:49:14 +08:00
"github.com/fatedier/frp/pkg/util/xlog"
)
2016-12-19 01:22:21 +08:00
2022-03-28 12:12:35 +08:00
func init() {
crypto.DefaultSalt = "frp"
}
type cancelErr struct {
Err error
}
func (e cancelErr) Error() string {
return e.Err.Error()
}
2023-11-27 15:47:49 +08: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 18:35:05 +08:00
2023-11-27 15:47:49 +08: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 18:35:05 +08:00
ctlMu sync.RWMutex
2023-11-27 15:47:49 +08:00
// manager control connection with server
ctl *Control
// Uniq id got from frps, it will be attached to loginMsg.
runID string
2017-03-09 02:03:47 +08:00
// Sets authentication based on selected method
authSetter auth.Setter
2023-11-27 15:47:49 +08:00
// web server for admin UI and apis
webServer *httppkg.Server
2018-11-06 18:35:05 +08:00
cfgMu sync.RWMutex
2023-11-27 15:47:49 +08:00
common *v1.ClientCommonConfig
proxyCfgs []v1.ProxyConfigurer
visitorCfgs []v1.VisitorConfigurer
clientSpec *msg.ClientSpec
2018-11-06 18:35:05 +08:00
// The configuration file used to initialize this client, or an empty
// string if no configuration file was used.
2023-11-27 15:47:49 +08:00
configFilePath string
2019-10-12 20:13:12 +08:00
// service context
ctx context.Context
// call cancel to stop service
cancel context.CancelCauseFunc
2023-11-27 15:47:49 +08:00
gracefulShutdownDuration time.Duration
2023-11-21 11:19:35 +08:00
2023-11-27 15:47:49 +08:00
connectorCreator func(context.Context, *v1.ClientCommonConfig) Connector
handleWorkConnCb func(*v1.ProxyBaseConfig, net.Conn, *msg.StartWorkConn) bool
2017-03-09 02:03:47 +08:00
}
2023-11-27 15:47:49 +08: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 11:19:35 +08:00
ctx: context.Background(),
2023-11-27 15:47:49 +08: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-19 01:22:21 +08:00
}
2023-11-27 15:47:49 +08:00
if webServer != nil {
webServer.RouteRegister(s.registerRouteHandlers)
}
return s, nil
2018-11-06 18:35:05 +08:00
}
func (svr *Service) Run(ctx context.Context) error {
ctx, cancel := context.WithCancelCause(ctx)
2023-11-21 11:19:35 +08:00
svr.ctx = xlog.NewContext(ctx, xlog.FromContextSafe(ctx))
svr.cancel = cancel
2022-03-28 12:12:35 +08:00
// set custom DNSServer
2023-11-27 15:47:49 +08:00
if svr.common.DNSServer != "" {
netpkg.SetDefaultDNSAddress(svr.common.DNSServer)
2022-03-28 12:12:35 +08:00
}
2023-11-27 15:47:49 +08: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-09 02:03:47 +08:00
}
2018-11-06 18:35:05 +08:00
go svr.keepControllerWorking()
2023-11-27 15:47:49 +08:00
if svr.webServer != nil {
go func() {
log.Info("admin server listen on %s", svr.webServer.Address())
if err := svr.webServer.Run(); err != nil {
log.Warn("admin server exit with error: %v", err)
}
}()
}
2019-10-12 20:13:12 +08:00
<-svr.ctx.Done()
svr.stop()
2017-03-09 02:03:47 +08:00
return nil
}
2017-06-27 01:59:30 +08:00
2018-11-06 18:35:05 +08: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 15:47:49 +08:00
if svr.ctl != nil {
<-svr.ctl.Done()
return false, errors.New("control is closed and try another loop")
2023-11-27 15:47:49 +08: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 18:35:05 +08: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 11:19:35 +08:00
func (svr *Service) login() (conn net.Conn, connector Connector, err error) {
2019-10-12 20:13:12 +08:00
xl := xlog.FromContextSafe(svr.ctx)
2023-11-27 15:47:49 +08:00
connector = svr.connectorCreator(svr.ctx, svr.common)
2023-11-21 11:19:35 +08:00
if err = connector.Open(); err != nil {
return nil, nil, err
2018-11-06 18:35:05 +08:00
}
defer func() {
if err != nil {
2023-11-21 11:19:35 +08:00
connector.Close()
2018-11-06 18:35:05 +08:00
}
}()
2023-11-21 11:19:35 +08:00
conn, err = connector.Connect()
if err != nil {
return
2018-11-06 18:35:05 +08:00
}
loginMsg := &msg.Login{
Arch: runtime.GOARCH,
Os: runtime.GOOS,
2023-11-27 15:47:49 +08:00
PoolCount: svr.common.Transport.PoolCount,
User: svr.common.User,
Version: version.Full(),
Timestamp: time.Now().Unix(),
2020-05-24 17:48:37 +08:00
RunID: svr.runID,
2023-11-27 15:47:49 +08: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 18:35:05 +08:00
}
if err = msg.WriteMsg(conn, loginMsg); err != nil {
return
}
var loginRespMsg msg.LoginResp
2022-08-29 01:02:53 +08:00
_ = conn.SetReadDeadline(time.Now().Add(10 * time.Second))
2018-11-06 18:35:05 +08:00
if err = msg.ReadMsgInto(conn, &loginRespMsg); err != nil {
return
}
2022-08-29 01:02:53 +08:00
_ = conn.SetReadDeadline(time.Time{})
2018-11-06 18:35:05 +08:00
if loginRespMsg.Error != "" {
err = fmt.Errorf("%s", loginRespMsg.Error)
2019-10-12 20:13:12 +08:00
xl.Error("%s", loginRespMsg.Error)
2018-11-06 18:35:05 +08:00
return
}
2020-05-24 17:48:37 +08:00
svr.runID = loginRespMsg.RunID
2023-11-21 11:19:35 +08:00
xl.AddPrefix(xlog.LogPrefix{Name: "runID", Value: svr.runID})
2019-10-12 20:13:12 +08:00
xl.Info("login to server success, get run id [%s]", loginRespMsg.RunID)
2018-11-06 18:35:05 +08:00
return
}
func (svr *Service) loopLoginUntilSuccess(maxInterval time.Duration, firstLoginExit bool) {
xl := xlog.FromContextSafe(svr.ctx)
loginFunc := func() (bool, error) {
xl.Info("try to connect to server...")
2023-11-21 11:19:35 +08:00
conn, connector, err := svr.login()
if err != nil {
xl.Warn("connect to server error: %v", err)
if firstLoginExit {
svr.cancel(cancelErr{Err: err})
}
return false, err
}
2023-11-27 15:47:49 +08: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()
xl.Error("NewControl error: %v", err)
return false, err
}
2023-11-27 15:47:49 +08:00
ctl.SetInWorkConnCallback(svr.handleWorkConnCb)
2023-11-27 15:47:49 +08: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 21:38:32 +08:00
Duration: time.Second,
Factor: 2,
Jitter: 0.1,
MaxDuration: maxInterval,
}), true, svr.ctx.Done())
}
2023-11-27 15:47:49 +08:00
func (svr *Service) UpdateAllConfigurer(proxyCfgs []v1.ProxyConfigurer, visitorCfgs []v1.VisitorConfigurer) error {
2018-11-06 18:35:05 +08:00
svr.cfgMu.Lock()
2023-11-27 15:47:49 +08:00
svr.proxyCfgs = proxyCfgs
2018-11-06 18:35:05 +08:00
svr.visitorCfgs = visitorCfgs
svr.cfgMu.Unlock()
svr.ctlMu.RLock()
2022-04-14 11:24:36 +08:00
ctl := svr.ctl
svr.ctlMu.RUnlock()
if ctl != nil {
2023-11-27 15:47:49 +08:00
return svr.ctl.UpdateAllConfigurer(proxyCfgs, visitorCfgs)
2022-04-14 11:24:36 +08:00
}
return nil
2018-11-06 18:35:05 +08:00
}
2021-10-19 15:02:45 +08:00
func (svr *Service) Close() {
svr.GracefulClose(time.Duration(0))
}
func (svr *Service) GracefulClose(d time.Duration) {
2023-11-27 15:47:49 +08:00
svr.gracefulShutdownDuration = d
svr.cancel(nil)
}
func (svr *Service) stop() {
svr.ctlMu.Lock()
defer svr.ctlMu.Unlock()
2020-09-07 15:45:44 +08:00
if svr.ctl != nil {
2023-11-27 15:47:49 +08:00
svr.ctl.GracefulClose(svr.gracefulShutdownDuration)
svr.ctl = nil
2020-09-07 15:45:44 +08:00
}
2017-06-27 01:59:30 +08:00
}
2023-11-27 15:47:49 +08:00
// TODO(fatedier): Use StatusExporter to provide query interfaces instead of directly using methods from the Service.
func (svr *Service) GetProxyStatus(name string) (*proxy.WorkingStatus, error) {
svr.ctlMu.RLock()
ctl := svr.ctl
svr.ctlMu.RUnlock()
if ctl == nil {
return nil, fmt.Errorf("control is not running")
}
ws, ok := ctl.pm.GetProxyStatus(name)
if !ok {
return nil, fmt.Errorf("proxy [%s] is not found", name)
}
return ws, nil
}