| // |
| 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 | "io" |
| 21 | "net" |
| 22 | "reflect" |
| 23 | "strconv" |
| 24 | "sync" |
| 25 | "time" |
| 26 |
| 27 | libio "github.com/fatedier/golib/io" |
| 28 | libnet "github.com/fatedier/golib/net" |
| 29 | "golang.org/x/time/rate" |
| 30 |
| 31 | "github.com/fatedier/frp/pkg/config/types" |
| 32 | v1 "github.com/fatedier/frp/pkg/config/v1" |
| 33 | "github.com/fatedier/frp/pkg/msg" |
| 34 | plugin "github.com/fatedier/frp/pkg/plugin/client" |
| 35 | "github.com/fatedier/frp/pkg/transport" |
| 36 | "github.com/fatedier/frp/pkg/util/limit" |
| 37 | netpkg "github.com/fatedier/frp/pkg/util/net" |
| 38 | "github.com/fatedier/frp/pkg/util/xlog" |
| 39 | "github.com/fatedier/frp/pkg/vnet" |
| 40 | ) |
| 41 |
| 42 | var proxyFactoryRegistry = map[reflect.Type]func(*BaseProxy, v1.ProxyConfigurer) Proxy{} |
| 43 |
| 44 | func RegisterProxyFactory(proxyConfType reflect.Type, factory func(*BaseProxy, v1.ProxyConfigurer) Proxy) { |
| 45 | proxyFactoryRegistry[proxyConfType] = factory |
| 46 | } |
| 47 |
| 48 | // Proxy defines how to handle work connections for different proxy type. |
| 49 | type Proxy interface { |
| 50 | Run() error |
| 51 | // InWorkConn accept work connections registered to server. |
| 52 | InWorkConn(net.Conn, *msg.StartWorkConn) |
| 53 | SetInWorkConnCallback(func(*v1.ProxyBaseConfig, net.Conn, *msg.StartWorkConn) /* continue */ bool) |
| 54 | Close() |
| 55 | } |
| 56 |
| 57 | func NewProxy( |
| 58 | ctx context.Context, |
| 59 | pxyConf v1.ProxyConfigurer, |
| 60 | clientCfg *v1.ClientCommonConfig, |
| 61 | encryptionKey []byte, |
| 62 | msgTransporter transport.MessageTransporter, |
| 63 | vnetController *vnet.Controller, |
| 64 | ) (pxy Proxy) { |
| 65 | var limiter *rate.Limiter |
| 66 | limitBytes := pxyConf.GetBaseConfig().Transport.BandwidthLimit.Bytes() |
| 67 | if limitBytes > 0 && pxyConf.GetBaseConfig().Transport.BandwidthLimitMode == types.BandwidthLimitModeClient { |
| 68 | limiter = rate.NewLimiter(rate.Limit(float64(limitBytes)), int(limitBytes)) |
| 69 | } |
| 70 |
| 71 | baseProxy := BaseProxy{ |
| 72 | baseCfg: pxyConf.GetBaseConfig(), |
| 73 | clientCfg: clientCfg, |
| 74 | encryptionKey: encryptionKey, |
| 75 | limiter: limiter, |
| 76 | msgTransporter: msgTransporter, |
| 77 | vnetController: vnetController, |
| 78 | xl: xlog.FromContextSafe(ctx), |
| 79 | ctx: ctx, |
| 80 | } |
| 81 |
| 82 | factory := proxyFactoryRegistry[reflect.TypeOf(pxyConf)] |
| 83 | if factory == nil { |
| 84 | return nil |
| 85 | } |
| 86 | return factory(&baseProxy, pxyConf) |
| 87 | } |
| 88 |
| 89 | type BaseProxy struct { |
| 90 | baseCfg *v1.ProxyBaseConfig |
| 91 | clientCfg *v1.ClientCommonConfig |
| 92 | encryptionKey []byte |
| 93 | msgTransporter transport.MessageTransporter |
| 94 | vnetController *vnet.Controller |
| 95 | limiter *rate.Limiter |
| 96 | // proxyPlugin is used to handle connections instead of dialing to local service. |
| 97 | // It's only validate for TCP protocol now. |
| 98 | proxyPlugin plugin.Plugin |
| 99 | inWorkConnCallback func(*v1.ProxyBaseConfig, net.Conn, *msg.StartWorkConn) /* continue */ bool |
| 100 |
| 101 | mu sync.RWMutex |
| 102 | xl *xlog.Logger |
| 103 | ctx context.Context |
| 104 | } |
| 105 |
| 106 | func (pxy *BaseProxy) Run() error { |
| 107 | if pxy.baseCfg.Plugin.Type != "" { |
| 108 | p, err := plugin.Create(pxy.baseCfg.Plugin.Type, plugin.PluginContext{ |
| 109 | Name: pxy.baseCfg.Name, |
| 110 | VnetController: pxy.vnetController, |
| 111 | }, pxy.baseCfg.Plugin.ClientPluginOptions) |
| 112 | if err != nil { |
| 113 | return err |
| 114 | } |
| 115 | pxy.proxyPlugin = p |
| 116 | } |
| 117 | return nil |
| 118 | } |
| 119 |
| 120 | func (pxy *BaseProxy) Close() { |
| 121 | if pxy.proxyPlugin != nil { |
| 122 | pxy.proxyPlugin.Close() |
| 123 | } |
| 124 | } |
| 125 |
| 126 | // wrapWorkConn applies rate limiting, encryption, and compression |
| 127 | // to a work connection based on the proxy's transport configuration. |
| 128 | // The returned recycle function should be called when the stream is no longer in use |
| 129 | // to return compression resources to the pool. It is safe to not call recycle, |
| 130 | // in which case resources will be garbage collected normally. |
| 131 | func (pxy *BaseProxy) wrapWorkConn(conn net.Conn, encKey []byte) (io.ReadWriteCloser, func(), error) { |
| 132 | var rwc io.ReadWriteCloser = conn |
| 133 | if pxy.limiter != nil { |
| 134 | rwc = libio.WrapReadWriteCloser(limit.NewReader(conn, pxy.limiter), limit.NewWriter(conn, pxy.limiter), func() error { |
| 135 | return conn.Close() |
| 136 | }) |
| 137 | } |
| 138 | if pxy.baseCfg.Transport.UseEncryption { |
| 139 | var err error |
| 140 | rwc, err = libio.WithEncryption(rwc, encKey) |
| 141 | if err != nil { |
| 142 | conn.Close() |
| 143 | return nil, nil, fmt.Errorf("create encryption stream error: %w", err) |
| 144 | } |
| 145 | } |
| 146 | var recycleFn func() |
| 147 | if pxy.baseCfg.Transport.UseCompression { |
| 148 | rwc, recycleFn = libio.WithCompressionFromPool(rwc) |
| 149 | } |
| 150 | return rwc, recycleFn, nil |
| 151 | } |
| 152 |
| 153 | func (pxy *BaseProxy) SetInWorkConnCallback(cb func(*v1.ProxyBaseConfig, net.Conn, *msg.StartWorkConn) bool) { |
| 154 | pxy.inWorkConnCallback = cb |
| 155 | } |
| 156 |
| 157 | func (pxy *BaseProxy) InWorkConn(conn net.Conn, m *msg.StartWorkConn) { |
| 158 | if pxy.inWorkConnCallback != nil { |
| 159 | if !pxy.inWorkConnCallback(pxy.baseCfg, conn, m) { |
| 160 | return |
| 161 | } |
| 162 | } |
| 163 | pxy.HandleTCPWorkConnection(conn, m, pxy.encryptionKey) |
| 164 | } |
| 165 |
| 166 | // Common handler for tcp work connections. |
| 167 | func (pxy *BaseProxy) HandleTCPWorkConnection(workConn net.Conn, m *msg.StartWorkConn, encKey []byte) { |
| 168 | xl := pxy.xl |
| 169 | baseCfg := pxy.baseCfg |
| 170 |
| 171 | xl.Tracef("handle tcp work connection, useEncryption: %t, useCompression: %t", |
| 172 | baseCfg.Transport.UseEncryption, baseCfg.Transport.UseCompression) |
| 173 |
| 174 | remote, recycleFn, err := pxy.wrapWorkConn(workConn, encKey) |
| 175 | if err != nil { |
| 176 | xl.Errorf("wrap work connection: %v", err) |
| 177 | return |
| 178 | } |
| 179 |
| 180 | // check if we need to send proxy protocol info |
| 181 | var connInfo plugin.ConnectionInfo |
| 182 | if m.SrcAddr != "" && m.SrcPort != 0 { |
| 183 | if m.DstAddr == "" { |
| 184 | m.DstAddr = "127.0.0.1" |
| 185 | } |
| 186 | srcAddr, _ := net.ResolveTCPAddr("tcp", net.JoinHostPort(m.SrcAddr, strconv.Itoa(int(m.SrcPort)))) |
| 187 | dstAddr, _ := net.ResolveTCPAddr("tcp", net.JoinHostPort(m.DstAddr, strconv.Itoa(int(m.DstPort)))) |
| 188 | connInfo.SrcAddr = srcAddr |
| 189 | connInfo.DstAddr = dstAddr |
| 190 | } |
| 191 |
| 192 | if baseCfg.Transport.ProxyProtocolVersion != "" && m.SrcAddr != "" && m.SrcPort != 0 { |
| 193 | header := netpkg.BuildProxyProtocolHeaderStruct(connInfo.SrcAddr, connInfo.DstAddr, baseCfg.Transport.ProxyProtocolVersion) |
| 194 | connInfo.ProxyProtocolHeader = header |
| 195 | } |
| 196 | connInfo.Conn = remote |
| 197 | connInfo.UnderlyingConn = workConn |
| 198 |
| 199 | if pxy.proxyPlugin != nil { |
| 200 | // if plugin is set, let plugin handle connection first |
| 201 | // Don't recycle compression resources here because plugins may |
| 202 | // retain the connection after Handle returns. |
| 203 | xl.Debugf("handle by plugin: %s", pxy.proxyPlugin.Name()) |
| 204 | pxy.proxyPlugin.Handle(pxy.ctx, &connInfo) |
| 205 | xl.Debugf("handle by plugin finished") |
| 206 | return |
| 207 | } |
| 208 |
| 209 | if recycleFn != nil { |
| 210 | defer recycleFn() |
| 211 | } |
| 212 |
| 213 | localConn, err := libnet.Dial( |
| 214 | net.JoinHostPort(baseCfg.LocalIP, strconv.Itoa(baseCfg.LocalPort)), |
| 215 | libnet.WithTimeout(10*time.Second), |
| 216 | ) |
| 217 | if err != nil { |
| 218 | workConn.Close() |
| 219 | xl.Errorf("connect to local service [%s:%d] error: %v", baseCfg.LocalIP, baseCfg.LocalPort, err) |
| 220 | return |
| 221 | } |
| 222 |
| 223 | xl.Debugf("join connections, localConn(l[%s] r[%s]) workConn(l[%s] r[%s])", localConn.LocalAddr().String(), |
| 224 | localConn.RemoteAddr().String(), workConn.LocalAddr().String(), workConn.RemoteAddr().String()) |
| 225 |
| 226 | if connInfo.ProxyProtocolHeader != nil { |
| 227 | if _, err := connInfo.ProxyProtocolHeader.WriteTo(localConn); err != nil { |
| 228 | workConn.Close() |
| 229 | localConn.Close() |
| 230 | xl.Errorf("write proxy protocol header to local conn error: %v", err) |
| 231 | return |
| 232 | } |
| 233 | } |
| 234 |
| 235 | _, _, errs := libio.Join(localConn, remote) |
| 236 | xl.Debugf("join connections closed") |
| 237 | if len(errs) > 0 { |
| 238 | xl.Tracef("join connections errors: %v", errs) |
| 239 | } |
| 240 | } |