| // |
| 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 | //go:build !frps |
| 16 |
| 17 | package visitor |
| 18 |
| 19 | import ( |
| 20 | "context" |
| 21 | "errors" |
| 22 | "fmt" |
| 23 | "net" |
| 24 | "sync" |
| 25 | "time" |
| 26 |
| 27 | v1 "github.com/fatedier/frp/pkg/config/v1" |
| 28 | netutil "github.com/fatedier/frp/pkg/util/net" |
| 29 | "github.com/fatedier/frp/pkg/util/xlog" |
| 30 | ) |
| 31 |
| 32 | func init() { |
| 33 | Register(v1.VisitorPluginVirtualNet, NewVirtualNetPlugin) |
| 34 | } |
| 35 |
| 36 | type VirtualNetPlugin struct { |
| 37 | pluginCtx PluginContext |
| 38 |
| 39 | routes []net.IPNet |
| 40 |
| 41 | mu sync.Mutex |
| 42 | controllerConn net.Conn |
| 43 | closeSignal chan struct{} |
| 44 |
| 45 | consecutiveErrors int // Tracks consecutive connection errors for exponential backoff |
| 46 |
| 47 | ctx context.Context |
| 48 | cancel context.CancelFunc |
| 49 | } |
| 50 |
| 51 | func NewVirtualNetPlugin(pluginCtx PluginContext, options v1.VisitorPluginOptions) (Plugin, error) { |
| 52 | opts := options.(*v1.VirtualNetVisitorPluginOptions) |
| 53 |
| 54 | p := &VirtualNetPlugin{ |
| 55 | pluginCtx: pluginCtx, |
| 56 | routes: make([]net.IPNet, 0), |
| 57 | } |
| 58 |
| 59 | p.ctx, p.cancel = context.WithCancel(pluginCtx.Ctx) |
| 60 |
| 61 | if opts.DestinationIP == "" { |
| 62 | return nil, errors.New("destinationIP is required") |
| 63 | } |
| 64 |
| 65 | // Parse DestinationIP and create a host route. |
| 66 | ip := net.ParseIP(opts.DestinationIP) |
| 67 | if ip == nil { |
| 68 | return nil, fmt.Errorf("invalid destination IP address [%s]", opts.DestinationIP) |
| 69 | } |
| 70 |
| 71 | var mask net.IPMask |
| 72 | if ip.To4() != nil { |
| 73 | mask = net.CIDRMask(32, 32) // /32 for IPv4 |
| 74 | } else { |
| 75 | mask = net.CIDRMask(128, 128) // /128 for IPv6 |
| 76 | } |
| 77 | p.routes = append(p.routes, net.IPNet{IP: ip, Mask: mask}) |
| 78 |
| 79 | return p, nil |
| 80 | } |
| 81 |
| 82 | func (p *VirtualNetPlugin) Name() string { |
| 83 | return v1.VisitorPluginVirtualNet |
| 84 | } |
| 85 |
| 86 | func (p *VirtualNetPlugin) Start() { |
| 87 | xl := xlog.FromContextSafe(p.pluginCtx.Ctx) |
| 88 | if p.pluginCtx.VnetController == nil { |
| 89 | return |
| 90 | } |
| 91 |
| 92 | routeStr := "unknown" |
| 93 | if len(p.routes) > 0 { |
| 94 | routeStr = p.routes[0].String() |
| 95 | } |
| 96 | xl.Infof("starting VirtualNetPlugin for visitor [%s], attempting to register routes for %s", p.pluginCtx.Name, routeStr) |
| 97 |
| 98 | go p.run() |
| 99 | } |
| 100 |
| 101 | func (p *VirtualNetPlugin) run() { |
| 102 | xl := xlog.FromContextSafe(p.ctx) |
| 103 |
| 104 | for { |
| 105 | currentCloseSignal := make(chan struct{}) |
| 106 |
| 107 | p.mu.Lock() |
| 108 | p.closeSignal = currentCloseSignal |
| 109 | p.mu.Unlock() |
| 110 |
| 111 | select { |
| 112 | case <-p.ctx.Done(): |
| 113 | xl.Infof("VirtualNetPlugin run loop for visitor [%s] stopping (context cancelled before pipe creation).", p.pluginCtx.Name) |
| 114 | p.cleanupControllerConn(xl) |
| 115 | return |
| 116 | default: |
| 117 | } |
| 118 |
| 119 | controllerConn, pluginConn := net.Pipe() |
| 120 |
| 121 | p.mu.Lock() |
| 122 | p.controllerConn = controllerConn |
| 123 | p.mu.Unlock() |
| 124 |
| 125 | // Wrap with CloseNotifyConn which supports both close notification and error recording |
| 126 | var closeErr error |
| 127 | pluginNotifyConn := netutil.WrapCloseNotifyConn(pluginConn, func(err error) { |
| 128 | closeErr = err |
| 129 | close(currentCloseSignal) // Signal the run loop on close. |
| 130 | }) |
| 131 |
| 132 | xl.Infof("attempting to register client route for visitor [%s]", p.pluginCtx.Name) |
| 133 | p.pluginCtx.VnetController.RegisterClientRoute(p.ctx, p.pluginCtx.Name, p.routes, controllerConn) |
| 134 | xl.Infof("successfully registered client route for visitor [%s]. Starting connection handler with CloseNotifyConn.", p.pluginCtx.Name) |
| 135 |
| 136 | // Pass the CloseNotifyConn to the visitor for handling. |
| 137 | // The visitor can call CloseWithError to record the failure reason. |
| 138 | p.pluginCtx.SendConnToVisitor(pluginNotifyConn) |
| 139 |
| 140 | // Wait for context cancellation or connection close. |
| 141 | select { |
| 142 | case <-p.ctx.Done(): |
| 143 | xl.Infof("VirtualNetPlugin run loop stopping for visitor [%s] (context cancelled while waiting).", p.pluginCtx.Name) |
| 144 | p.cleanupControllerConn(xl) |
| 145 | return |
| 146 | case <-currentCloseSignal: |
| 147 | // Determine reconnect delay based on error with exponential backoff |
| 148 | var reconnectDelay time.Duration |
| 149 | if closeErr != nil { |
| 150 | p.consecutiveErrors++ |
| 151 | xl.Warnf("connection closed with error for visitor [%s] (consecutive errors: %d): %v", |
| 152 | p.pluginCtx.Name, p.consecutiveErrors, closeErr) |
| 153 |
| 154 | // Exponential backoff: 60s, 120s, 240s, 300s (capped) |
| 155 | baseDelay := 60 * time.Second |
| 156 | reconnectDelay = min(baseDelay*time.Duration(1<<uint(p.consecutiveErrors-1)), 300*time.Second) |
| 157 | } else { |
| 158 | // Reset consecutive errors on successful connection |
| 159 | if p.consecutiveErrors > 0 { |
| 160 | xl.Infof("connection closed normally for visitor [%s], resetting error counter (was %d)", |
| 161 | p.pluginCtx.Name, p.consecutiveErrors) |
| 162 | p.consecutiveErrors = 0 |
| 163 | } else { |
| 164 | xl.Infof("connection closed normally for visitor [%s]", p.pluginCtx.Name) |
| 165 | } |
| 166 | reconnectDelay = 10 * time.Second |
| 167 | } |
| 168 |
| 169 | // The visitor closed the plugin side. Close the controller side. |
| 170 | p.cleanupControllerConn(xl) |
| 171 |
| 172 | xl.Infof("waiting %v before attempting reconnection for visitor [%s]...", reconnectDelay, p.pluginCtx.Name) |
| 173 | select { |
| 174 | case <-time.After(reconnectDelay): |
| 175 | case <-p.ctx.Done(): |
| 176 | xl.Infof("VirtualNetPlugin reconnection delay interrupted for visitor [%s]", p.pluginCtx.Name) |
| 177 | return |
| 178 | } |
| 179 | } |
| 180 |
| 181 | xl.Infof("re-establishing virtual connection for visitor [%s]...", p.pluginCtx.Name) |
| 182 | } |
| 183 | } |
| 184 |
| 185 | // cleanupControllerConn closes the current controllerConn (if it exists) under lock. |
| 186 | func (p *VirtualNetPlugin) cleanupControllerConn(xl *xlog.Logger) { |
| 187 | p.mu.Lock() |
| 188 | defer p.mu.Unlock() |
| 189 | if p.controllerConn != nil { |
| 190 | xl.Debugf("cleaning up controllerConn for visitor [%s]", p.pluginCtx.Name) |
| 191 | p.controllerConn.Close() |
| 192 | p.controllerConn = nil |
| 193 | } |
| 194 | p.closeSignal = nil |
| 195 | } |
| 196 |
| 197 | // Close initiates the plugin shutdown. |
| 198 | func (p *VirtualNetPlugin) Close() error { |
| 199 | xl := xlog.FromContextSafe(p.pluginCtx.Ctx) |
| 200 | xl.Infof("closing VirtualNetPlugin for visitor [%s]", p.pluginCtx.Name) |
| 201 |
| 202 | // Signal the run loop goroutine to stop. |
| 203 | p.cancel() |
| 204 |
| 205 | // Unregister the route from the controller. |
| 206 | if p.pluginCtx.VnetController != nil { |
| 207 | p.pluginCtx.VnetController.UnregisterClientRoute(p.pluginCtx.Name) |
| 208 | xl.Infof("unregistered client route for visitor [%s]", p.pluginCtx.Name) |
| 209 | } |
| 210 |
| 211 | // Explicitly close the controller side of the pipe. |
| 212 | // This ensures the pipe is broken even if the run loop is stuck or the visitor hasn't closed its end. |
| 213 | p.cleanupControllerConn(xl) |
| 214 | xl.Infof("finished cleaning up connections during close for visitor [%s]", p.pluginCtx.Name) |
| 215 |
| 216 | return nil |
| 217 | } |