| // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 |
| 15 | package client |
| 16 |
| 17 | import ( |
| 18 | "context" |
| 19 | "net" |
| 20 | "sync/atomic" |
| 21 | "time" |
| 22 |
| 23 | "github.com/fatedier/frp/client/proxy" |
| 24 | "github.com/fatedier/frp/client/visitor" |
| 25 | "github.com/fatedier/frp/pkg/auth" |
| 26 | v1 "github.com/fatedier/frp/pkg/config/v1" |
| 27 | "github.com/fatedier/frp/pkg/msg" |
| 28 | "github.com/fatedier/frp/pkg/naming" |
| 29 | "github.com/fatedier/frp/pkg/transport" |
| 30 | "github.com/fatedier/frp/pkg/util/wait" |
| 31 | "github.com/fatedier/frp/pkg/util/xlog" |
| 32 | "github.com/fatedier/frp/pkg/vnet" |
| 33 | ) |
| 34 |
| 35 | type SessionContext struct { |
| 36 | // The client common configuration. |
| 37 | Common *v1.ClientCommonConfig |
| 38 |
| 39 | // Unique ID obtained from frps. |
| 40 | // It should be attached to the login message when reconnecting. |
| 41 | RunID string |
| 42 | // Underlying control connection. Once conn is closed, the msgDispatcher and the entire Control will exit. |
| 43 | Conn *msg.Conn |
| 44 | // Auth runtime used for login, heartbeats, and encryption. |
| 45 | Auth *auth.ClientAuth |
| 46 | // Connector is used to create message connections to frps. |
| 47 | Connector MessageConnector |
| 48 | // Virtual net controller |
| 49 | VnetController *vnet.Controller |
| 50 | } |
| 51 |
| 52 | type Control struct { |
| 53 | // service context |
| 54 | ctx context.Context |
| 55 | xl *xlog.Logger |
| 56 |
| 57 | // session context |
| 58 | sessionCtx *SessionContext |
| 59 |
| 60 | // manage all proxies |
| 61 | pm *proxy.Manager |
| 62 |
| 63 | // manage all visitors |
| 64 | vm *visitor.Manager |
| 65 |
| 66 | doneCh chan struct{} |
| 67 |
| 68 | // of time.Time, last time got the Pong message |
| 69 | lastPong atomic.Value |
| 70 |
| 71 | // The role of msgTransporter is similar to HTTP2. |
| 72 | // It allows multiple messages to be sent simultaneously on the same control connection. |
| 73 | // The server's response messages will be dispatched to the corresponding waiting goroutines based on the laneKey and message type. |
| 74 | msgTransporter transport.MessageTransporter |
| 75 |
| 76 | // msgDispatcher is a wrapper for control connection. |
| 77 | // It provides a channel for sending messages, and you can register handlers to process messages based on their respective types. |
| 78 | msgDispatcher *msg.Dispatcher |
| 79 | } |
| 80 |
| 81 | func NewControl(ctx context.Context, sessionCtx *SessionContext) (*Control, error) { |
| 82 | // new xlog instance |
| 83 | ctl := &Control{ |
| 84 | ctx: ctx, |
| 85 | xl: xlog.FromContextSafe(ctx), |
| 86 | sessionCtx: sessionCtx, |
| 87 | doneCh: make(chan struct{}), |
| 88 | } |
| 89 | ctl.lastPong.Store(time.Now()) |
| 90 |
| 91 | ctl.msgDispatcher = msg.NewDispatcher(sessionCtx.Conn) |
| 92 | ctl.registerMsgHandlers() |
| 93 | ctl.msgTransporter = transport.NewMessageTransporter(ctl.msgDispatcher) |
| 94 |
| 95 | ctl.pm = proxy.NewManager(ctl.ctx, sessionCtx.Common, sessionCtx.Auth.EncryptionKey(), ctl.msgTransporter, sessionCtx.VnetController) |
| 96 | ctl.vm = visitor.NewManager(ctl.ctx, sessionCtx.RunID, sessionCtx.Common, |
| 97 | ctl.connectServer, ctl.msgTransporter, sessionCtx.VnetController) |
| 98 | return ctl, nil |
| 99 | } |
| 100 |
| 101 | func (ctl *Control) Run(proxyCfgs []v1.ProxyConfigurer, visitorCfgs []v1.VisitorConfigurer) { |
| 102 | go ctl.worker() |
| 103 |
| 104 | // start all proxies |
| 105 | ctl.pm.UpdateAll(proxyCfgs) |
| 106 |
| 107 | // start all visitors |
| 108 | ctl.vm.UpdateAll(visitorCfgs) |
| 109 | } |
| 110 |
| 111 | func (ctl *Control) SetInWorkConnCallback(cb func(*v1.ProxyBaseConfig, net.Conn, *msg.StartWorkConn) bool) { |
| 112 | ctl.pm.SetInWorkConnCallback(cb) |
| 113 | } |
| 114 |
| 115 | func (ctl *Control) handleReqWorkConn(_ msg.Message) { |
| 116 | xl := ctl.xl |
| 117 | workConn, err := ctl.connectServer() |
| 118 | if err != nil { |
| 119 | xl.Warnf("start new connection to server error: %v", err) |
| 120 | return |
| 121 | } |
| 122 |
| 123 | m := &msg.NewWorkConn{ |
| 124 | RunID: ctl.sessionCtx.RunID, |
| 125 | } |
| 126 | if err = ctl.sessionCtx.Auth.Setter.SetNewWorkConn(m); err != nil { |
| 127 | xl.Warnf("error during NewWorkConn authentication: %v", err) |
| 128 | workConn.Close() |
| 129 | return |
| 130 | } |
| 131 | if err = workConn.WriteMsg(m); err != nil { |
| 132 | xl.Warnf("work connection write to server error: %v", err) |
| 133 | workConn.Close() |
| 134 | return |
| 135 | } |
| 136 |
| 137 | var startMsg msg.StartWorkConn |
| 138 | if err = workConn.ReadMsgInto(&startMsg); err != nil { |
| 139 | xl.Tracef("work connection closed before response StartWorkConn message: %v", err) |
| 140 | workConn.Close() |
| 141 | return |
| 142 | } |
| 143 | if startMsg.Error != "" { |
| 144 | xl.Errorf("StartWorkConn contains error: %s", startMsg.Error) |
| 145 | workConn.Close() |
| 146 | return |
| 147 | } |
| 148 |
| 149 | startMsg.ProxyName = naming.StripUserPrefix(ctl.sessionCtx.Common.User, startMsg.ProxyName) |
| 150 |
| 151 | // dispatch this work connection to related proxy |
| 152 | ctl.pm.HandleWorkConn(startMsg.ProxyName, workConn, &startMsg) |
| 153 | } |
| 154 |
| 155 | func (ctl *Control) handleNewProxyResp(m msg.Message) { |
| 156 | xl := ctl.xl |
| 157 | inMsg := m.(*msg.NewProxyResp) |
| 158 | // Server will return NewProxyResp message to each NewProxy message. |
| 159 | // Start a new proxy handler if no error got |
| 160 | proxyName := naming.StripUserPrefix(ctl.sessionCtx.Common.User, inMsg.ProxyName) |
| 161 | err := ctl.pm.StartProxy(proxyName, inMsg.RemoteAddr, inMsg.Error) |
| 162 | if err != nil { |
| 163 | xl.Warnf("[%s] start error: %v", proxyName, err) |
| 164 | } else { |
| 165 | xl.Infof("[%s] start proxy success", proxyName) |
| 166 | } |
| 167 | } |
| 168 |
| 169 | func (ctl *Control) handleNatHoleResp(m msg.Message) { |
| 170 | xl := ctl.xl |
| 171 | inMsg := m.(*msg.NatHoleResp) |
| 172 |
| 173 | // Dispatch the NatHoleResp message to the related proxy. |
| 174 | ok := ctl.msgTransporter.DispatchWithType(inMsg, msg.TypeNameNatHoleResp, inMsg.TransactionID) |
| 175 | if !ok { |
| 176 | xl.Tracef("dispatch NatHoleResp message to related proxy error") |
| 177 | } |
| 178 | } |
| 179 |
| 180 | func (ctl *Control) handlePong(m msg.Message) { |
| 181 | xl := ctl.xl |
| 182 | inMsg := m.(*msg.Pong) |
| 183 |
| 184 | if inMsg.Error != "" { |
| 185 | xl.Errorf("pong message contains error: %s", inMsg.Error) |
| 186 | ctl.closeSession() |
| 187 | return |
| 188 | } |
| 189 | ctl.lastPong.Store(time.Now()) |
| 190 | xl.Debugf("receive heartbeat from server") |
| 191 | } |
| 192 |
| 193 | // closeSession closes the control connection. |
| 194 | func (ctl *Control) closeSession() { |
| 195 | ctl.sessionCtx.Conn.Close() |
| 196 | ctl.sessionCtx.Connector.Close() |
| 197 | } |
| 198 |
| 199 | func (ctl *Control) Close() error { |
| 200 | return ctl.GracefulClose(0) |
| 201 | } |
| 202 |
| 203 | func (ctl *Control) GracefulClose(d time.Duration) error { |
| 204 | ctl.pm.Close() |
| 205 | ctl.vm.Close() |
| 206 |
| 207 | time.Sleep(d) |
| 208 |
| 209 | ctl.closeSession() |
| 210 | return nil |
| 211 | } |
| 212 |
| 213 | // Done returns a channel that will be closed after all resources are released |
| 214 | func (ctl *Control) Done() <-chan struct{} { |
| 215 | return ctl.doneCh |
| 216 | } |
| 217 |
| 218 | // connectServer return a new connection to frps |
| 219 | func (ctl *Control) connectServer() (*msg.Conn, error) { |
| 220 | return ctl.sessionCtx.Connector.Connect() |
| 221 | } |
| 222 |
| 223 | func (ctl *Control) registerMsgHandlers() { |
| 224 | ctl.msgDispatcher.RegisterHandler(&msg.ReqWorkConn{}, msg.AsyncHandler(ctl.handleReqWorkConn)) |
| 225 | ctl.msgDispatcher.RegisterHandler(&msg.NewProxyResp{}, ctl.handleNewProxyResp) |
| 226 | ctl.msgDispatcher.RegisterHandler(&msg.NatHoleResp{}, ctl.handleNatHoleResp) |
| 227 | ctl.msgDispatcher.RegisterHandler(&msg.Pong{}, ctl.handlePong) |
| 228 | } |
| 229 |
| 230 | // heartbeatWorker sends heartbeat to server and check heartbeat timeout. |
| 231 | func (ctl *Control) heartbeatWorker() { |
| 232 | xl := ctl.xl |
| 233 |
| 234 | if ctl.sessionCtx.Common.Transport.HeartbeatInterval > 0 { |
| 235 | // Send heartbeat to server. |
| 236 | sendHeartBeat := func() (bool, error) { |
| 237 | xl.Debugf("send heartbeat to server") |
| 238 | pingMsg := &msg.Ping{} |
| 239 | if err := ctl.sessionCtx.Auth.Setter.SetPing(pingMsg); err != nil { |
| 240 | xl.Warnf("error during ping authentication: %v, skip sending ping message", err) |
| 241 | return false, err |
| 242 | } |
| 243 | _ = ctl.msgDispatcher.Send(pingMsg) |
| 244 | return false, nil |
| 245 | } |
| 246 |
| 247 | go wait.BackoffUntil(sendHeartBeat, |
| 248 | wait.NewFastBackoffManager(wait.FastBackoffOptions{ |
| 249 | Duration: time.Duration(ctl.sessionCtx.Common.Transport.HeartbeatInterval) * time.Second, |
| 250 | InitDurationIfFail: time.Second, |
| 251 | Factor: 2.0, |
| 252 | Jitter: 0.1, |
| 253 | MaxDuration: time.Duration(ctl.sessionCtx.Common.Transport.HeartbeatInterval) * time.Second, |
| 254 | }), |
| 255 | true, ctl.doneCh, |
| 256 | ) |
| 257 | } |
| 258 |
| 259 | // Check heartbeat timeout. |
| 260 | if ctl.sessionCtx.Common.Transport.HeartbeatInterval > 0 && ctl.sessionCtx.Common.Transport.HeartbeatTimeout > 0 { |
| 261 | go wait.Until(func() { |
| 262 | if time.Since(ctl.lastPong.Load().(time.Time)) > time.Duration(ctl.sessionCtx.Common.Transport.HeartbeatTimeout)*time.Second { |
| 263 | xl.Warnf("heartbeat timeout") |
| 264 | ctl.closeSession() |
| 265 | return |
| 266 | } |
| 267 | }, time.Second, ctl.doneCh) |
| 268 | } |
| 269 | } |
| 270 |
| 271 | func (ctl *Control) worker() { |
| 272 | xl := ctl.xl |
| 273 | go ctl.heartbeatWorker() |
| 274 | go ctl.msgDispatcher.Run() |
| 275 |
| 276 | <-ctl.msgDispatcher.Done() |
| 277 | xl.Debugf("control message dispatcher exited") |
| 278 | ctl.closeSession() |
| 279 |
| 280 | ctl.pm.Close() |
| 281 | ctl.vm.Close() |
| 282 | close(ctl.doneCh) |
| 283 | } |
| 284 |
| 285 | func (ctl *Control) UpdateAllConfigurer(proxyCfgs []v1.ProxyConfigurer, visitorCfgs []v1.VisitorConfigurer) error { |
| 286 | ctl.vm.UpdateAll(visitorCfgs) |
| 287 | ctl.pm.UpdateAll(proxyCfgs) |
| 288 | return nil |
| 289 | } |