frp/client/service.go

329 lines
7.9 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"
2019-03-11 14:14:31 +08:00
"crypto/tls"
"errors"
2018-11-06 18:35:05 +08:00
"fmt"
"io"
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"
"sync/atomic"
"time"
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"
"github.com/fatedier/frp/pkg/config"
"github.com/fatedier/frp/pkg/msg"
"github.com/fatedier/frp/pkg/transport"
"github.com/fatedier/frp/pkg/util/log"
frpNet "github.com/fatedier/frp/pkg/util/net"
"github.com/fatedier/frp/pkg/util/version"
"github.com/fatedier/frp/pkg/util/xlog"
2018-11-06 18:35:05 +08:00
fmux "github.com/hashicorp/yamux"
)
2016-12-19 01:22:21 +08:00
// 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 config.ClientCommonConf
2018-11-06 18:35:05 +08:00
pxyCfgs map[string]config.ProxyConf
visitorCfgs map[string]config.VisitorConf
cfgMu sync.RWMutex
// The configuration file used to initialize this client, or an empty
// string if no configuration file was used.
cfgFile string
// This is configured by the login response from frps
serverUDPPort int
2019-10-12 20:13:12 +08:00
exit uint32 // 0 means not exit
// service context
ctx context.Context
// call cancel to stop service
cancel context.CancelFunc
2017-03-09 02:03:47 +08:00
}
func NewService(cfg config.ClientCommonConf, pxyCfgs map[string]config.ProxyConf, visitorCfgs map[string]config.VisitorConf, cfgFile string) (svr *Service, err error) {
2019-10-12 20:13:12 +08:00
ctx, cancel := context.WithCancel(context.Background())
2017-03-09 02:03:47 +08:00
svr = &Service{
2020-05-24 17:48:37 +08:00
authSetter: auth.NewAuthSetter(cfg.ClientConfig),
cfg: cfg,
cfgFile: cfgFile,
2018-11-06 18:35:05 +08:00
pxyCfgs: pxyCfgs,
visitorCfgs: visitorCfgs,
exit: 0,
2019-10-12 20:13:12 +08:00
ctx: xlog.NewContext(ctx, xlog.New()),
cancel: cancel,
2016-12-19 01:22:21 +08:00
}
return
}
2017-03-09 02:03:47 +08:00
2018-11-06 18:35:05 +08:00
func (svr *Service) GetController() *Control {
svr.ctlMu.RLock()
defer svr.ctlMu.RUnlock()
return svr.ctl
}
2017-03-09 02:03:47 +08:00
func (svr *Service) Run() error {
2019-10-12 20:13:12 +08:00
xl := xlog.FromContextSafe(svr.ctx)
// login to frps
2018-11-06 18:35:05 +08:00
for {
conn, session, err := svr.login()
if err != nil {
2019-10-12 20:13:12 +08:00
xl.Warn("login to server failed: %v", err)
2018-11-06 18:35:05 +08:00
// if login_fail_exit is true, just exit this program
// otherwise sleep a while and try again to connect to server
if svr.cfg.LoginFailExit {
2018-11-06 18:35:05 +08:00
return err
}
2020-05-24 17:48:37 +08:00
time.Sleep(10 * time.Second)
2018-11-06 18:35:05 +08:00
} else {
// login success
2020-05-24 17:48:37 +08:00
ctl := NewControl(svr.ctx, svr.runID, conn, session, svr.cfg, svr.pxyCfgs, svr.visitorCfgs, svr.serverUDPPort, svr.authSetter)
2018-11-06 18:35:05 +08:00
ctl.Run()
svr.ctlMu.Lock()
svr.ctl = ctl
svr.ctlMu.Unlock()
break
}
2017-03-09 02:03:47 +08:00
}
2018-11-06 18:35:05 +08:00
go svr.keepControllerWorking()
if svr.cfg.AdminPort != 0 {
// Init admin server assets
assets.Load(svr.cfg.AssetsDir)
2021-03-10 20:19:58 +08:00
address := net.JoinHostPort(svr.cfg.AdminAddr, strconv.Itoa(svr.cfg.AdminPort))
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.AdminAddr, svr.cfg.AdminPort)
}
2019-10-12 20:13:12 +08:00
<-svr.ctx.Done()
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() {
2019-10-12 20:13:12 +08:00
xl := xlog.FromContextSafe(svr.ctx)
2018-11-06 18:35:05 +08:00
maxDelayTime := 20 * time.Second
delayTime := time.Second
// if frpc reconnect frps, we need to limit retry times in 1min
// current retry logic is sleep 0s, 0s, 0s, 1s, 2s, 4s, 8s, ...
// when exceed 1min, we will reset delay and counts
cutoffTime := time.Now().Add(time.Minute)
reconnectDelay := time.Second
reconnectCounts := 1
2018-11-06 18:35:05 +08:00
for {
<-svr.ctl.ClosedDoneCh()
if atomic.LoadUint32(&svr.exit) != 0 {
return
}
// the first three retry with no delay
if reconnectCounts > 3 {
time.Sleep(reconnectDelay)
reconnectDelay *= 2
}
reconnectCounts++
now := time.Now()
if now.After(cutoffTime) {
// reset
cutoffTime = now.Add(time.Minute)
reconnectDelay = time.Second
reconnectCounts = 1
}
2018-11-06 18:35:05 +08:00
for {
2019-10-12 20:13:12 +08:00
xl.Info("try to reconnect to server...")
2018-11-06 18:35:05 +08:00
conn, session, err := svr.login()
if err != nil {
2019-10-12 20:13:12 +08:00
xl.Warn("reconnect to server error: %v", err)
2018-11-06 18:35:05 +08:00
time.Sleep(delayTime)
opErr := &net.OpError{}
// quick retry for dial error
if errors.As(err, &opErr) && opErr.Op == "dial" {
delayTime = 2 * time.Second
} else {
delayTime = delayTime * 2
if delayTime > maxDelayTime {
delayTime = maxDelayTime
}
2018-11-06 18:35:05 +08:00
}
continue
}
// reconnect success, init delayTime
delayTime = time.Second
2020-05-24 17:48:37 +08:00
ctl := NewControl(svr.ctx, svr.runID, conn, session, svr.cfg, svr.pxyCfgs, svr.visitorCfgs, svr.serverUDPPort, svr.authSetter)
2018-11-06 18:35:05 +08:00
ctl.Run()
svr.ctlMu.Lock()
if svr.ctl != nil {
svr.ctl.Close()
}
2018-11-06 18:35:05 +08:00
svr.ctl = ctl
svr.ctlMu.Unlock()
break
}
}
}
// 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
2019-10-12 20:13:12 +08:00
func (svr *Service) login() (conn net.Conn, session *fmux.Session, err error) {
xl := xlog.FromContextSafe(svr.ctx)
2019-03-11 14:14:31 +08:00
var tlsConfig *tls.Config
if svr.cfg.TLSEnable {
sn := svr.cfg.TLSServerName
if sn == "" {
sn = svr.cfg.ServerAddr
}
tlsConfig, err = transport.NewClientTLSConfig(
svr.cfg.TLSCertFile,
svr.cfg.TLSKeyFile,
svr.cfg.TLSTrustedCaFile,
sn)
if err != nil {
xl.Warn("fail to build tls configuration when service login, err: %v", err)
return
2019-03-11 14:14:31 +08:00
}
}
conn, err = frpNet.DialWithOptions(net.JoinHostPort(svr.cfg.ServerAddr, strconv.Itoa(svr.cfg.ServerPort)),
frpNet.WithProxyURL(svr.cfg.HTTPProxy),
frpNet.WithProtocol(svr.cfg.Protocol),
frpNet.WithTLSConfig(tlsConfig),
frpNet.WithDisableCustomTLSHeadByte(svr.cfg.DisableCustomTLSFirstByte))
2018-11-06 18:35:05 +08:00
if err != nil {
return
}
defer func() {
if err != nil {
conn.Close()
2019-08-03 16:43:21 +08:00
if session != nil {
session.Close()
}
2018-11-06 18:35:05 +08:00
}
}()
2020-05-24 17:48:37 +08:00
if svr.cfg.TCPMux {
2018-11-06 18:35:05 +08:00
fmuxCfg := fmux.DefaultConfig()
2018-12-11 15:06:54 +08:00
fmuxCfg.KeepAliveInterval = 20 * time.Second
fmuxCfg.LogOutput = io.Discard
2018-11-06 18:35:05 +08:00
session, err = fmux.Client(conn, fmuxCfg)
if err != nil {
return
}
stream, errRet := session.OpenStream()
if errRet != nil {
session.Close()
err = errRet
return
}
2019-10-12 20:13:12 +08:00
conn = stream
2018-11-06 18:35:05 +08:00
}
loginMsg := &msg.Login{
Arch: runtime.GOARCH,
Os: runtime.GOOS,
PoolCount: svr.cfg.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.Metas,
}
// 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
conn.SetReadDeadline(time.Now().Add(10 * time.Second))
if err = msg.ReadMsgInto(conn, &loginRespMsg); err != nil {
return
}
conn.SetReadDeadline(time.Time{})
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
2019-10-12 20:13:12 +08:00
xl.ResetPrefixes()
2020-05-24 17:48:37 +08:00
xl.AppendPrefix(svr.runID)
2019-10-12 20:13:12 +08:00
2020-05-24 17:48:37 +08:00
svr.serverUDPPort = loginRespMsg.ServerUDPPort
xl.Info("login to server success, get run id [%s], server udp port [%d]", loginRespMsg.RunID, loginRespMsg.ServerUDPPort)
2018-11-06 18:35:05 +08:00
return
}
func (svr *Service) ReloadConf(pxyCfgs map[string]config.ProxyConf, visitorCfgs map[string]config.VisitorConf) error {
svr.cfgMu.Lock()
svr.pxyCfgs = pxyCfgs
svr.visitorCfgs = visitorCfgs
svr.cfgMu.Unlock()
return svr.ctl.ReloadConf(pxyCfgs, visitorCfgs)
}
2021-10-19 15:02:45 +08:00
func (svr *Service) Close() {
svr.GracefulClose(time.Duration(0))
}
func (svr *Service) GracefulClose(d time.Duration) {
2018-11-06 18:35:05 +08:00
atomic.StoreUint32(&svr.exit, 1)
2020-09-07 15:45:44 +08:00
if svr.ctl != nil {
2021-10-19 15:02:45 +08:00
svr.ctl.GracefulClose(d)
2020-09-07 15:45:44 +08:00
}
2019-10-12 20:13:12 +08:00
svr.cancel()
2017-06-27 01:59:30 +08:00
}