frp/client/service.go

320 lines
8.2 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"
"strconv"
2018-11-06 18:35:05 +08:00
"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
2019-02-01 19:26:10 +08:00
"github.com/fatedier/frp/assets"
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"
"github.com/fatedier/frp/pkg/util/log"
"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"
}
// Service is a client service.
2017-03-09 02:03:47 +08:00
type Service struct {
2018-11-06 18:35:05 +08:00
// uniq id got from frps, attach it in loginMsg
2020-05-24 17:48:37 +08:00
runID string
2018-11-06 18:35:05 +08:00
2017-03-09 02:03:47 +08:00
// manager control connection with server
2018-11-06 18:35:05 +08:00
ctl *Control
ctlMu sync.RWMutex
2017-03-09 02:03:47 +08:00
// Sets authentication based on selected method
authSetter auth.Setter
cfg *v1.ClientCommonConfig
pxyCfgs []v1.ProxyConfigurer
visitorCfgs []v1.VisitorConfigurer
2018-11-06 18:35:05 +08:00
cfgMu sync.RWMutex
// The configuration file used to initialize this client, or an empty
// string if no configuration file was used.
cfgFile string
2019-10-12 20:13:12 +08:00
// service context
ctx context.Context
// call cancel to stop service
cancel context.CancelFunc
gracefulDuration time.Duration
2023-11-21 11:19:35 +08:00
connectorCreator func(context.Context, *v1.ClientCommonConfig) Connector
inWorkConnCallback func(*v1.ProxyBaseConfig, net.Conn, *msg.StartWorkConn) bool
2017-03-09 02:03:47 +08:00
}
2022-08-29 01:02:53 +08:00
func NewService(
cfg *v1.ClientCommonConfig,
pxyCfgs []v1.ProxyConfigurer,
visitorCfgs []v1.VisitorConfigurer,
2022-08-29 01:02:53 +08:00
cfgFile string,
) *Service {
return &Service{
2023-11-21 11:19:35 +08:00
authSetter: auth.NewAuthSetter(cfg.Auth),
cfg: cfg,
cfgFile: cfgFile,
pxyCfgs: pxyCfgs,
visitorCfgs: visitorCfgs,
ctx: context.Background(),
connectorCreator: NewConnector,
2016-12-19 01:22:21 +08:00
}
}
2017-03-09 02:03:47 +08:00
2023-11-21 11:19:35 +08:00
func (svr *Service) SetConnectorCreator(h func(context.Context, *v1.ClientCommonConfig) Connector) {
svr.connectorCreator = h
}
func (svr *Service) SetInWorkConnCallback(cb func(*v1.ProxyBaseConfig, net.Conn, *msg.StartWorkConn) bool) {
svr.inWorkConnCallback = cb
}
2018-11-06 18:35:05 +08:00
func (svr *Service) GetController() *Control {
svr.ctlMu.RLock()
defer svr.ctlMu.RUnlock()
return svr.ctl
}
func (svr *Service) Run(ctx context.Context) error {
ctx, cancel := context.WithCancel(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
if svr.cfg.DNSServer != "" {
dnsAddr := svr.cfg.DNSServer
if _, _, err := net.SplitHostPort(dnsAddr); err != nil {
dnsAddr = net.JoinHostPort(dnsAddr, "53")
2022-03-28 12:12:35 +08:00
}
// Change default dns server for frpc
net.DefaultResolver = &net.Resolver{
PreferGo: true,
Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
return net.Dial("udp", dnsAddr)
},
}
}
2019-10-12 20:13:12 +08:00
// login to frps
svr.loopLoginUntilSuccess(10*time.Second, lo.FromPtr(svr.cfg.LoginFailExit))
if svr.ctl == nil {
return fmt.Errorf("the process exited because the first login to the server failed, and the loginFailExit feature is enabled")
2017-03-09 02:03:47 +08:00
}
2018-11-06 18:35:05 +08:00
go svr.keepControllerWorking()
if svr.cfg.WebServer.Port != 0 {
// Init admin server assets
assets.Load(svr.cfg.WebServer.AssetsDir)
address := net.JoinHostPort(svr.cfg.WebServer.Addr, strconv.Itoa(svr.cfg.WebServer.Port))
err := svr.RunAdminServer(address)
if err != nil {
log.Warn("run admin server error: %v", err)
}
log.Info("admin server listen on %s:%d", svr.cfg.WebServer.Addr, svr.cfg.WebServer.Port)
}
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() error {
// loopLoginUntilSuccess is another layer of loop that will continuously attempt to
// login to the server until successful.
svr.loopLoginUntilSuccess(20*time.Second, false)
<-svr.ctl.Done()
return errors.New("control is closed and try another loop")
}, 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-21 11:19:35 +08:00
connector = svr.connectorCreator(svr.ctx, svr.cfg)
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,
PoolCount: svr.cfg.Transport.PoolCount,
User: svr.cfg.User,
Version: version.Full(),
Timestamp: time.Now().Unix(),
2020-05-24 17:48:37 +08:00
RunID: svr.runID,
Metas: svr.cfg.Metadatas,
}
// 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)
successCh := make(chan struct{})
loginFunc := func() 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()
}
return err
}
2023-11-21 11:19:35 +08:00
ctl, err := NewControl(svr.ctx, svr.runID, conn, connector,
svr.cfg, svr.pxyCfgs, svr.visitorCfgs, svr.authSetter)
if err != nil {
conn.Close()
xl.Error("NewControl error: %v", err)
return err
}
2023-11-21 11:19:35 +08:00
ctl.SetInWorkConnCallback(svr.inWorkConnCallback)
ctl.Run()
// close and replace previous control
svr.ctlMu.Lock()
if svr.ctl != nil {
svr.ctl.Close()
}
svr.ctl = ctl
svr.ctlMu.Unlock()
close(successCh)
return nil
}
// try to reconnect to server until success
wait.BackoffUntil(loginFunc, wait.NewFastBackoffManager(
wait.FastBackoffOptions{
Duration: time.Second,
Factor: 2,
Jitter: 0.1,
MaxDuration: maxInterval,
}),
true,
wait.MergeAndCloseOnAnyStopChannel(svr.ctx.Done(), successCh))
}
func (svr *Service) ReloadConf(pxyCfgs []v1.ProxyConfigurer, visitorCfgs []v1.VisitorConfigurer) error {
2018-11-06 18:35:05 +08:00
svr.cfgMu.Lock()
svr.pxyCfgs = pxyCfgs
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 {
return svr.ctl.ReloadConf(pxyCfgs, visitorCfgs)
}
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) {
svr.gracefulDuration = d
svr.cancel()
}
func (svr *Service) stop() {
svr.ctlMu.Lock()
defer svr.ctlMu.Unlock()
2020-09-07 15:45:44 +08:00
if svr.ctl != nil {
svr.ctl.GracefulClose(svr.gracefulDuration)
svr.ctl = nil
2020-09-07 15:45:44 +08:00
}
2017-06-27 01:59:30 +08:00
}