| // |
| 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 proxy |
| 16 |
| 17 | import ( |
| 18 | "context" |
| 19 | "fmt" |
| 20 | "net" |
| 21 | "strconv" |
| 22 | "sync" |
| 23 | "sync/atomic" |
| 24 | "time" |
| 25 |
| 26 | "github.com/fatedier/golib/errors" |
| 27 |
| 28 | "github.com/fatedier/frp/client/event" |
| 29 | "github.com/fatedier/frp/client/health" |
| 30 | v1 "github.com/fatedier/frp/pkg/config/v1" |
| 31 | "github.com/fatedier/frp/pkg/msg" |
| 32 | "github.com/fatedier/frp/pkg/naming" |
| 33 | "github.com/fatedier/frp/pkg/transport" |
| 34 | "github.com/fatedier/frp/pkg/util/xlog" |
| 35 | "github.com/fatedier/frp/pkg/vnet" |
| 36 | ) |
| 37 |
| 38 | const ( |
| 39 | ProxyPhaseNew = "new" |
| 40 | ProxyPhaseWaitStart = "wait start" |
| 41 | ProxyPhaseStartErr = "start error" |
| 42 | ProxyPhaseRunning = "running" |
| 43 | ProxyPhaseCheckFailed = "check failed" |
| 44 | ProxyPhaseClosed = "closed" |
| 45 | ) |
| 46 |
| 47 | var ( |
| 48 | statusCheckInterval = 3 * time.Second |
| 49 | waitResponseTimeout = 20 * time.Second |
| 50 | startErrTimeout = 30 * time.Second |
| 51 | ) |
| 52 |
| 53 | type WorkingStatus struct { |
| 54 | Name string `json:"name"` |
| 55 | Type string `json:"type"` |
| 56 | Phase string `json:"status"` |
| 57 | Err string `json:"err"` |
| 58 | Cfg v1.ProxyConfigurer `json:"cfg"` |
| 59 |
| 60 | // Got from server. |
| 61 | RemoteAddr string `json:"remote_addr"` |
| 62 | } |
| 63 |
| 64 | type Wrapper struct { |
| 65 | WorkingStatus |
| 66 |
| 67 | // underlying proxy |
| 68 | pxy Proxy |
| 69 |
| 70 | // if ProxyConf has healcheck config |
| 71 | // monitor will watch if it is alive |
| 72 | monitor *health.Monitor |
| 73 |
| 74 | // event handler |
| 75 | handler event.Handler |
| 76 |
| 77 | msgTransporter transport.MessageTransporter |
| 78 | // vnet controller |
| 79 | vnetController *vnet.Controller |
| 80 |
| 81 | health uint32 |
| 82 | lastSendStartMsg time.Time |
| 83 | lastStartErr time.Time |
| 84 | closeCh chan struct{} |
| 85 | healthNotifyCh chan struct{} |
| 86 | mu sync.RWMutex |
| 87 |
| 88 | xl *xlog.Logger |
| 89 | ctx context.Context |
| 90 |
| 91 | wireName string |
| 92 | } |
| 93 |
| 94 | func NewWrapper( |
| 95 | ctx context.Context, |
| 96 | cfg v1.ProxyConfigurer, |
| 97 | clientCfg *v1.ClientCommonConfig, |
| 98 | encryptionKey []byte, |
| 99 | eventHandler event.Handler, |
| 100 | msgTransporter transport.MessageTransporter, |
| 101 | vnetController *vnet.Controller, |
| 102 | ) *Wrapper { |
| 103 | baseInfo := cfg.GetBaseConfig() |
| 104 | xl := xlog.FromContextSafe(ctx).Spawn().AppendPrefix(baseInfo.Name) |
| 105 | pw := &Wrapper{ |
| 106 | WorkingStatus: WorkingStatus{ |
| 107 | Name: baseInfo.Name, |
| 108 | Type: baseInfo.Type, |
| 109 | Phase: ProxyPhaseNew, |
| 110 | Cfg: cfg, |
| 111 | }, |
| 112 | closeCh: make(chan struct{}), |
| 113 | healthNotifyCh: make(chan struct{}), |
| 114 | handler: eventHandler, |
| 115 | msgTransporter: msgTransporter, |
| 116 | vnetController: vnetController, |
| 117 | xl: xl, |
| 118 | ctx: xlog.NewContext(ctx, xl), |
| 119 | wireName: naming.AddUserPrefix(clientCfg.User, baseInfo.Name), |
| 120 | } |
| 121 |
| 122 | if baseInfo.HealthCheck.Type != "" && baseInfo.LocalPort > 0 { |
| 123 | pw.health = 1 // means failed |
| 124 | addr := net.JoinHostPort(baseInfo.LocalIP, strconv.Itoa(baseInfo.LocalPort)) |
| 125 | pw.monitor = health.NewMonitor(pw.ctx, baseInfo.HealthCheck, addr, |
| 126 | pw.statusNormalCallback, pw.statusFailedCallback) |
| 127 | xl.Tracef("enable health check monitor") |
| 128 | } |
| 129 |
| 130 | pw.pxy = NewProxy(pw.ctx, pw.Cfg, clientCfg, encryptionKey, pw.msgTransporter, pw.vnetController) |
| 131 | return pw |
| 132 | } |
| 133 |
| 134 | func (pw *Wrapper) SetInWorkConnCallback(cb func(*v1.ProxyBaseConfig, net.Conn, *msg.StartWorkConn) bool) { |
| 135 | pw.pxy.SetInWorkConnCallback(cb) |
| 136 | } |
| 137 |
| 138 | func (pw *Wrapper) SetRunningStatus(remoteAddr string, respErr string) error { |
| 139 | pw.mu.Lock() |
| 140 | defer pw.mu.Unlock() |
| 141 | if pw.Phase != ProxyPhaseWaitStart { |
| 142 | return fmt.Errorf("status not wait start, ignore start message") |
| 143 | } |
| 144 |
| 145 | pw.RemoteAddr = remoteAddr |
| 146 | if respErr != "" { |
| 147 | pw.Phase = ProxyPhaseStartErr |
| 148 | pw.Err = respErr |
| 149 | pw.lastStartErr = time.Now() |
| 150 | return fmt.Errorf("%s", pw.Err) |
| 151 | } |
| 152 |
| 153 | if err := pw.pxy.Run(); err != nil { |
| 154 | pw.close() |
| 155 | pw.Phase = ProxyPhaseStartErr |
| 156 | pw.Err = err.Error() |
| 157 | pw.lastStartErr = time.Now() |
| 158 | return err |
| 159 | } |
| 160 |
| 161 | pw.Phase = ProxyPhaseRunning |
| 162 | pw.Err = "" |
| 163 | return nil |
| 164 | } |
| 165 |
| 166 | func (pw *Wrapper) Start() { |
| 167 | go pw.checkWorker() |
| 168 | if pw.monitor != nil { |
| 169 | go pw.monitor.Start() |
| 170 | } |
| 171 | } |
| 172 |
| 173 | func (pw *Wrapper) Stop() { |
| 174 | pw.mu.Lock() |
| 175 | defer pw.mu.Unlock() |
| 176 | close(pw.closeCh) |
| 177 | close(pw.healthNotifyCh) |
| 178 | pw.pxy.Close() |
| 179 | if pw.monitor != nil { |
| 180 | pw.monitor.Stop() |
| 181 | } |
| 182 | pw.Phase = ProxyPhaseClosed |
| 183 | pw.close() |
| 184 | } |
| 185 |
| 186 | func (pw *Wrapper) close() { |
| 187 | _ = pw.handler(&event.CloseProxyPayload{ |
| 188 | CloseProxyMsg: &msg.CloseProxy{ |
| 189 | ProxyName: pw.wireName, |
| 190 | }, |
| 191 | }) |
| 192 | } |
| 193 |
| 194 | func (pw *Wrapper) checkWorker() { |
| 195 | xl := pw.xl |
| 196 | if pw.monitor != nil { |
| 197 | // let monitor do check request first |
| 198 | time.Sleep(500 * time.Millisecond) |
| 199 | } |
| 200 | for { |
| 201 | // check proxy status |
| 202 | now := time.Now() |
| 203 | if atomic.LoadUint32(&pw.health) == 0 { |
| 204 | pw.mu.Lock() |
| 205 | if pw.Phase == ProxyPhaseNew || |
| 206 | pw.Phase == ProxyPhaseCheckFailed || |
| 207 | (pw.Phase == ProxyPhaseWaitStart && now.After(pw.lastSendStartMsg.Add(waitResponseTimeout))) || |
| 208 | (pw.Phase == ProxyPhaseStartErr && now.After(pw.lastStartErr.Add(startErrTimeout))) { |
| 209 |
| 210 | xl.Tracef("change status from [%s] to [%s]", pw.Phase, ProxyPhaseWaitStart) |
| 211 | pw.Phase = ProxyPhaseWaitStart |
| 212 |
| 213 | var newProxyMsg msg.NewProxy |
| 214 | pw.Cfg.MarshalToMsg(&newProxyMsg) |
| 215 | newProxyMsg.ProxyName = pw.wireName |
| 216 | pw.lastSendStartMsg = now |
| 217 | _ = pw.handler(&event.StartProxyPayload{ |
| 218 | NewProxyMsg: &newProxyMsg, |
| 219 | }) |
| 220 | } |
| 221 | pw.mu.Unlock() |
| 222 | } else { |
| 223 | pw.mu.Lock() |
| 224 | if pw.Phase == ProxyPhaseRunning || pw.Phase == ProxyPhaseWaitStart { |
| 225 | pw.close() |
| 226 | xl.Tracef("change status from [%s] to [%s]", pw.Phase, ProxyPhaseCheckFailed) |
| 227 | pw.Phase = ProxyPhaseCheckFailed |
| 228 | } |
| 229 | pw.mu.Unlock() |
| 230 | } |
| 231 |
| 232 | select { |
| 233 | case <-pw.closeCh: |
| 234 | return |
| 235 | case <-time.After(statusCheckInterval): |
| 236 | case <-pw.healthNotifyCh: |
| 237 | } |
| 238 | } |
| 239 | } |
| 240 |
| 241 | func (pw *Wrapper) statusNormalCallback() { |
| 242 | xl := pw.xl |
| 243 | atomic.StoreUint32(&pw.health, 0) |
| 244 | _ = errors.PanicToError(func() { |
| 245 | select { |
| 246 | case pw.healthNotifyCh <- struct{}{}: |
| 247 | default: |
| 248 | } |
| 249 | }) |
| 250 | xl.Infof("health check success") |
| 251 | } |
| 252 |
| 253 | func (pw *Wrapper) statusFailedCallback() { |
| 254 | xl := pw.xl |
| 255 | atomic.StoreUint32(&pw.health, 1) |
| 256 | _ = errors.PanicToError(func() { |
| 257 | select { |
| 258 | case pw.healthNotifyCh <- struct{}{}: |
| 259 | default: |
| 260 | } |
| 261 | }) |
| 262 | xl.Infof("health check failed") |
| 263 | } |
| 264 |
| 265 | func (pw *Wrapper) InWorkConn(workConn net.Conn, m *msg.StartWorkConn) { |
| 266 | xl := pw.xl |
| 267 | pw.mu.RLock() |
| 268 | pxy := pw.pxy |
| 269 | pw.mu.RUnlock() |
| 270 | if pxy != nil && pw.Phase == ProxyPhaseRunning { |
| 271 | xl.Debugf("start a new work connection, localAddr: %s remoteAddr: %s", workConn.LocalAddr().String(), workConn.RemoteAddr().String()) |
| 272 | go pxy.InWorkConn(workConn, m) |
| 273 | } else { |
| 274 | workConn.Close() |
| 275 | } |
| 276 | } |
| 277 |
| 278 | func (pw *Wrapper) GetStatus() *WorkingStatus { |
| 279 | pw.mu.RLock() |
| 280 | defer pw.mu.RUnlock() |
| 281 | ps := &WorkingStatus{ |
| 282 | Name: pw.Name, |
| 283 | Type: pw.Type, |
| 284 | Phase: pw.Phase, |
| 285 | Err: pw.Err, |
| 286 | Cfg: pw.Cfg, |
| 287 | RemoteAddr: pw.RemoteAddr, |
| 288 | } |
| 289 | return ps |
| 290 | } |