SakuraFrp/client/control.go

319 lines
7.9 KiB
Go
Raw Permalink Normal View History

2017-03-08 18:03:47 +00: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-03-11 06:14:31 +00:00
"crypto/tls"
2017-03-08 18:03:47 +00:00
"fmt"
"io"
2018-05-11 02:42:57 +00:00
"runtime/debug"
2017-03-08 18:03:47 +00:00
"sync"
"time"
2018-12-09 14:06:22 +00:00
"github.com/fatedier/frp/client/proxy"
2018-04-10 09:46:49 +00:00
"github.com/fatedier/frp/g"
2017-03-08 18:03:47 +00:00
"github.com/fatedier/frp/models/config"
"github.com/fatedier/frp/models/msg"
"github.com/fatedier/frp/utils/log"
2017-06-25 19:02:33 +00:00
frpNet "github.com/fatedier/frp/utils/net"
2018-04-24 18:34:07 +00:00
2018-05-08 15:51:13 +00:00
"github.com/fatedier/golib/control/shutdown"
2018-05-07 18:13:30 +00:00
"github.com/fatedier/golib/crypto"
2018-04-24 18:34:07 +00:00
fmux "github.com/hashicorp/yamux"
2017-03-08 18:03:47 +00:00
)
type Control struct {
2018-11-06 10:35:05 +00:00
// uniq id got from frps, attach it in loginMsg
runId string
2017-03-08 18:03:47 +00:00
// manage all proxies
2018-12-07 09:05:36 +00:00
pxyCfgs map[string]config.ProxyConf
2018-12-09 14:06:22 +00:00
pm *proxy.ProxyManager
2017-06-25 19:02:33 +00:00
// manage all visitors
vm *VisitorManager
2017-03-08 18:03:47 +00:00
// control connection
2017-06-25 19:02:33 +00:00
conn frpNet.Conn
2017-03-08 18:03:47 +00:00
// tcp stream multiplexing, if enabled
2018-04-24 18:34:07 +00:00
session *fmux.Session
2017-03-08 18:03:47 +00: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 10:35:05 +00:00
closedCh chan struct{}
closedDoneCh chan struct{}
2017-03-08 18:03:47 +00:00
// last time got the Pong message
lastPong time.Time
2018-01-16 17:09:33 +00:00
readerShutdown *shutdown.Shutdown
writerShutdown *shutdown.Shutdown
msgHandlerShutdown *shutdown.Shutdown
2017-03-08 18:03:47 +00:00
mu sync.RWMutex
log.Logger
}
2018-11-06 10:35:05 +00:00
func NewControl(runId string, conn frpNet.Conn, session *fmux.Session, pxyCfgs map[string]config.ProxyConf, visitorCfgs map[string]config.VisitorConf) *Control {
2018-01-16 17:09:33 +00:00
ctl := &Control{
2018-11-06 10:35:05 +00:00
runId: runId,
conn: conn,
session: session,
2018-12-07 09:05:36 +00:00
pxyCfgs: pxyCfgs,
sendCh: make(chan msg.Message, 100),
readCh: make(chan msg.Message, 100),
2018-11-06 10:35:05 +00:00
closedCh: make(chan struct{}),
closedDoneCh: make(chan struct{}),
2018-01-16 17:09:33 +00:00
readerShutdown: shutdown.New(),
writerShutdown: shutdown.New(),
msgHandlerShutdown: shutdown.New(),
Logger: log.NewPrefixLogger(""),
2017-03-08 18:03:47 +00:00
}
2018-12-09 14:06:22 +00:00
ctl.pm = proxy.NewProxyManager(ctl.sendCh, runId)
2018-12-07 09:05:36 +00:00
ctl.vm = NewVisitorManager(ctl)
ctl.vm.Reload(visitorCfgs)
2018-01-16 17:09:33 +00:00
return ctl
2017-03-08 18:03:47 +00:00
}
2018-11-06 10:35:05 +00:00
func (ctl *Control) Run() {
2018-01-16 17:09:33 +00:00
go ctl.worker()
2017-06-27 15:30:09 +00:00
2018-12-07 09:05:36 +00:00
// start all proxies
ctl.pm.Reload(ctl.pxyCfgs)
2018-12-07 09:05:36 +00:00
// start all visitors
go ctl.vm.Run()
2018-11-06 10:35:05 +00:00
return
2017-06-25 19:02:33 +00:00
}
2018-01-16 17:09:33 +00:00
func (ctl *Control) HandleReqWorkConn(inMsg *msg.ReqWorkConn) {
2017-06-25 19:02:33 +00:00
workConn, err := ctl.connectServer()
if err != nil {
return
2017-03-08 18:03:47 +00:00
}
m := &msg.NewWorkConn{
2018-01-16 17:09:33 +00:00
RunId: ctl.runId,
2017-03-08 18:03:47 +00:00
}
if err = msg.WriteMsg(workConn, m); err != nil {
ctl.Warn("work connection write to server error: %v", err)
workConn.Close()
return
}
var startMsg msg.StartWorkConn
if err = msg.ReadMsgInto(workConn, &startMsg); err != nil {
2017-03-09 17:42:06 +00:00
ctl.Error("work connection closed, %v", err)
2017-03-08 18:03:47 +00:00
workConn.Close()
return
}
workConn.AddLogPrefix(startMsg.ProxyName)
// dispatch this work connection to related proxy
2019-03-29 11:01:18 +00:00
ctl.pm.HandleWorkConn(startMsg.ProxyName, workConn, &startMsg)
2018-01-16 17:09:33 +00:00
}
func (ctl *Control) HandleNewProxyResp(inMsg *msg.NewProxyResp) {
// Server will return NewProxyResp message to each NewProxy message.
// Start a new proxy handler if no error got
2018-01-17 06:40:08 +00:00
err := ctl.pm.StartProxy(inMsg.ProxyName, inMsg.RemoteAddr, inMsg.Error)
2018-01-16 17:09:33 +00:00
if err != nil {
ctl.Warn("[%s] start error: %v", inMsg.ProxyName, err)
2017-03-12 18:44:47 +00:00
} else {
2018-01-16 17:09:33 +00:00
ctl.Info("[%s] start proxy success", inMsg.ProxyName)
2017-03-08 18:03:47 +00:00
}
}
2017-06-26 17:59:30 +00:00
func (ctl *Control) Close() error {
2018-12-11 07:06:54 +00:00
ctl.pm.Close()
2018-12-07 09:05:36 +00:00
ctl.conn.Close()
2019-04-08 07:39:14 +00:00
if ctl.session != nil {
ctl.session.Close()
}
2018-01-16 17:09:33 +00:00
return nil
2017-03-08 18:03:47 +00:00
}
2018-11-06 10:35:05 +00:00
// ClosedDoneCh returns a channel which will be closed after all resources are released
func (ctl *Control) ClosedDoneCh() <-chan struct{} {
return ctl.closedDoneCh
2017-03-08 18:03:47 +00:00
}
2018-07-15 17:21:29 +00:00
// connectServer return a new connection to frps
2017-06-25 19:02:33 +00:00
func (ctl *Control) connectServer() (conn frpNet.Conn, err error) {
2018-04-10 09:46:49 +00:00
if g.GlbClientCfg.TcpMux {
2017-06-25 19:02:33 +00:00
stream, errRet := ctl.session.OpenStream()
if errRet != nil {
err = errRet
ctl.Warn("start new connection to server error: %v", err)
return
}
conn = frpNet.WrapConn(stream)
} else {
2019-03-11 06:14:31 +00:00
var tlsConfig *tls.Config
if g.GlbClientCfg.TLSEnable {
tlsConfig = &tls.Config{
InsecureSkipVerify: true,
}
}
conn, err = frpNet.ConnectServerByProxyWithTLS(g.GlbClientCfg.HttpProxy, g.GlbClientCfg.Protocol,
fmt.Sprintf("%s:%d", g.GlbClientCfg.ServerAddr, g.GlbClientCfg.ServerPort), tlsConfig)
2017-06-25 19:02:33 +00:00
if err != nil {
ctl.Warn("start new connection to server error: %v", err)
return
}
}
return
}
2018-01-16 17:09:33 +00:00
// reader read all messages from frps and send to readCh
2017-03-08 18:03:47 +00:00
func (ctl *Control) reader() {
defer func() {
if err := recover(); err != nil {
ctl.Error("panic error: %v", err)
2018-05-11 02:42:57 +00:00
ctl.Error(string(debug.Stack()))
2017-03-08 18:03:47 +00:00
}
}()
2018-01-16 17:09:33 +00:00
defer ctl.readerShutdown.Done()
2017-03-09 17:42:06 +00:00
defer close(ctl.closedCh)
2017-03-08 18:03:47 +00:00
2018-04-10 09:46:49 +00:00
encReader := crypto.NewReader(ctl.conn, []byte(g.GlbClientCfg.Token))
2017-03-08 18:03:47 +00:00
for {
2017-03-09 17:42:06 +00:00
if m, err := msg.ReadMsg(encReader); err != nil {
2017-03-08 18:03:47 +00:00
if err == io.EOF {
ctl.Debug("read from control connection EOF")
return
} else {
ctl.Warn("read error: %v", err)
2019-04-08 07:39:14 +00:00
ctl.conn.Close()
2017-03-27 09:25:25 +00:00
return
2017-03-08 18:03:47 +00:00
}
} else {
ctl.readCh <- m
}
}
}
2018-01-16 17:09:33 +00:00
// writer writes messages got from sendCh to frps
2017-03-08 18:03:47 +00:00
func (ctl *Control) writer() {
2018-01-16 17:09:33 +00:00
defer ctl.writerShutdown.Done()
2018-04-10 09:46:49 +00:00
encWriter, err := crypto.NewWriter(ctl.conn, []byte(g.GlbClientCfg.Token))
2017-03-09 17:42:06 +00:00
if err != nil {
ctl.conn.Error("crypto new writer error: %v", err)
ctl.conn.Close()
return
}
2017-03-08 18:03:47 +00:00
for {
if m, ok := <-ctl.sendCh; !ok {
ctl.Info("control writer is closing")
return
} else {
2017-03-09 17:42:06 +00:00
if err := msg.WriteMsg(encWriter, m); err != nil {
2017-03-08 18:03:47 +00:00
ctl.Warn("write message to control connection error: %v", err)
return
}
}
}
}
2018-01-16 17:09:33 +00:00
// msgHandler handles all channel events and do corresponding operations.
func (ctl *Control) msgHandler() {
2017-03-08 18:03:47 +00:00
defer func() {
if err := recover(); err != nil {
ctl.Error("panic error: %v", err)
2018-05-11 02:42:57 +00:00
ctl.Error(string(debug.Stack()))
2017-03-08 18:03:47 +00:00
}
}()
2018-01-16 17:09:33 +00:00
defer ctl.msgHandlerShutdown.Done()
2017-03-08 18:03:47 +00:00
2018-04-10 09:46:49 +00:00
hbSend := time.NewTicker(time.Duration(g.GlbClientCfg.HeartBeatInterval) * time.Second)
2017-03-08 18:03:47 +00:00
defer hbSend.Stop()
hbCheck := time.NewTicker(time.Second)
defer hbCheck.Stop()
2018-01-16 17:09:33 +00:00
ctl.lastPong = time.Now()
2017-03-08 18:03:47 +00:00
for {
select {
case <-hbSend.C:
// send heartbeat to server
2017-03-27 09:25:25 +00:00
ctl.Debug("send heartbeat to server")
2017-03-08 18:03:47 +00:00
ctl.sendCh <- &msg.Ping{}
case <-hbCheck.C:
2018-04-10 09:46:49 +00:00
if time.Since(ctl.lastPong) > time.Duration(g.GlbClientCfg.HeartBeatTimeout)*time.Second {
2017-03-08 18:03:47 +00:00
ctl.Warn("heartbeat timeout")
2017-03-27 09:25:25 +00:00
// let reader() stop
ctl.conn.Close()
2017-03-08 18:03:47 +00:00
return
}
case rawMsg, ok := <-ctl.readCh:
if !ok {
return
}
switch m := rawMsg.(type) {
case *msg.ReqWorkConn:
2018-01-16 17:09:33 +00:00
go ctl.HandleReqWorkConn(m)
2017-03-08 18:03:47 +00:00
case *msg.NewProxyResp:
2018-01-16 17:09:33 +00:00
ctl.HandleNewProxyResp(m)
2017-03-08 18:03:47 +00:00
case *msg.Pong:
ctl.lastPong = time.Now()
2017-03-27 09:25:25 +00:00
ctl.Debug("receive heartbeat from server")
2017-03-08 18:03:47 +00:00
}
}
}
}
2018-11-06 10:35:05 +00:00
// If controler is notified by closedCh, reader and writer and handler will exit
2018-01-16 17:09:33 +00:00
func (ctl *Control) worker() {
go ctl.msgHandler()
go ctl.reader()
go ctl.writer()
2018-01-16 17:09:33 +00:00
2018-12-07 09:05:36 +00:00
select {
case <-ctl.closedCh:
// close related channels and wait until other goroutines done
close(ctl.readCh)
ctl.readerShutdown.WaitDone()
ctl.msgHandlerShutdown.WaitDone()
2018-11-06 10:35:05 +00:00
2018-12-07 09:05:36 +00:00
close(ctl.sendCh)
ctl.writerShutdown.WaitDone()
2018-11-06 10:35:05 +00:00
2018-12-07 09:05:36 +00:00
ctl.pm.Close()
ctl.vm.Close()
2018-11-06 10:35:05 +00:00
2018-12-07 09:05:36 +00:00
close(ctl.closedDoneCh)
2019-04-08 07:39:14 +00:00
if ctl.session != nil {
ctl.session.Close()
}
2018-12-07 09:05:36 +00:00
return
2017-03-08 18:03:47 +00:00
}
}
2017-06-27 15:30:09 +00:00
2018-11-06 10:35:05 +00:00
func (ctl *Control) ReloadConf(pxyCfgs map[string]config.ProxyConf, visitorCfgs map[string]config.VisitorConf) error {
ctl.vm.Reload(visitorCfgs)
2018-12-07 09:05:36 +00:00
ctl.pm.Reload(pxyCfgs)
return nil
}