frp/client/control.go

362 lines
9.2 KiB
Go
Raw Normal View History

2017-03-08 19:03:47 +01:00
// Copyright 2017 fatedier, fatedier@gmail.com
//
// 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.
package client
import (
2019-10-12 14:13:12 +02:00
"context"
2017-03-08 19:03:47 +01:00
"io"
2019-10-12 14:13:12 +02:00
"net"
2018-05-11 04:42:57 +02:00
"runtime/debug"
2017-03-08 19:03:47 +01:00
"time"
2022-08-28 19:02:53 +02:00
"github.com/fatedier/golib/control/shutdown"
"github.com/fatedier/golib/crypto"
2018-12-09 15:06:22 +01:00
"github.com/fatedier/frp/client/proxy"
"github.com/fatedier/frp/client/visitor"
2020-09-23 07:49:14 +02: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"
2020-09-23 07:49:14 +02:00
"github.com/fatedier/frp/pkg/util/xlog"
2017-03-08 19:03:47 +01:00
)
type Control struct {
// service context
ctx context.Context
xl *xlog.Logger
// Unique ID obtained from frps.
// It should be attached to the login message when reconnecting.
2020-05-24 11:48:37 +02:00
runID string
2017-03-08 19:03:47 +01:00
// manage all proxies
2018-12-07 10:05:36 +01:00
pxyCfgs map[string]config.ProxyConf
2020-05-24 11:48:37 +02:00
pm *proxy.Manager
2017-06-25 21:02:33 +02:00
// manage all visitors
vm *visitor.Manager
2017-03-08 19:03:47 +01:00
// control connection
2019-10-12 14:13:12 +02:00
conn net.Conn
2017-03-08 19:03:47 +01:00
cm *ConnectionManager
2017-03-08 19:03:47 +01:00
// put a message in this channel to send it over control connection to server
sendCh chan (msg.Message)
// read from this channel to get the next message sent by server
readCh chan (msg.Message)
// goroutines can block by reading from this channel, it will be closed only in reader() when control connection is closed
2018-11-06 11:35:05 +01:00
closedCh chan struct{}
closedDoneCh chan struct{}
2017-03-08 19:03:47 +01:00
// last time got the Pong message
lastPong time.Time
// The client configuration
clientCfg config.ClientCommonConf
2018-01-16 18:09:33 +01:00
readerShutdown *shutdown.Shutdown
writerShutdown *shutdown.Shutdown
msgHandlerShutdown *shutdown.Shutdown
// sets authentication based on selected method
authSetter auth.Setter
msgTransporter transport.MessageTransporter
2017-03-08 19:03:47 +01:00
}
func NewControl(
ctx context.Context, runID string, conn net.Conn, cm *ConnectionManager,
2019-10-12 14:13:12 +02:00
clientCfg config.ClientCommonConf,
pxyCfgs map[string]config.ProxyConf,
visitorCfgs map[string]config.VisitorConf,
2022-08-28 19:02:53 +02:00
authSetter auth.Setter,
) *Control {
2019-10-12 14:13:12 +02:00
// new xlog instance
2018-01-16 18:09:33 +01:00
ctl := &Control{
ctx: ctx,
xl: xlog.FromContextSafe(ctx),
2020-05-24 11:48:37 +02:00
runID: runID,
2018-11-06 11:35:05 +01:00
conn: conn,
cm: cm,
2018-12-07 10:05:36 +01:00
pxyCfgs: pxyCfgs,
sendCh: make(chan msg.Message, 100),
readCh: make(chan msg.Message, 100),
2018-11-06 11:35:05 +01:00
closedCh: make(chan struct{}),
closedDoneCh: make(chan struct{}),
clientCfg: clientCfg,
2018-01-16 18:09:33 +01:00
readerShutdown: shutdown.New(),
writerShutdown: shutdown.New(),
msgHandlerShutdown: shutdown.New(),
authSetter: authSetter,
2017-03-08 19:03:47 +01:00
}
ctl.msgTransporter = transport.NewMessageTransporter(ctl.sendCh)
ctl.pm = proxy.NewManager(ctl.ctx, clientCfg, ctl.msgTransporter)
2018-12-07 10:05:36 +01:00
2023-05-30 14:25:22 +02:00
ctl.vm = visitor.NewManager(ctl.ctx, ctl.runID, ctl.clientCfg, ctl.connectServer, ctl.msgTransporter)
ctl.vm.Reload(visitorCfgs)
2018-01-16 18:09:33 +01:00
return ctl
2017-03-08 19:03:47 +01:00
}
2018-11-06 11:35:05 +01:00
func (ctl *Control) Run() {
2018-01-16 18:09:33 +01:00
go ctl.worker()
2017-06-27 17:30:09 +02:00
2018-12-07 10:05:36 +01:00
// start all proxies
ctl.pm.Reload(ctl.pxyCfgs)
2018-12-07 10:05:36 +01:00
// start all visitors
go ctl.vm.Run()
2017-06-25 21:02:33 +02:00
}
2023-07-21 04:30:46 +02:00
func (ctl *Control) HandleReqWorkConn(_ *msg.ReqWorkConn) {
2019-10-12 14:13:12 +02:00
xl := ctl.xl
2017-06-25 21:02:33 +02:00
workConn, err := ctl.connectServer()
if err != nil {
xl.Warn("start new connection to server error: %v", err)
2017-06-25 21:02:33 +02:00
return
2017-03-08 19:03:47 +01:00
}
m := &msg.NewWorkConn{
2020-05-24 11:48:37 +02:00
RunID: ctl.runID,
2017-03-08 19:03:47 +01:00
}
if err = ctl.authSetter.SetNewWorkConn(m); err != nil {
xl.Warn("error during NewWorkConn authentication: %v", err)
return
}
2017-03-08 19:03:47 +01:00
if err = msg.WriteMsg(workConn, m); err != nil {
2019-10-12 14:13:12 +02:00
xl.Warn("work connection write to server error: %v", err)
2017-03-08 19:03:47 +01:00
workConn.Close()
return
}
var startMsg msg.StartWorkConn
if err = msg.ReadMsgInto(workConn, &startMsg); err != nil {
2022-12-18 11:43:42 +01:00
xl.Trace("work connection closed before response StartWorkConn message: %v", err)
2017-03-08 19:03:47 +01:00
workConn.Close()
return
}
if startMsg.Error != "" {
xl.Error("StartWorkConn contains error: %s", startMsg.Error)
workConn.Close()
return
}
2017-03-08 19:03:47 +01:00
// dispatch this work connection to related proxy
2019-03-29 12:01:18 +01:00
ctl.pm.HandleWorkConn(startMsg.ProxyName, workConn, &startMsg)
2018-01-16 18:09:33 +01:00
}
func (ctl *Control) HandleNewProxyResp(inMsg *msg.NewProxyResp) {
2019-10-12 14:13:12 +02:00
xl := ctl.xl
2018-01-16 18:09:33 +01:00
// Server will return NewProxyResp message to each NewProxy message.
// Start a new proxy handler if no error got
2018-01-17 07:40:08 +01:00
err := ctl.pm.StartProxy(inMsg.ProxyName, inMsg.RemoteAddr, inMsg.Error)
2018-01-16 18:09:33 +01:00
if err != nil {
2019-10-12 14:13:12 +02:00
xl.Warn("[%s] start error: %v", inMsg.ProxyName, err)
2017-03-12 19:44:47 +01:00
} else {
2019-10-12 14:13:12 +02:00
xl.Info("[%s] start proxy success", inMsg.ProxyName)
2017-03-08 19:03:47 +01:00
}
}
func (ctl *Control) HandleNatHoleResp(inMsg *msg.NatHoleResp) {
xl := ctl.xl
// Dispatch the NatHoleResp message to the related proxy.
ok := ctl.msgTransporter.DispatchWithType(inMsg, msg.TypeNameNatHoleResp, inMsg.TransactionID)
if !ok {
xl.Trace("dispatch NatHoleResp message to related proxy error")
}
}
2017-06-26 19:59:30 +02:00
func (ctl *Control) Close() error {
return ctl.GracefulClose(0)
}
2021-10-19 09:02:45 +02:00
func (ctl *Control) GracefulClose(d time.Duration) error {
2018-12-11 08:06:54 +01:00
ctl.pm.Close()
ctl.vm.Close()
2021-10-19 09:02:45 +02:00
time.Sleep(d)
ctl.conn.Close()
ctl.cm.Close()
2018-01-16 18:09:33 +01:00
return nil
2017-03-08 19:03:47 +01:00
}
// ClosedDoneCh returns a channel that will be closed after all resources are released
2018-11-06 11:35:05 +01:00
func (ctl *Control) ClosedDoneCh() <-chan struct{} {
return ctl.closedDoneCh
2017-03-08 19:03:47 +01:00
}
2018-07-15 19:21:29 +02:00
// connectServer return a new connection to frps
2019-10-12 14:13:12 +02:00
func (ctl *Control) connectServer() (conn net.Conn, err error) {
return ctl.cm.Connect()
2017-06-25 21:02:33 +02:00
}
2018-01-16 18:09:33 +01:00
// reader read all messages from frps and send to readCh
2017-03-08 19:03:47 +01:00
func (ctl *Control) reader() {
2019-10-12 14:13:12 +02:00
xl := ctl.xl
2017-03-08 19:03:47 +01:00
defer func() {
if err := recover(); err != nil {
2019-10-12 14:13:12 +02:00
xl.Error("panic error: %v", err)
xl.Error(string(debug.Stack()))
2017-03-08 19:03:47 +01:00
}
}()
2018-01-16 18:09:33 +01:00
defer ctl.readerShutdown.Done()
2017-03-09 18:42:06 +01:00
defer close(ctl.closedCh)
2017-03-08 19:03:47 +01:00
encReader := crypto.NewReader(ctl.conn, []byte(ctl.clientCfg.Token))
2017-03-08 19:03:47 +01:00
for {
2020-05-24 11:48:37 +02:00
m, err := msg.ReadMsg(encReader)
if err != nil {
2017-03-08 19:03:47 +01:00
if err == io.EOF {
2019-10-12 14:13:12 +02:00
xl.Debug("read from control connection EOF")
2017-03-08 19:03:47 +01:00
return
}
2020-05-24 11:48:37 +02:00
xl.Warn("read error: %v", err)
ctl.conn.Close()
return
2017-03-08 19:03:47 +01:00
}
2020-05-24 11:48:37 +02:00
ctl.readCh <- m
2017-03-08 19:03:47 +01:00
}
}
2018-01-16 18:09:33 +01:00
// writer writes messages got from sendCh to frps
2017-03-08 19:03:47 +01:00
func (ctl *Control) writer() {
2019-10-12 14:13:12 +02:00
xl := ctl.xl
2018-01-16 18:09:33 +01:00
defer ctl.writerShutdown.Done()
encWriter, err := crypto.NewWriter(ctl.conn, []byte(ctl.clientCfg.Token))
2017-03-09 18:42:06 +01:00
if err != nil {
2019-10-12 14:13:12 +02:00
xl.Error("crypto new writer error: %v", err)
2017-03-09 18:42:06 +01:00
ctl.conn.Close()
return
}
2017-03-08 19:03:47 +01:00
for {
2020-05-24 11:48:37 +02:00
m, ok := <-ctl.sendCh
if !ok {
2019-10-12 14:13:12 +02:00
xl.Info("control writer is closing")
2017-03-08 19:03:47 +01:00
return
2020-05-24 11:48:37 +02:00
}
if err := msg.WriteMsg(encWriter, m); err != nil {
xl.Warn("write message to control connection error: %v", err)
return
2017-03-08 19:03:47 +01:00
}
}
}
// msgHandler handles all channel events and performs corresponding operations.
2018-01-16 18:09:33 +01:00
func (ctl *Control) msgHandler() {
2019-10-12 14:13:12 +02:00
xl := ctl.xl
2017-03-08 19:03:47 +01:00
defer func() {
if err := recover(); err != nil {
2019-10-12 14:13:12 +02:00
xl.Error("panic error: %v", err)
xl.Error(string(debug.Stack()))
2017-03-08 19:03:47 +01:00
}
}()
2018-01-16 18:09:33 +01:00
defer ctl.msgHandlerShutdown.Done()
2017-03-08 19:03:47 +01:00
var hbSendCh <-chan time.Time
// TODO(fatedier): disable heartbeat if TCPMux is enabled.
// Just keep it here to keep compatible with old version frps.
if ctl.clientCfg.HeartbeatInterval > 0 {
hbSend := time.NewTicker(time.Duration(ctl.clientCfg.HeartbeatInterval) * time.Second)
defer hbSend.Stop()
hbSendCh = hbSend.C
}
2017-03-08 19:03:47 +01:00
var hbCheckCh <-chan time.Time
// Check heartbeat timeout only if TCPMux is not enabled and users don't disable heartbeat feature.
if ctl.clientCfg.HeartbeatInterval > 0 && ctl.clientCfg.HeartbeatTimeout > 0 && !ctl.clientCfg.TCPMux {
hbCheck := time.NewTicker(time.Second)
defer hbCheck.Stop()
hbCheckCh = hbCheck.C
}
2018-01-16 18:09:33 +01:00
ctl.lastPong = time.Now()
2017-03-08 19:03:47 +01:00
for {
select {
case <-hbSendCh:
2017-03-08 19:03:47 +01:00
// send heartbeat to server
2019-10-12 14:13:12 +02:00
xl.Debug("send heartbeat to server")
pingMsg := &msg.Ping{}
if err := ctl.authSetter.SetPing(pingMsg); err != nil {
xl.Warn("error during ping authentication: %v", err)
return
}
ctl.sendCh <- pingMsg
case <-hbCheckCh:
2020-11-23 04:38:21 +01:00
if time.Since(ctl.lastPong) > time.Duration(ctl.clientCfg.HeartbeatTimeout)*time.Second {
2019-10-12 14:13:12 +02:00
xl.Warn("heartbeat timeout")
2017-03-27 11:25:25 +02:00
// let reader() stop
ctl.conn.Close()
2017-03-08 19:03:47 +01:00
return
}
case rawMsg, ok := <-ctl.readCh:
if !ok {
return
}
switch m := rawMsg.(type) {
case *msg.ReqWorkConn:
2018-01-16 18:09:33 +01:00
go ctl.HandleReqWorkConn(m)
2017-03-08 19:03:47 +01:00
case *msg.NewProxyResp:
2018-01-16 18:09:33 +01:00
ctl.HandleNewProxyResp(m)
case *msg.NatHoleResp:
ctl.HandleNatHoleResp(m)
2017-03-08 19:03:47 +01:00
case *msg.Pong:
if m.Error != "" {
xl.Error("Pong contains error: %s", m.Error)
ctl.conn.Close()
return
}
2017-03-08 19:03:47 +01:00
ctl.lastPong = time.Now()
2019-10-12 14:13:12 +02:00
xl.Debug("receive heartbeat from server")
2017-03-08 19:03:47 +01:00
}
}
}
}
2018-11-06 11:35:05 +01:00
// If controler is notified by closedCh, reader and writer and handler will exit
2018-01-16 18:09:33 +01:00
func (ctl *Control) worker() {
go ctl.msgHandler()
go ctl.reader()
go ctl.writer()
2018-01-16 18:09:33 +01:00
2022-08-28 19:02:53 +02:00
<-ctl.closedCh
// close related channels and wait until other goroutines done
close(ctl.readCh)
ctl.readerShutdown.WaitDone()
ctl.msgHandlerShutdown.WaitDone()
2018-11-06 11:35:05 +01:00
2022-08-28 19:02:53 +02:00
close(ctl.sendCh)
ctl.writerShutdown.WaitDone()
2018-11-06 11:35:05 +01:00
2022-08-28 19:02:53 +02:00
ctl.pm.Close()
ctl.vm.Close()
2018-11-06 11:35:05 +01:00
2022-08-28 19:02:53 +02:00
close(ctl.closedDoneCh)
ctl.cm.Close()
2017-03-08 19:03:47 +01:00
}
2017-06-27 17:30:09 +02:00
2018-11-06 11:35:05 +01:00
func (ctl *Control) ReloadConf(pxyCfgs map[string]config.ProxyConf, visitorCfgs map[string]config.VisitorConf) error {
ctl.vm.Reload(visitorCfgs)
2018-12-07 10:05:36 +01:00
ctl.pm.Reload(pxyCfgs)
return nil
}