frp/client/control.go

623 lines
15 KiB
Go
Raw Normal View History

2017-03-09 02:03:47 +08: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 (
"fmt"
"io"
"runtime"
"sync"
"time"
"github.com/fatedier/frp/models/config"
"github.com/fatedier/frp/models/msg"
2017-03-10 01:42:06 +08:00
"github.com/fatedier/frp/utils/crypto"
2017-06-27 01:59:30 +08:00
"github.com/fatedier/frp/utils/errors"
2017-03-09 02:03:47 +08:00
"github.com/fatedier/frp/utils/log"
2017-06-26 03:02:33 +08:00
frpNet "github.com/fatedier/frp/utils/net"
2017-03-09 02:03:47 +08:00
"github.com/fatedier/frp/utils/util"
"github.com/fatedier/frp/utils/version"
"github.com/xtaci/smux"
2017-03-09 02:03:47 +08:00
)
2017-05-10 00:46:42 +08:00
const (
connReadTimeout time.Duration = 10 * time.Second
)
2017-03-09 02:03:47 +08:00
type Control struct {
// frpc service
svr *Service
// login message to server
loginMsg *msg.Login
// proxy configures
pxyCfgs map[string]config.ProxyConf
// proxies
proxies map[string]Proxy
2017-12-05 01:34:33 +08:00
// visitor configures
visitorCfgs map[string]config.ProxyConf
2017-06-26 03:02:33 +08:00
2017-12-05 01:34:33 +08:00
// visitors
visitors map[string]Visitor
2017-06-26 03:02:33 +08:00
2017-03-09 02:03:47 +08:00
// control connection
2017-06-26 03:02:33 +08:00
conn frpNet.Conn
2017-03-09 02:03:47 +08:00
// tcp stream multiplexing, if enabled
session *smux.Session
2017-03-09 02:03:47 +08: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)
// run id got from server
runId string
2017-06-27 01:59:30 +08:00
// if we call close() in control, do not reconnect to server
exit bool
2017-03-09 02:03:47 +08:00
// goroutines can block by reading from this channel, it will be closed only in reader() when control connection is closed
closedCh chan int
// last time got the Pong message
lastPong time.Time
mu sync.RWMutex
log.Logger
}
2017-12-05 01:34:33 +08:00
func NewControl(svr *Service, pxyCfgs map[string]config.ProxyConf, visitorCfgs map[string]config.ProxyConf) *Control {
2017-03-09 02:03:47 +08:00
loginMsg := &msg.Login{
Arch: runtime.GOARCH,
Os: runtime.GOOS,
PoolCount: config.ClientCommonCfg.PoolCount,
User: config.ClientCommonCfg.User,
Version: version.Full(),
}
return &Control{
2017-12-05 01:34:33 +08:00
svr: svr,
loginMsg: loginMsg,
pxyCfgs: pxyCfgs,
visitorCfgs: visitorCfgs,
proxies: make(map[string]Proxy),
visitors: make(map[string]Visitor),
sendCh: make(chan msg.Message, 10),
readCh: make(chan msg.Message, 10),
closedCh: make(chan int),
Logger: log.NewPrefixLogger(""),
2017-03-09 02:03:47 +08:00
}
}
// 1. login
// 2. start reader() writer() manager()
// 3. connection closed
// 4. In reader(): close closedCh and exit, controler() get it
// 5. In controler(): close readCh and sendCh, manager() and writer() will exit
// 6. In controler(): ini readCh, sendCh, closedCh
// 7. In controler(): start new reader(), writer(), manager()
// controler() will keep running
2017-06-26 03:02:33 +08:00
func (ctl *Control) Run() (err error) {
for {
2017-06-26 03:02:33 +08:00
err = ctl.login()
if err != nil {
2017-06-26 03:02:33 +08:00
ctl.Warn("login to server failed: %v", err)
// if login_fail_exit is true, just exit this program
// otherwise sleep a while and continues relogin to server
if config.ClientCommonCfg.LoginFailExit {
2017-06-26 03:02:33 +08:00
return
} else {
time.Sleep(30 * time.Second)
}
} else {
break
}
2017-03-09 02:03:47 +08:00
}
go ctl.controler()
go ctl.manager()
go ctl.writer()
go ctl.reader()
2017-12-05 01:34:33 +08:00
// start all local visitors
for _, cfg := range ctl.visitorCfgs {
visitor := NewVisitor(ctl, cfg)
err = visitor.Run()
if err != nil {
2017-12-05 01:34:33 +08:00
visitor.Warn("start error: %v", err)
2017-06-26 03:02:33 +08:00
continue
}
2017-12-05 01:34:33 +08:00
ctl.visitors[cfg.GetName()] = visitor
visitor.Info("start visitor success")
2017-06-26 03:02:33 +08:00
}
2017-06-27 23:30:09 +08:00
// send NewProxy message for all configured proxies
for _, cfg := range ctl.pxyCfgs {
var newProxyMsg msg.NewProxy
cfg.UnMarshalToMsg(&newProxyMsg)
ctl.sendCh <- &newProxyMsg
}
2017-06-26 03:02:33 +08:00
return nil
}
2017-06-26 03:02:33 +08:00
func (ctl *Control) NewWorkConn() {
workConn, err := ctl.connectServer()
if err != nil {
return
2017-03-09 02:03:47 +08:00
}
m := &msg.NewWorkConn{
2017-06-27 23:30:09 +08:00
RunId: ctl.getRunId(),
2017-03-09 02:03:47 +08: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-10 01:42:06 +08:00
ctl.Error("work connection closed, %v", err)
2017-03-09 02:03:47 +08:00
workConn.Close()
return
}
workConn.AddLogPrefix(startMsg.ProxyName)
// dispatch this work connection to related proxy
2017-06-27 23:30:09 +08:00
pxy, ok := ctl.getProxy(startMsg.ProxyName)
2017-06-27 01:59:30 +08:00
if ok {
workConn.Debug("start a new work connection, localAddr: %s remoteAddr: %s", workConn.LocalAddr().String(), workConn.RemoteAddr().String())
2017-04-25 00:34:14 +08:00
go pxy.InWorkConn(workConn)
2017-03-13 02:44:47 +08:00
} else {
workConn.Close()
2017-03-09 02:03:47 +08:00
}
}
2017-06-27 01:59:30 +08:00
func (ctl *Control) Close() error {
ctl.mu.Lock()
ctl.exit = true
err := errors.PanicToError(func() {
for name, _ := range ctl.proxies {
ctl.sendCh <- &msg.CloseProxy{
ProxyName: name,
}
}
})
ctl.mu.Unlock()
return err
}
2017-03-09 02:03:47 +08:00
func (ctl *Control) init() {
ctl.sendCh = make(chan msg.Message, 10)
ctl.readCh = make(chan msg.Message, 10)
ctl.closedCh = make(chan int)
}
// login send a login message to server and wait for a loginResp message.
func (ctl *Control) login() (err error) {
if ctl.conn != nil {
ctl.conn.Close()
}
if ctl.session != nil {
ctl.session.Close()
}
2017-06-26 03:02:33 +08:00
conn, err := frpNet.ConnectServerByHttpProxy(config.ClientCommonCfg.HttpProxy, config.ClientCommonCfg.Protocol,
2017-03-09 02:03:47 +08:00
fmt.Sprintf("%s:%d", config.ClientCommonCfg.ServerAddr, config.ClientCommonCfg.ServerPort))
if err != nil {
return err
}
2017-05-10 00:46:42 +08:00
defer func() {
if err != nil {
conn.Close()
}
}()
if config.ClientCommonCfg.TcpMux {
session, errRet := smux.Client(conn, nil)
if errRet != nil {
return errRet
}
stream, errRet := session.OpenStream()
if errRet != nil {
session.Close()
return errRet
}
2017-06-26 03:02:33 +08:00
conn = frpNet.WrapConn(stream)
ctl.session = session
}
2017-03-09 02:03:47 +08:00
now := time.Now().Unix()
ctl.loginMsg.PrivilegeKey = util.GetAuthKey(config.ClientCommonCfg.PrivilegeToken, now)
ctl.loginMsg.Timestamp = now
2017-06-27 23:30:09 +08:00
ctl.loginMsg.RunId = ctl.getRunId()
2017-03-09 02:03:47 +08:00
if err = msg.WriteMsg(conn, ctl.loginMsg); err != nil {
return err
}
var loginRespMsg msg.LoginResp
2017-05-10 00:46:42 +08:00
conn.SetReadDeadline(time.Now().Add(connReadTimeout))
2017-03-09 02:03:47 +08:00
if err = msg.ReadMsgInto(conn, &loginRespMsg); err != nil {
return err
}
2017-05-10 00:46:42 +08:00
conn.SetReadDeadline(time.Time{})
2017-03-09 02:03:47 +08:00
if loginRespMsg.Error != "" {
err = fmt.Errorf("%s", loginRespMsg.Error)
ctl.Error("%s", loginRespMsg.Error)
return err
}
ctl.conn = conn
// update runId got from server
2017-06-27 23:30:09 +08:00
ctl.setRunId(loginRespMsg.RunId)
2017-10-24 18:20:07 +08:00
config.ClientCommonCfg.ServerUdpPort = loginRespMsg.ServerUdpPort
2017-03-09 02:03:47 +08:00
ctl.ClearLogPrefix()
ctl.AddLogPrefix(loginRespMsg.RunId)
2017-10-24 18:20:07 +08:00
ctl.Info("login to server success, get run id [%s], server udp port [%d]", loginRespMsg.RunId, loginRespMsg.ServerUdpPort)
2017-03-09 02:03:47 +08:00
// login success, so we let closedCh available again
ctl.closedCh = make(chan int)
ctl.lastPong = time.Now()
return nil
}
2017-06-26 03:02:33 +08:00
func (ctl *Control) connectServer() (conn frpNet.Conn, err error) {
if config.ClientCommonCfg.TcpMux {
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 {
conn, err = frpNet.ConnectServerByHttpProxy(config.ClientCommonCfg.HttpProxy, config.ClientCommonCfg.Protocol,
fmt.Sprintf("%s:%d", config.ClientCommonCfg.ServerAddr, config.ClientCommonCfg.ServerPort))
if err != nil {
ctl.Warn("start new connection to server error: %v", err)
return
}
}
return
}
2017-03-09 02:03:47 +08:00
func (ctl *Control) reader() {
defer func() {
if err := recover(); err != nil {
ctl.Error("panic error: %v", err)
}
}()
2017-03-10 01:42:06 +08:00
defer close(ctl.closedCh)
2017-03-09 02:03:47 +08:00
2017-03-10 02:01:17 +08:00
encReader := crypto.NewReader(ctl.conn, []byte(config.ClientCommonCfg.PrivilegeToken))
2017-03-09 02:03:47 +08:00
for {
2017-03-10 01:42:06 +08:00
if m, err := msg.ReadMsg(encReader); err != nil {
2017-03-09 02:03:47 +08:00
if err == io.EOF {
ctl.Debug("read from control connection EOF")
return
} else {
ctl.Warn("read error: %v", err)
2017-03-27 17:25:25 +08:00
return
2017-03-09 02:03:47 +08:00
}
} else {
ctl.readCh <- m
}
}
}
func (ctl *Control) writer() {
2017-03-10 01:42:06 +08:00
encWriter, err := crypto.NewWriter(ctl.conn, []byte(config.ClientCommonCfg.PrivilegeToken))
if err != nil {
ctl.conn.Error("crypto new writer error: %v", err)
ctl.conn.Close()
return
}
2017-03-09 02:03:47 +08:00
for {
if m, ok := <-ctl.sendCh; !ok {
ctl.Info("control writer is closing")
return
} else {
2017-03-10 01:42:06 +08:00
if err := msg.WriteMsg(encWriter, m); err != nil {
2017-03-09 02:03:47 +08:00
ctl.Warn("write message to control connection error: %v", err)
return
}
}
}
}
2017-06-27 23:30:09 +08:00
// manager handles all channel events and do corresponding process
2017-03-09 02:03:47 +08:00
func (ctl *Control) manager() {
defer func() {
if err := recover(); err != nil {
ctl.Error("panic error: %v", err)
}
}()
hbSend := time.NewTicker(time.Duration(config.ClientCommonCfg.HeartBeatInterval) * time.Second)
defer hbSend.Stop()
hbCheck := time.NewTicker(time.Second)
defer hbCheck.Stop()
for {
select {
case <-hbSend.C:
// send heartbeat to server
2017-03-27 17:25:25 +08:00
ctl.Debug("send heartbeat to server")
2017-03-09 02:03:47 +08:00
ctl.sendCh <- &msg.Ping{}
case <-hbCheck.C:
if time.Since(ctl.lastPong) > time.Duration(config.ClientCommonCfg.HeartBeatTimeout)*time.Second {
ctl.Warn("heartbeat timeout")
2017-03-27 17:25:25 +08:00
// let reader() stop
ctl.conn.Close()
2017-03-09 02:03:47 +08:00
return
}
case rawMsg, ok := <-ctl.readCh:
if !ok {
return
}
switch m := rawMsg.(type) {
case *msg.ReqWorkConn:
go ctl.NewWorkConn()
case *msg.NewProxyResp:
// Server will return NewProxyResp message to each NewProxy message.
// Start a new proxy handler if no error got
if m.Error != "" {
ctl.Warn("[%s] start error: %s", m.ProxyName, m.Error)
continue
}
cfg, ok := ctl.getProxyConf(m.ProxyName)
2017-03-09 02:03:47 +08:00
if !ok {
2017-04-25 00:34:14 +08:00
// it will never go to this branch now
2017-03-09 02:03:47 +08:00
ctl.Warn("[%s] no proxy conf found", m.ProxyName)
continue
}
2017-06-27 01:59:30 +08:00
2017-06-27 23:30:09 +08:00
oldPxy, ok := ctl.getProxy(m.ProxyName)
2017-03-12 02:03:24 +08:00
if ok {
oldPxy.Close()
}
2017-03-09 02:03:47 +08:00
pxy := NewProxy(ctl, cfg)
2017-03-12 02:03:24 +08:00
if err := pxy.Run(); err != nil {
ctl.Warn("[%s] proxy start running error: %v", m.ProxyName, err)
2017-06-11 17:22:05 +08:00
ctl.sendCh <- &msg.CloseProxy{
ProxyName: m.ProxyName,
}
2017-03-12 02:03:24 +08:00
continue
}
2017-06-27 23:30:09 +08:00
ctl.addProxy(m.ProxyName, pxy)
2017-03-09 02:03:47 +08:00
ctl.Info("[%s] start proxy success", m.ProxyName)
case *msg.Pong:
ctl.lastPong = time.Now()
2017-03-27 17:25:25 +08:00
ctl.Debug("receive heartbeat from server")
2017-03-09 02:03:47 +08:00
}
}
}
}
2017-06-27 23:30:09 +08:00
// controler keep watching closedCh, start a new connection if previous control connection is closed.
// If controler is notified by closedCh, reader and writer and manager will exit, then recall these functions.
2017-03-09 02:03:47 +08:00
func (ctl *Control) controler() {
var err error
maxDelayTime := 30 * time.Second
delayTime := time.Second
2017-03-12 02:03:24 +08:00
checkInterval := 10 * time.Second
2017-03-12 02:03:24 +08:00
checkProxyTicker := time.NewTicker(checkInterval)
2017-03-09 02:03:47 +08:00
for {
2017-03-12 02:03:24 +08:00
select {
case <-checkProxyTicker.C:
// Every 10 seconds, check which proxy registered failed and reregister it to server.
ctl.mu.RLock()
2017-03-12 02:03:24 +08:00
for _, cfg := range ctl.pxyCfgs {
if _, exist := ctl.proxies[cfg.GetName()]; !exist {
ctl.Info("try to register proxy [%s]", cfg.GetName())
2017-03-12 02:03:24 +08:00
var newProxyMsg msg.NewProxy
cfg.UnMarshalToMsg(&newProxyMsg)
ctl.sendCh <- &newProxyMsg
2017-03-09 02:03:47 +08:00
}
}
2017-12-05 01:34:33 +08:00
for _, cfg := range ctl.visitorCfgs {
if _, exist := ctl.visitors[cfg.GetName()]; !exist {
ctl.Info("try to start visitor [%s]", cfg.GetName())
visitor := NewVisitor(ctl, cfg)
err = visitor.Run()
if err != nil {
2017-12-05 01:34:33 +08:00
visitor.Warn("start error: %v", err)
continue
}
2017-12-05 01:34:33 +08:00
ctl.visitors[cfg.GetName()] = visitor
visitor.Info("start visitor success")
}
}
ctl.mu.RUnlock()
2017-03-12 02:03:24 +08:00
case _, ok := <-ctl.closedCh:
// we won't get any variable from this channel
if !ok {
// close related channels
close(ctl.readCh)
close(ctl.sendCh)
2017-04-25 00:34:14 +08:00
for _, pxy := range ctl.proxies {
pxy.Close()
}
2017-06-27 01:59:30 +08:00
// if ctl.exit is true, just exit
ctl.mu.RLock()
exit := ctl.exit
ctl.mu.RUnlock()
if exit {
return
}
2017-03-12 02:03:24 +08:00
time.Sleep(time.Second)
// loop util reconnect to server success
for {
ctl.Info("try to reconnect to server...")
err = ctl.login()
if err != nil {
ctl.Warn("reconnect to server error: %v", err)
time.Sleep(delayTime)
delayTime = delayTime * 2
if delayTime > maxDelayTime {
delayTime = maxDelayTime
}
continue
}
// reconnect success, init the delayTime
delayTime = time.Second
break
}
2017-03-09 02:03:47 +08:00
2017-03-12 02:03:24 +08:00
// init related channels and variables
ctl.init()
2017-03-09 02:03:47 +08:00
2017-03-12 02:03:24 +08:00
// previous work goroutines should be closed and start them here
go ctl.manager()
go ctl.writer()
go ctl.reader()
2017-03-09 02:03:47 +08:00
2017-03-12 02:03:24 +08:00
// send NewProxy message for all configured proxies
ctl.mu.RLock()
2017-03-12 02:03:24 +08:00
for _, cfg := range ctl.pxyCfgs {
var newProxyMsg msg.NewProxy
cfg.UnMarshalToMsg(&newProxyMsg)
ctl.sendCh <- &newProxyMsg
}
ctl.mu.RUnlock()
2017-03-12 02:03:24 +08:00
checkProxyTicker.Stop()
checkProxyTicker = time.NewTicker(checkInterval)
2017-03-09 02:03:47 +08:00
}
}
}
}
2017-06-27 23:30:09 +08:00
func (ctl *Control) setRunId(runId string) {
ctl.mu.Lock()
defer ctl.mu.Unlock()
ctl.runId = runId
}
func (ctl *Control) getRunId() string {
ctl.mu.RLock()
defer ctl.mu.RUnlock()
return ctl.runId
}
func (ctl *Control) getProxy(name string) (pxy Proxy, ok bool) {
ctl.mu.RLock()
defer ctl.mu.RUnlock()
pxy, ok = ctl.proxies[name]
return
}
func (ctl *Control) addProxy(name string, pxy Proxy) {
ctl.mu.Lock()
defer ctl.mu.Unlock()
ctl.proxies[name] = pxy
}
func (ctl *Control) getProxyConf(name string) (conf config.ProxyConf, ok bool) {
ctl.mu.RLock()
defer ctl.mu.RUnlock()
conf, ok = ctl.pxyCfgs[name]
return
}
2017-12-05 01:34:33 +08:00
func (ctl *Control) reloadConf(pxyCfgs map[string]config.ProxyConf, visitorCfgs map[string]config.ProxyConf) {
ctl.mu.Lock()
defer ctl.mu.Unlock()
removedPxyNames := make([]string, 0)
for name, oldCfg := range ctl.pxyCfgs {
del := false
cfg, ok := pxyCfgs[name]
if !ok {
del = true
} else {
if !oldCfg.Compare(cfg) {
del = true
}
}
if del {
removedPxyNames = append(removedPxyNames, name)
delete(ctl.pxyCfgs, name)
if pxy, ok := ctl.proxies[name]; ok {
pxy.Close()
}
delete(ctl.proxies, name)
ctl.sendCh <- &msg.CloseProxy{
ProxyName: name,
}
}
}
ctl.Info("proxy removed: %v", removedPxyNames)
addedPxyNames := make([]string, 0)
for name, cfg := range pxyCfgs {
if _, ok := ctl.pxyCfgs[name]; !ok {
ctl.pxyCfgs[name] = cfg
addedPxyNames = append(addedPxyNames, name)
}
}
ctl.Info("proxy added: %v", addedPxyNames)
2017-12-05 01:34:33 +08:00
removedVisitorName := make([]string, 0)
for name, oldVisitorCfg := range ctl.visitorCfgs {
del := false
2017-12-05 01:34:33 +08:00
cfg, ok := visitorCfgs[name]
if !ok {
del = true
} else {
2017-12-05 01:34:33 +08:00
if !oldVisitorCfg.Compare(cfg) {
del = true
}
}
if del {
2017-12-05 01:34:33 +08:00
removedVisitorName = append(removedVisitorName, name)
delete(ctl.visitorCfgs, name)
if visitor, ok := ctl.visitors[name]; ok {
visitor.Close()
}
2017-12-05 01:34:33 +08:00
delete(ctl.visitors, name)
}
}
2017-12-05 01:34:33 +08:00
ctl.Info("visitor removed: %v", removedVisitorName)
2017-12-05 01:34:33 +08:00
addedVisitorName := make([]string, 0)
for name, visitorCfg := range visitorCfgs {
if _, ok := ctl.visitorCfgs[name]; !ok {
ctl.visitorCfgs[name] = visitorCfg
addedVisitorName = append(addedVisitorName, name)
}
}
2017-12-05 01:34:33 +08:00
ctl.Info("visitor added: %v", addedVisitorName)
}