repo stringlengths 6 47 | file_url stringlengths 77 269 | file_path stringlengths 5 186 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-07 08:35:43 2026-01-07 08:55:24 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/config/v1/visitor_plugin.go | pkg/config/v1/visitor_plugin.go | // Copyright 2025 The frp Authors
//
// 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 v1
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"reflect"
)
const (
VisitorPluginVirtualNet = "virtual_net"
)
var visitorPluginOptionsTypeMap = map[string]reflect.Type{
VisitorPluginVirtualNet: reflect.TypeOf(VirtualNetVisitorPluginOptions{}),
}
type VisitorPluginOptions interface {
Complete()
}
type TypedVisitorPluginOptions struct {
Type string `json:"type"`
VisitorPluginOptions
}
func (c *TypedVisitorPluginOptions) UnmarshalJSON(b []byte) error {
if len(b) == 4 && string(b) == "null" {
return nil
}
typeStruct := struct {
Type string `json:"type"`
}{}
if err := json.Unmarshal(b, &typeStruct); err != nil {
return err
}
c.Type = typeStruct.Type
if c.Type == "" {
return errors.New("visitor plugin type is empty")
}
v, ok := visitorPluginOptionsTypeMap[typeStruct.Type]
if !ok {
return fmt.Errorf("unknown visitor plugin type: %s", typeStruct.Type)
}
options := reflect.New(v).Interface().(VisitorPluginOptions)
decoder := json.NewDecoder(bytes.NewBuffer(b))
if DisallowUnknownFields {
decoder.DisallowUnknownFields()
}
if err := decoder.Decode(options); err != nil {
return fmt.Errorf("unmarshal VisitorPluginOptions error: %v", err)
}
c.VisitorPluginOptions = options
return nil
}
func (c *TypedVisitorPluginOptions) MarshalJSON() ([]byte, error) {
return json.Marshal(c.VisitorPluginOptions)
}
type VirtualNetVisitorPluginOptions struct {
Type string `json:"type"`
DestinationIP string `json:"destinationIP"`
}
func (o *VirtualNetVisitorPluginOptions) Complete() {}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/config/v1/proxy.go | pkg/config/v1/proxy.go | // Copyright 2023 The frp Authors
//
// 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 v1
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"reflect"
"github.com/samber/lo"
"github.com/fatedier/frp/pkg/config/types"
"github.com/fatedier/frp/pkg/msg"
"github.com/fatedier/frp/pkg/util/util"
)
type ProxyTransport struct {
// UseEncryption controls whether or not communication with the server will
// be encrypted. Encryption is done using the tokens supplied in the server
// and client configuration.
UseEncryption bool `json:"useEncryption,omitempty"`
// UseCompression controls whether or not communication with the server
// will be compressed.
UseCompression bool `json:"useCompression,omitempty"`
// BandwidthLimit limit the bandwidth
// 0 means no limit
BandwidthLimit types.BandwidthQuantity `json:"bandwidthLimit,omitempty"`
// BandwidthLimitMode specifies whether to limit the bandwidth on the
// client or server side. Valid values include "client" and "server".
// By default, this value is "client".
BandwidthLimitMode string `json:"bandwidthLimitMode,omitempty"`
// ProxyProtocolVersion specifies which protocol version to use. Valid
// values include "v1", "v2", and "". If the value is "", a protocol
// version will be automatically selected. By default, this value is "".
ProxyProtocolVersion string `json:"proxyProtocolVersion,omitempty"`
}
type LoadBalancerConfig struct {
// Group specifies which group the is a part of. The server will use
// this information to load balance proxies in the same group. If the value
// is "", this will not be in a group.
Group string `json:"group"`
// GroupKey specifies a group key, which should be the same among proxies
// of the same group.
GroupKey string `json:"groupKey,omitempty"`
}
type ProxyBackend struct {
// LocalIP specifies the IP address or host name of the backend.
LocalIP string `json:"localIP,omitempty"`
// LocalPort specifies the port of the backend.
LocalPort int `json:"localPort,omitempty"`
// Plugin specifies what plugin should be used for handling connections. If this value
// is set, the LocalIP and LocalPort values will be ignored.
Plugin TypedClientPluginOptions `json:"plugin,omitempty"`
}
// HealthCheckConfig configures health checking. This can be useful for load
// balancing purposes to detect and remove proxies to failing services.
type HealthCheckConfig struct {
// Type specifies what protocol to use for health checking.
// Valid values include "tcp", "http", and "". If this value is "", health
// checking will not be performed.
//
// If the type is "tcp", a connection will be attempted to the target
// server. If a connection cannot be established, the health check fails.
//
// If the type is "http", a GET request will be made to the endpoint
// specified by HealthCheckURL. If the response is not a 200, the health
// check fails.
Type string `json:"type"` // tcp | http
// TimeoutSeconds specifies the number of seconds to wait for a health
// check attempt to connect. If the timeout is reached, this counts as a
// health check failure. By default, this value is 3.
TimeoutSeconds int `json:"timeoutSeconds,omitempty"`
// MaxFailed specifies the number of allowed failures before the
// is stopped. By default, this value is 1.
MaxFailed int `json:"maxFailed,omitempty"`
// IntervalSeconds specifies the time in seconds between health
// checks. By default, this value is 10.
IntervalSeconds int `json:"intervalSeconds"`
// Path specifies the path to send health checks to if the
// health check type is "http".
Path string `json:"path,omitempty"`
// HTTPHeaders specifies the headers to send with the health request, if
// the health check type is "http".
HTTPHeaders []HTTPHeader `json:"httpHeaders,omitempty"`
}
type DomainConfig struct {
CustomDomains []string `json:"customDomains,omitempty"`
SubDomain string `json:"subdomain,omitempty"`
}
type ProxyBaseConfig struct {
Name string `json:"name"`
Type string `json:"type"`
// Enabled controls whether this proxy is enabled. nil or true means enabled, false means disabled.
// This allows individual control over each proxy, complementing the global "start" field.
Enabled *bool `json:"enabled,omitempty"`
Annotations map[string]string `json:"annotations,omitempty"`
Transport ProxyTransport `json:"transport,omitempty"`
// metadata info for each proxy
Metadatas map[string]string `json:"metadatas,omitempty"`
LoadBalancer LoadBalancerConfig `json:"loadBalancer,omitempty"`
HealthCheck HealthCheckConfig `json:"healthCheck,omitempty"`
ProxyBackend
}
func (c *ProxyBaseConfig) GetBaseConfig() *ProxyBaseConfig {
return c
}
func (c *ProxyBaseConfig) Complete(namePrefix string) {
c.Name = lo.Ternary(namePrefix == "", "", namePrefix+".") + c.Name
c.LocalIP = util.EmptyOr(c.LocalIP, "127.0.0.1")
c.Transport.BandwidthLimitMode = util.EmptyOr(c.Transport.BandwidthLimitMode, types.BandwidthLimitModeClient)
if c.Plugin.ClientPluginOptions != nil {
c.Plugin.Complete()
}
}
func (c *ProxyBaseConfig) MarshalToMsg(m *msg.NewProxy) {
m.ProxyName = c.Name
m.ProxyType = c.Type
m.UseEncryption = c.Transport.UseEncryption
m.UseCompression = c.Transport.UseCompression
m.BandwidthLimit = c.Transport.BandwidthLimit.String()
// leave it empty for default value to reduce traffic
if c.Transport.BandwidthLimitMode != "client" {
m.BandwidthLimitMode = c.Transport.BandwidthLimitMode
}
m.Group = c.LoadBalancer.Group
m.GroupKey = c.LoadBalancer.GroupKey
m.Metas = c.Metadatas
m.Annotations = c.Annotations
}
func (c *ProxyBaseConfig) UnmarshalFromMsg(m *msg.NewProxy) {
c.Name = m.ProxyName
c.Type = m.ProxyType
c.Transport.UseEncryption = m.UseEncryption
c.Transport.UseCompression = m.UseCompression
if m.BandwidthLimit != "" {
c.Transport.BandwidthLimit, _ = types.NewBandwidthQuantity(m.BandwidthLimit)
}
if m.BandwidthLimitMode != "" {
c.Transport.BandwidthLimitMode = m.BandwidthLimitMode
}
c.LoadBalancer.Group = m.Group
c.LoadBalancer.GroupKey = m.GroupKey
c.Metadatas = m.Metas
c.Annotations = m.Annotations
}
type TypedProxyConfig struct {
Type string `json:"type"`
ProxyConfigurer
}
func (c *TypedProxyConfig) UnmarshalJSON(b []byte) error {
if len(b) == 4 && string(b) == "null" {
return errors.New("type is required")
}
typeStruct := struct {
Type string `json:"type"`
}{}
if err := json.Unmarshal(b, &typeStruct); err != nil {
return err
}
c.Type = typeStruct.Type
configurer := NewProxyConfigurerByType(ProxyType(typeStruct.Type))
if configurer == nil {
return fmt.Errorf("unknown proxy type: %s", typeStruct.Type)
}
decoder := json.NewDecoder(bytes.NewBuffer(b))
if DisallowUnknownFields {
decoder.DisallowUnknownFields()
}
if err := decoder.Decode(configurer); err != nil {
return fmt.Errorf("unmarshal ProxyConfig error: %v", err)
}
c.ProxyConfigurer = configurer
return nil
}
func (c *TypedProxyConfig) MarshalJSON() ([]byte, error) {
return json.Marshal(c.ProxyConfigurer)
}
type ProxyConfigurer interface {
Complete(namePrefix string)
GetBaseConfig() *ProxyBaseConfig
// MarshalToMsg marshals this config into a msg.NewProxy message. This
// function will be called on the frpc side.
MarshalToMsg(*msg.NewProxy)
// UnmarshalFromMsg unmarshal a msg.NewProxy message into this config.
// This function will be called on the frps side.
UnmarshalFromMsg(*msg.NewProxy)
}
type ProxyType string
const (
ProxyTypeTCP ProxyType = "tcp"
ProxyTypeUDP ProxyType = "udp"
ProxyTypeTCPMUX ProxyType = "tcpmux"
ProxyTypeHTTP ProxyType = "http"
ProxyTypeHTTPS ProxyType = "https"
ProxyTypeSTCP ProxyType = "stcp"
ProxyTypeXTCP ProxyType = "xtcp"
ProxyTypeSUDP ProxyType = "sudp"
)
var proxyConfigTypeMap = map[ProxyType]reflect.Type{
ProxyTypeTCP: reflect.TypeOf(TCPProxyConfig{}),
ProxyTypeUDP: reflect.TypeOf(UDPProxyConfig{}),
ProxyTypeHTTP: reflect.TypeOf(HTTPProxyConfig{}),
ProxyTypeHTTPS: reflect.TypeOf(HTTPSProxyConfig{}),
ProxyTypeTCPMUX: reflect.TypeOf(TCPMuxProxyConfig{}),
ProxyTypeSTCP: reflect.TypeOf(STCPProxyConfig{}),
ProxyTypeXTCP: reflect.TypeOf(XTCPProxyConfig{}),
ProxyTypeSUDP: reflect.TypeOf(SUDPProxyConfig{}),
}
func NewProxyConfigurerByType(proxyType ProxyType) ProxyConfigurer {
v, ok := proxyConfigTypeMap[proxyType]
if !ok {
return nil
}
pc := reflect.New(v).Interface().(ProxyConfigurer)
pc.GetBaseConfig().Type = string(proxyType)
return pc
}
var _ ProxyConfigurer = &TCPProxyConfig{}
type TCPProxyConfig struct {
ProxyBaseConfig
RemotePort int `json:"remotePort,omitempty"`
}
func (c *TCPProxyConfig) MarshalToMsg(m *msg.NewProxy) {
c.ProxyBaseConfig.MarshalToMsg(m)
m.RemotePort = c.RemotePort
}
func (c *TCPProxyConfig) UnmarshalFromMsg(m *msg.NewProxy) {
c.ProxyBaseConfig.UnmarshalFromMsg(m)
c.RemotePort = m.RemotePort
}
var _ ProxyConfigurer = &UDPProxyConfig{}
type UDPProxyConfig struct {
ProxyBaseConfig
RemotePort int `json:"remotePort,omitempty"`
}
func (c *UDPProxyConfig) MarshalToMsg(m *msg.NewProxy) {
c.ProxyBaseConfig.MarshalToMsg(m)
m.RemotePort = c.RemotePort
}
func (c *UDPProxyConfig) UnmarshalFromMsg(m *msg.NewProxy) {
c.ProxyBaseConfig.UnmarshalFromMsg(m)
c.RemotePort = m.RemotePort
}
var _ ProxyConfigurer = &HTTPProxyConfig{}
type HTTPProxyConfig struct {
ProxyBaseConfig
DomainConfig
Locations []string `json:"locations,omitempty"`
HTTPUser string `json:"httpUser,omitempty"`
HTTPPassword string `json:"httpPassword,omitempty"`
HostHeaderRewrite string `json:"hostHeaderRewrite,omitempty"`
RequestHeaders HeaderOperations `json:"requestHeaders,omitempty"`
ResponseHeaders HeaderOperations `json:"responseHeaders,omitempty"`
RouteByHTTPUser string `json:"routeByHTTPUser,omitempty"`
}
func (c *HTTPProxyConfig) MarshalToMsg(m *msg.NewProxy) {
c.ProxyBaseConfig.MarshalToMsg(m)
m.CustomDomains = c.CustomDomains
m.SubDomain = c.SubDomain
m.Locations = c.Locations
m.HostHeaderRewrite = c.HostHeaderRewrite
m.HTTPUser = c.HTTPUser
m.HTTPPwd = c.HTTPPassword
m.Headers = c.RequestHeaders.Set
m.ResponseHeaders = c.ResponseHeaders.Set
m.RouteByHTTPUser = c.RouteByHTTPUser
}
func (c *HTTPProxyConfig) UnmarshalFromMsg(m *msg.NewProxy) {
c.ProxyBaseConfig.UnmarshalFromMsg(m)
c.CustomDomains = m.CustomDomains
c.SubDomain = m.SubDomain
c.Locations = m.Locations
c.HostHeaderRewrite = m.HostHeaderRewrite
c.HTTPUser = m.HTTPUser
c.HTTPPassword = m.HTTPPwd
c.RequestHeaders.Set = m.Headers
c.ResponseHeaders.Set = m.ResponseHeaders
c.RouteByHTTPUser = m.RouteByHTTPUser
}
var _ ProxyConfigurer = &HTTPSProxyConfig{}
type HTTPSProxyConfig struct {
ProxyBaseConfig
DomainConfig
}
func (c *HTTPSProxyConfig) MarshalToMsg(m *msg.NewProxy) {
c.ProxyBaseConfig.MarshalToMsg(m)
m.CustomDomains = c.CustomDomains
m.SubDomain = c.SubDomain
}
func (c *HTTPSProxyConfig) UnmarshalFromMsg(m *msg.NewProxy) {
c.ProxyBaseConfig.UnmarshalFromMsg(m)
c.CustomDomains = m.CustomDomains
c.SubDomain = m.SubDomain
}
type TCPMultiplexerType string
const (
TCPMultiplexerHTTPConnect TCPMultiplexerType = "httpconnect"
)
var _ ProxyConfigurer = &TCPMuxProxyConfig{}
type TCPMuxProxyConfig struct {
ProxyBaseConfig
DomainConfig
HTTPUser string `json:"httpUser,omitempty"`
HTTPPassword string `json:"httpPassword,omitempty"`
RouteByHTTPUser string `json:"routeByHTTPUser,omitempty"`
Multiplexer string `json:"multiplexer,omitempty"`
}
func (c *TCPMuxProxyConfig) MarshalToMsg(m *msg.NewProxy) {
c.ProxyBaseConfig.MarshalToMsg(m)
m.CustomDomains = c.CustomDomains
m.SubDomain = c.SubDomain
m.Multiplexer = c.Multiplexer
m.HTTPUser = c.HTTPUser
m.HTTPPwd = c.HTTPPassword
m.RouteByHTTPUser = c.RouteByHTTPUser
}
func (c *TCPMuxProxyConfig) UnmarshalFromMsg(m *msg.NewProxy) {
c.ProxyBaseConfig.UnmarshalFromMsg(m)
c.CustomDomains = m.CustomDomains
c.SubDomain = m.SubDomain
c.Multiplexer = m.Multiplexer
c.HTTPUser = m.HTTPUser
c.HTTPPassword = m.HTTPPwd
c.RouteByHTTPUser = m.RouteByHTTPUser
}
var _ ProxyConfigurer = &STCPProxyConfig{}
type STCPProxyConfig struct {
ProxyBaseConfig
Secretkey string `json:"secretKey,omitempty"`
AllowUsers []string `json:"allowUsers,omitempty"`
}
func (c *STCPProxyConfig) MarshalToMsg(m *msg.NewProxy) {
c.ProxyBaseConfig.MarshalToMsg(m)
m.Sk = c.Secretkey
m.AllowUsers = c.AllowUsers
}
func (c *STCPProxyConfig) UnmarshalFromMsg(m *msg.NewProxy) {
c.ProxyBaseConfig.UnmarshalFromMsg(m)
c.Secretkey = m.Sk
c.AllowUsers = m.AllowUsers
}
var _ ProxyConfigurer = &XTCPProxyConfig{}
type XTCPProxyConfig struct {
ProxyBaseConfig
Secretkey string `json:"secretKey,omitempty"`
AllowUsers []string `json:"allowUsers,omitempty"`
// NatTraversal configuration for NAT traversal
NatTraversal *NatTraversalConfig `json:"natTraversal,omitempty"`
}
func (c *XTCPProxyConfig) MarshalToMsg(m *msg.NewProxy) {
c.ProxyBaseConfig.MarshalToMsg(m)
m.Sk = c.Secretkey
m.AllowUsers = c.AllowUsers
}
func (c *XTCPProxyConfig) UnmarshalFromMsg(m *msg.NewProxy) {
c.ProxyBaseConfig.UnmarshalFromMsg(m)
c.Secretkey = m.Sk
c.AllowUsers = m.AllowUsers
}
var _ ProxyConfigurer = &SUDPProxyConfig{}
type SUDPProxyConfig struct {
ProxyBaseConfig
Secretkey string `json:"secretKey,omitempty"`
AllowUsers []string `json:"allowUsers,omitempty"`
}
func (c *SUDPProxyConfig) MarshalToMsg(m *msg.NewProxy) {
c.ProxyBaseConfig.MarshalToMsg(m)
m.Sk = c.Secretkey
m.AllowUsers = c.AllowUsers
}
func (c *SUDPProxyConfig) UnmarshalFromMsg(m *msg.NewProxy) {
c.ProxyBaseConfig.UnmarshalFromMsg(m)
c.Secretkey = m.Sk
c.AllowUsers = m.AllowUsers
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/config/v1/api.go | pkg/config/v1/api.go | // Copyright 2023 The frp Authors
//
// 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 v1
type APIMetadata struct {
Version string `json:"version"`
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/config/v1/client.go | pkg/config/v1/client.go | // Copyright 2023 The frp Authors
//
// 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 v1
import (
"os"
"github.com/samber/lo"
"github.com/fatedier/frp/pkg/util/util"
)
type ClientConfig struct {
ClientCommonConfig
Proxies []TypedProxyConfig `json:"proxies,omitempty"`
Visitors []TypedVisitorConfig `json:"visitors,omitempty"`
}
type ClientCommonConfig struct {
APIMetadata
Auth AuthClientConfig `json:"auth,omitempty"`
// User specifies a prefix for proxy names to distinguish them from other
// clients. If this value is not "", proxy names will automatically be
// changed to "{user}.{proxy_name}".
User string `json:"user,omitempty"`
// ServerAddr specifies the address of the server to connect to. By
// default, this value is "0.0.0.0".
ServerAddr string `json:"serverAddr,omitempty"`
// ServerPort specifies the port to connect to the server on. By default,
// this value is 7000.
ServerPort int `json:"serverPort,omitempty"`
// STUN server to help penetrate NAT hole.
NatHoleSTUNServer string `json:"natHoleStunServer,omitempty"`
// DNSServer specifies a DNS server address for FRPC to use. If this value
// is "", the default DNS will be used.
DNSServer string `json:"dnsServer,omitempty"`
// LoginFailExit controls whether or not the client should exit after a
// failed login attempt. If false, the client will retry until a login
// attempt succeeds. By default, this value is true.
LoginFailExit *bool `json:"loginFailExit,omitempty"`
// Start specifies a set of enabled proxies by name. If this set is empty,
// all supplied proxies are enabled. By default, this value is an empty
// set.
Start []string `json:"start,omitempty"`
Log LogConfig `json:"log,omitempty"`
WebServer WebServerConfig `json:"webServer,omitempty"`
Transport ClientTransportConfig `json:"transport,omitempty"`
VirtualNet VirtualNetConfig `json:"virtualNet,omitempty"`
// FeatureGates specifies a set of feature gates to enable or disable.
// This can be used to enable alpha/beta features or disable default features.
FeatureGates map[string]bool `json:"featureGates,omitempty"`
// UDPPacketSize specifies the udp packet size
// By default, this value is 1500
UDPPacketSize int64 `json:"udpPacketSize,omitempty"`
// Client metadata info
Metadatas map[string]string `json:"metadatas,omitempty"`
// Include other config files for proxies.
IncludeConfigFiles []string `json:"includes,omitempty"`
}
func (c *ClientCommonConfig) Complete() error {
c.ServerAddr = util.EmptyOr(c.ServerAddr, "0.0.0.0")
c.ServerPort = util.EmptyOr(c.ServerPort, 7000)
c.LoginFailExit = util.EmptyOr(c.LoginFailExit, lo.ToPtr(true))
c.NatHoleSTUNServer = util.EmptyOr(c.NatHoleSTUNServer, "stun.easyvoip.com:3478")
if err := c.Auth.Complete(); err != nil {
return err
}
c.Log.Complete()
c.Transport.Complete()
c.WebServer.Complete()
c.UDPPacketSize = util.EmptyOr(c.UDPPacketSize, 1500)
return nil
}
type ClientTransportConfig struct {
// Protocol specifies the protocol to use when interacting with the server.
// Valid values are "tcp", "kcp", "quic", "websocket" and "wss". By default, this value
// is "tcp".
Protocol string `json:"protocol,omitempty"`
// The maximum amount of time a dial to server will wait for a connect to complete.
DialServerTimeout int64 `json:"dialServerTimeout,omitempty"`
// DialServerKeepAlive specifies the interval between keep-alive probes for an active network connection between frpc and frps.
// If negative, keep-alive probes are disabled.
DialServerKeepAlive int64 `json:"dialServerKeepalive,omitempty"`
// ConnectServerLocalIP specifies the address of the client bind when it connect to server.
// Note: This value only use in TCP/Websocket protocol. Not support in KCP protocol.
ConnectServerLocalIP string `json:"connectServerLocalIP,omitempty"`
// ProxyURL specifies a proxy address to connect to the server through. If
// this value is "", the server will be connected to directly. By default,
// this value is read from the "http_proxy" environment variable.
ProxyURL string `json:"proxyURL,omitempty"`
// PoolCount specifies the number of connections the client will make to
// the server in advance.
PoolCount int `json:"poolCount,omitempty"`
// TCPMux toggles TCP stream multiplexing. This allows multiple requests
// from a client to share a single TCP connection. If this value is true,
// the server must have TCP multiplexing enabled as well. By default, this
// value is true.
TCPMux *bool `json:"tcpMux,omitempty"`
// TCPMuxKeepaliveInterval specifies the keep alive interval for TCP stream multiplier.
// If TCPMux is true, heartbeat of application layer is unnecessary because it can only rely on heartbeat in TCPMux.
TCPMuxKeepaliveInterval int64 `json:"tcpMuxKeepaliveInterval,omitempty"`
// QUIC protocol options.
QUIC QUICOptions `json:"quic,omitempty"`
// HeartBeatInterval specifies at what interval heartbeats are sent to the
// server, in seconds. It is not recommended to change this value. By
// default, this value is 30. Set negative value to disable it.
HeartbeatInterval int64 `json:"heartbeatInterval,omitempty"`
// HeartBeatTimeout specifies the maximum allowed heartbeat response delay
// before the connection is terminated, in seconds. It is not recommended
// to change this value. By default, this value is 90. Set negative value to disable it.
HeartbeatTimeout int64 `json:"heartbeatTimeout,omitempty"`
// TLS specifies TLS settings for the connection to the server.
TLS TLSClientConfig `json:"tls,omitempty"`
}
func (c *ClientTransportConfig) Complete() {
c.Protocol = util.EmptyOr(c.Protocol, "tcp")
c.DialServerTimeout = util.EmptyOr(c.DialServerTimeout, 10)
c.DialServerKeepAlive = util.EmptyOr(c.DialServerKeepAlive, 7200)
c.ProxyURL = util.EmptyOr(c.ProxyURL, os.Getenv("http_proxy"))
c.PoolCount = util.EmptyOr(c.PoolCount, 1)
c.TCPMux = util.EmptyOr(c.TCPMux, lo.ToPtr(true))
c.TCPMuxKeepaliveInterval = util.EmptyOr(c.TCPMuxKeepaliveInterval, 30)
if lo.FromPtr(c.TCPMux) {
// If TCPMux is enabled, heartbeat of application layer is unnecessary because we can rely on heartbeat in tcpmux.
c.HeartbeatInterval = util.EmptyOr(c.HeartbeatInterval, -1)
c.HeartbeatTimeout = util.EmptyOr(c.HeartbeatTimeout, -1)
} else {
c.HeartbeatInterval = util.EmptyOr(c.HeartbeatInterval, 30)
c.HeartbeatTimeout = util.EmptyOr(c.HeartbeatTimeout, 90)
}
c.QUIC.Complete()
c.TLS.Complete()
}
type TLSClientConfig struct {
// TLSEnable specifies whether or not TLS should be used when communicating
// with the server. If "tls.certFile" and "tls.keyFile" are valid,
// client will load the supplied tls configuration.
// Since v0.50.0, the default value has been changed to true, and tls is enabled by default.
Enable *bool `json:"enable,omitempty"`
// If DisableCustomTLSFirstByte is set to false, frpc will establish a connection with frps using the
// first custom byte when tls is enabled.
// Since v0.50.0, the default value has been changed to true, and the first custom byte is disabled by default.
DisableCustomTLSFirstByte *bool `json:"disableCustomTLSFirstByte,omitempty"`
TLSConfig
}
func (c *TLSClientConfig) Complete() {
c.Enable = util.EmptyOr(c.Enable, lo.ToPtr(true))
c.DisableCustomTLSFirstByte = util.EmptyOr(c.DisableCustomTLSFirstByte, lo.ToPtr(true))
}
type AuthClientConfig struct {
// Method specifies what authentication method to use to
// authenticate frpc with frps. If "token" is specified - token will be
// read into login message. If "oidc" is specified - OIDC (Open ID Connect)
// token will be issued using OIDC settings. By default, this value is "token".
Method AuthMethod `json:"method,omitempty"`
// Specify whether to include auth info in additional scope.
// Current supported scopes are: "HeartBeats", "NewWorkConns".
AdditionalScopes []AuthScope `json:"additionalScopes,omitempty"`
// Token specifies the authorization token used to create keys to be sent
// to the server. The server must have a matching token for authorization
// to succeed. By default, this value is "".
Token string `json:"token,omitempty"`
// TokenSource specifies a dynamic source for the authorization token.
// This is mutually exclusive with Token field.
TokenSource *ValueSource `json:"tokenSource,omitempty"`
OIDC AuthOIDCClientConfig `json:"oidc,omitempty"`
}
func (c *AuthClientConfig) Complete() error {
c.Method = util.EmptyOr(c.Method, "token")
return nil
}
type AuthOIDCClientConfig struct {
// ClientID specifies the client ID to use to get a token in OIDC authentication.
ClientID string `json:"clientID,omitempty"`
// ClientSecret specifies the client secret to use to get a token in OIDC
// authentication.
ClientSecret string `json:"clientSecret,omitempty"`
// Audience specifies the audience of the token in OIDC authentication.
Audience string `json:"audience,omitempty"`
// Scope specifies the scope of the token in OIDC authentication.
Scope string `json:"scope,omitempty"`
// TokenEndpointURL specifies the URL which implements OIDC Token Endpoint.
// It will be used to get an OIDC token.
TokenEndpointURL string `json:"tokenEndpointURL,omitempty"`
// AdditionalEndpointParams specifies additional parameters to be sent
// this field will be transfer to map[string][]string in OIDC token generator.
AdditionalEndpointParams map[string]string `json:"additionalEndpointParams,omitempty"`
// TrustedCaFile specifies the path to a custom CA certificate file
// for verifying the OIDC token endpoint's TLS certificate.
TrustedCaFile string `json:"trustedCaFile,omitempty"`
// InsecureSkipVerify disables TLS certificate verification for the
// OIDC token endpoint. Only use this for debugging, not recommended for production.
InsecureSkipVerify bool `json:"insecureSkipVerify,omitempty"`
// ProxyURL specifies a proxy to use when connecting to the OIDC token endpoint.
// Supports http, https, socks5, and socks5h proxy protocols.
// If empty, no proxy is used for OIDC connections.
ProxyURL string `json:"proxyURL,omitempty"`
// TokenSource specifies a custom dynamic source for the authorization token.
// This is mutually exclusive with every other field of this structure.
TokenSource *ValueSource `json:"tokenSource,omitempty"`
}
type VirtualNetConfig struct {
Address string `json:"address,omitempty"`
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/config/v1/server_test.go | pkg/config/v1/server_test.go | // Copyright 2023 The frp Authors
//
// 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 v1
import (
"testing"
"github.com/samber/lo"
"github.com/stretchr/testify/require"
)
func TestServerConfigComplete(t *testing.T) {
require := require.New(t)
c := &ServerConfig{}
err := c.Complete()
require.NoError(err)
require.EqualValues("token", c.Auth.Method)
require.Equal(true, lo.FromPtr(c.Transport.TCPMux))
require.Equal(true, lo.FromPtr(c.DetailedErrorsToClient))
}
func TestAuthServerConfig_Complete(t *testing.T) {
require := require.New(t)
cfg := &AuthServerConfig{}
err := cfg.Complete()
require.NoError(err)
require.EqualValues("token", cfg.Method)
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/config/v1/proxy_plugin.go | pkg/config/v1/proxy_plugin.go | // Copyright 2023 The frp Authors
//
// 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 v1
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"reflect"
"github.com/samber/lo"
"github.com/fatedier/frp/pkg/util/util"
)
const (
PluginHTTP2HTTPS = "http2https"
PluginHTTPProxy = "http_proxy"
PluginHTTPS2HTTP = "https2http"
PluginHTTPS2HTTPS = "https2https"
PluginHTTP2HTTP = "http2http"
PluginSocks5 = "socks5"
PluginStaticFile = "static_file"
PluginUnixDomainSocket = "unix_domain_socket"
PluginTLS2Raw = "tls2raw"
PluginVirtualNet = "virtual_net"
)
var clientPluginOptionsTypeMap = map[string]reflect.Type{
PluginHTTP2HTTPS: reflect.TypeOf(HTTP2HTTPSPluginOptions{}),
PluginHTTPProxy: reflect.TypeOf(HTTPProxyPluginOptions{}),
PluginHTTPS2HTTP: reflect.TypeOf(HTTPS2HTTPPluginOptions{}),
PluginHTTPS2HTTPS: reflect.TypeOf(HTTPS2HTTPSPluginOptions{}),
PluginHTTP2HTTP: reflect.TypeOf(HTTP2HTTPPluginOptions{}),
PluginSocks5: reflect.TypeOf(Socks5PluginOptions{}),
PluginStaticFile: reflect.TypeOf(StaticFilePluginOptions{}),
PluginUnixDomainSocket: reflect.TypeOf(UnixDomainSocketPluginOptions{}),
PluginTLS2Raw: reflect.TypeOf(TLS2RawPluginOptions{}),
PluginVirtualNet: reflect.TypeOf(VirtualNetPluginOptions{}),
}
type ClientPluginOptions interface {
Complete()
}
type TypedClientPluginOptions struct {
Type string `json:"type"`
ClientPluginOptions
}
func (c *TypedClientPluginOptions) UnmarshalJSON(b []byte) error {
if len(b) == 4 && string(b) == "null" {
return nil
}
typeStruct := struct {
Type string `json:"type"`
}{}
if err := json.Unmarshal(b, &typeStruct); err != nil {
return err
}
c.Type = typeStruct.Type
if c.Type == "" {
return errors.New("plugin type is empty")
}
v, ok := clientPluginOptionsTypeMap[typeStruct.Type]
if !ok {
return fmt.Errorf("unknown plugin type: %s", typeStruct.Type)
}
options := reflect.New(v).Interface().(ClientPluginOptions)
decoder := json.NewDecoder(bytes.NewBuffer(b))
if DisallowUnknownFields {
decoder.DisallowUnknownFields()
}
if err := decoder.Decode(options); err != nil {
return fmt.Errorf("unmarshal ClientPluginOptions error: %v", err)
}
c.ClientPluginOptions = options
return nil
}
func (c *TypedClientPluginOptions) MarshalJSON() ([]byte, error) {
return json.Marshal(c.ClientPluginOptions)
}
type HTTP2HTTPSPluginOptions struct {
Type string `json:"type,omitempty"`
LocalAddr string `json:"localAddr,omitempty"`
HostHeaderRewrite string `json:"hostHeaderRewrite,omitempty"`
RequestHeaders HeaderOperations `json:"requestHeaders,omitempty"`
}
func (o *HTTP2HTTPSPluginOptions) Complete() {}
type HTTPProxyPluginOptions struct {
Type string `json:"type,omitempty"`
HTTPUser string `json:"httpUser,omitempty"`
HTTPPassword string `json:"httpPassword,omitempty"`
}
func (o *HTTPProxyPluginOptions) Complete() {}
type HTTPS2HTTPPluginOptions struct {
Type string `json:"type,omitempty"`
LocalAddr string `json:"localAddr,omitempty"`
HostHeaderRewrite string `json:"hostHeaderRewrite,omitempty"`
RequestHeaders HeaderOperations `json:"requestHeaders,omitempty"`
EnableHTTP2 *bool `json:"enableHTTP2,omitempty"`
CrtPath string `json:"crtPath,omitempty"`
KeyPath string `json:"keyPath,omitempty"`
}
func (o *HTTPS2HTTPPluginOptions) Complete() {
o.EnableHTTP2 = util.EmptyOr(o.EnableHTTP2, lo.ToPtr(true))
}
type HTTPS2HTTPSPluginOptions struct {
Type string `json:"type,omitempty"`
LocalAddr string `json:"localAddr,omitempty"`
HostHeaderRewrite string `json:"hostHeaderRewrite,omitempty"`
RequestHeaders HeaderOperations `json:"requestHeaders,omitempty"`
EnableHTTP2 *bool `json:"enableHTTP2,omitempty"`
CrtPath string `json:"crtPath,omitempty"`
KeyPath string `json:"keyPath,omitempty"`
}
func (o *HTTPS2HTTPSPluginOptions) Complete() {
o.EnableHTTP2 = util.EmptyOr(o.EnableHTTP2, lo.ToPtr(true))
}
type HTTP2HTTPPluginOptions struct {
Type string `json:"type,omitempty"`
LocalAddr string `json:"localAddr,omitempty"`
HostHeaderRewrite string `json:"hostHeaderRewrite,omitempty"`
RequestHeaders HeaderOperations `json:"requestHeaders,omitempty"`
}
func (o *HTTP2HTTPPluginOptions) Complete() {}
type Socks5PluginOptions struct {
Type string `json:"type,omitempty"`
Username string `json:"username,omitempty"`
Password string `json:"password,omitempty"`
}
func (o *Socks5PluginOptions) Complete() {}
type StaticFilePluginOptions struct {
Type string `json:"type,omitempty"`
LocalPath string `json:"localPath,omitempty"`
StripPrefix string `json:"stripPrefix,omitempty"`
HTTPUser string `json:"httpUser,omitempty"`
HTTPPassword string `json:"httpPassword,omitempty"`
}
func (o *StaticFilePluginOptions) Complete() {}
type UnixDomainSocketPluginOptions struct {
Type string `json:"type,omitempty"`
UnixPath string `json:"unixPath,omitempty"`
}
func (o *UnixDomainSocketPluginOptions) Complete() {}
type TLS2RawPluginOptions struct {
Type string `json:"type,omitempty"`
LocalAddr string `json:"localAddr,omitempty"`
CrtPath string `json:"crtPath,omitempty"`
KeyPath string `json:"keyPath,omitempty"`
}
func (o *TLS2RawPluginOptions) Complete() {}
type VirtualNetPluginOptions struct {
Type string `json:"type,omitempty"`
}
func (o *VirtualNetPluginOptions) Complete() {}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/config/v1/value_source.go | pkg/config/v1/value_source.go | // Copyright 2025 The frp Authors
//
// 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 v1
import (
"context"
"errors"
"fmt"
"os"
"os/exec"
"strings"
)
// ValueSource provides a way to dynamically resolve configuration values
// from various sources like files, environment variables, or external services.
type ValueSource struct {
Type string `json:"type"`
File *FileSource `json:"file,omitempty"`
Exec *ExecSource `json:"exec,omitempty"`
}
// FileSource specifies how to load a value from a file.
type FileSource struct {
Path string `json:"path"`
}
// ExecSource specifies how to get a value from another program launched as subprocess.
type ExecSource struct {
Command string `json:"command"`
Args []string `json:"args,omitempty"`
Env []ExecEnvVar `json:"env,omitempty"`
}
type ExecEnvVar struct {
Name string `json:"name"`
Value string `json:"value"`
}
// Validate validates the ValueSource configuration.
func (v *ValueSource) Validate() error {
if v == nil {
return errors.New("valueSource cannot be nil")
}
switch v.Type {
case "file":
if v.File == nil {
return errors.New("file configuration is required when type is 'file'")
}
return v.File.Validate()
case "exec":
if v.Exec == nil {
return errors.New("exec configuration is required when type is 'exec'")
}
return v.Exec.Validate()
default:
return fmt.Errorf("unsupported value source type: %s (only 'file' and 'exec' are supported)", v.Type)
}
}
// Resolve resolves the value from the configured source.
func (v *ValueSource) Resolve(ctx context.Context) (string, error) {
if err := v.Validate(); err != nil {
return "", err
}
switch v.Type {
case "file":
return v.File.Resolve(ctx)
case "exec":
return v.Exec.Resolve(ctx)
default:
return "", fmt.Errorf("unsupported value source type: %s", v.Type)
}
}
// Validate validates the FileSource configuration.
func (f *FileSource) Validate() error {
if f == nil {
return errors.New("fileSource cannot be nil")
}
if f.Path == "" {
return errors.New("file path cannot be empty")
}
return nil
}
// Resolve reads and returns the content from the specified file.
func (f *FileSource) Resolve(_ context.Context) (string, error) {
if err := f.Validate(); err != nil {
return "", err
}
content, err := os.ReadFile(f.Path)
if err != nil {
return "", fmt.Errorf("failed to read file %s: %v", f.Path, err)
}
// Trim whitespace, which is important for file-based tokens
return strings.TrimSpace(string(content)), nil
}
// Validate validates the ExecSource configuration.
func (e *ExecSource) Validate() error {
if e == nil {
return errors.New("execSource cannot be nil")
}
if e.Command == "" {
return errors.New("exec command cannot be empty")
}
for _, env := range e.Env {
if env.Name == "" {
return errors.New("exec env name cannot be empty")
}
if strings.Contains(env.Name, "=") {
return errors.New("exec env name cannot contain '='")
}
}
return nil
}
// Resolve reads and returns the content captured from stdout of launched subprocess.
func (e *ExecSource) Resolve(ctx context.Context) (string, error) {
if err := e.Validate(); err != nil {
return "", err
}
cmd := exec.CommandContext(ctx, e.Command, e.Args...)
if len(e.Env) != 0 {
cmd.Env = os.Environ()
for _, env := range e.Env {
cmd.Env = append(cmd.Env, env.Name+"="+env.Value)
}
}
content, err := cmd.Output()
if err != nil {
return "", fmt.Errorf("failed to execute command %v: %v", e.Command, err)
}
// Trim whitespace, which is important for exec-based tokens
return strings.TrimSpace(string(content)), nil
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/config/v1/proxy_test.go | pkg/config/v1/proxy_test.go | // Copyright 2023 The frp Authors
//
// 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 v1
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/require"
)
func TestUnmarshalTypedProxyConfig(t *testing.T) {
require := require.New(t)
proxyConfigs := struct {
Proxies []TypedProxyConfig `json:"proxies,omitempty"`
}{}
strs := `{
"proxies": [
{
"type": "tcp",
"localPort": 22,
"remotePort": 6000
},
{
"type": "http",
"localPort": 80,
"customDomains": ["www.example.com"]
}
]
}`
err := json.Unmarshal([]byte(strs), &proxyConfigs)
require.NoError(err)
require.IsType(&TCPProxyConfig{}, proxyConfigs.Proxies[0].ProxyConfigurer)
require.IsType(&HTTPProxyConfig{}, proxyConfigs.Proxies[1].ProxyConfigurer)
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/config/v1/client_test.go | pkg/config/v1/client_test.go | // Copyright 2023 The frp Authors
//
// 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 v1
import (
"testing"
"github.com/samber/lo"
"github.com/stretchr/testify/require"
)
func TestClientConfigComplete(t *testing.T) {
require := require.New(t)
c := &ClientConfig{}
err := c.Complete()
require.NoError(err)
require.EqualValues("token", c.Auth.Method)
require.Equal(true, lo.FromPtr(c.Transport.TCPMux))
require.Equal(true, lo.FromPtr(c.LoginFailExit))
require.Equal(true, lo.FromPtr(c.Transport.TLS.Enable))
require.Equal(true, lo.FromPtr(c.Transport.TLS.DisableCustomTLSFirstByte))
require.NotEmpty(c.NatHoleSTUNServer)
}
func TestAuthClientConfig_Complete(t *testing.T) {
require := require.New(t)
cfg := &AuthClientConfig{}
err := cfg.Complete()
require.NoError(err)
require.EqualValues("token", cfg.Method)
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/config/v1/server.go | pkg/config/v1/server.go | // Copyright 2023 The frp Authors
//
// 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 v1
import (
"github.com/samber/lo"
"github.com/fatedier/frp/pkg/config/types"
"github.com/fatedier/frp/pkg/util/util"
)
type ServerConfig struct {
APIMetadata
Auth AuthServerConfig `json:"auth,omitempty"`
// BindAddr specifies the address that the server binds to. By default,
// this value is "0.0.0.0".
BindAddr string `json:"bindAddr,omitempty"`
// BindPort specifies the port that the server listens on. By default, this
// value is 7000.
BindPort int `json:"bindPort,omitempty"`
// KCPBindPort specifies the KCP port that the server listens on. If this
// value is 0, the server will not listen for KCP connections.
KCPBindPort int `json:"kcpBindPort,omitempty"`
// QUICBindPort specifies the QUIC port that the server listens on.
// Set this value to 0 will disable this feature.
QUICBindPort int `json:"quicBindPort,omitempty"`
// ProxyBindAddr specifies the address that the proxy binds to. This value
// may be the same as BindAddr.
ProxyBindAddr string `json:"proxyBindAddr,omitempty"`
// VhostHTTPPort specifies the port that the server listens for HTTP Vhost
// requests. If this value is 0, the server will not listen for HTTP
// requests.
VhostHTTPPort int `json:"vhostHTTPPort,omitempty"`
// VhostHTTPTimeout specifies the response header timeout for the Vhost
// HTTP server, in seconds. By default, this value is 60.
VhostHTTPTimeout int64 `json:"vhostHTTPTimeout,omitempty"`
// VhostHTTPSPort specifies the port that the server listens for HTTPS
// Vhost requests. If this value is 0, the server will not listen for HTTPS
// requests.
VhostHTTPSPort int `json:"vhostHTTPSPort,omitempty"`
// TCPMuxHTTPConnectPort specifies the port that the server listens for TCP
// HTTP CONNECT requests. If the value is 0, the server will not multiplex TCP
// requests on one single port. If it's not - it will listen on this value for
// HTTP CONNECT requests.
TCPMuxHTTPConnectPort int `json:"tcpmuxHTTPConnectPort,omitempty"`
// If TCPMuxPassthrough is true, frps won't do any update on traffic.
TCPMuxPassthrough bool `json:"tcpmuxPassthrough,omitempty"`
// SubDomainHost specifies the domain that will be attached to sub-domains
// requested by the client when using Vhost proxying. For example, if this
// value is set to "frps.com" and the client requested the subdomain
// "test", the resulting URL would be "test.frps.com".
SubDomainHost string `json:"subDomainHost,omitempty"`
// Custom404Page specifies a path to a custom 404 page to display. If this
// value is "", a default page will be displayed.
Custom404Page string `json:"custom404Page,omitempty"`
SSHTunnelGateway SSHTunnelGateway `json:"sshTunnelGateway,omitempty"`
WebServer WebServerConfig `json:"webServer,omitempty"`
// EnablePrometheus will export prometheus metrics on webserver address
// in /metrics api.
EnablePrometheus bool `json:"enablePrometheus,omitempty"`
Log LogConfig `json:"log,omitempty"`
Transport ServerTransportConfig `json:"transport,omitempty"`
// DetailedErrorsToClient defines whether to send the specific error (with
// debug info) to frpc. By default, this value is true.
DetailedErrorsToClient *bool `json:"detailedErrorsToClient,omitempty"`
// MaxPortsPerClient specifies the maximum number of ports a single client
// may proxy to. If this value is 0, no limit will be applied.
MaxPortsPerClient int64 `json:"maxPortsPerClient,omitempty"`
// UserConnTimeout specifies the maximum time to wait for a work
// connection. By default, this value is 10.
UserConnTimeout int64 `json:"userConnTimeout,omitempty"`
// UDPPacketSize specifies the UDP packet size
// By default, this value is 1500
UDPPacketSize int64 `json:"udpPacketSize,omitempty"`
// NatHoleAnalysisDataReserveHours specifies the hours to reserve nat hole analysis data.
NatHoleAnalysisDataReserveHours int64 `json:"natholeAnalysisDataReserveHours,omitempty"`
AllowPorts []types.PortsRange `json:"allowPorts,omitempty"`
HTTPPlugins []HTTPPluginOptions `json:"httpPlugins,omitempty"`
}
func (c *ServerConfig) Complete() error {
if err := c.Auth.Complete(); err != nil {
return err
}
c.Log.Complete()
c.Transport.Complete()
c.WebServer.Complete()
c.SSHTunnelGateway.Complete()
c.BindAddr = util.EmptyOr(c.BindAddr, "0.0.0.0")
c.BindPort = util.EmptyOr(c.BindPort, 7000)
if c.ProxyBindAddr == "" {
c.ProxyBindAddr = c.BindAddr
}
if c.WebServer.Port > 0 {
c.WebServer.Addr = util.EmptyOr(c.WebServer.Addr, "0.0.0.0")
}
c.VhostHTTPTimeout = util.EmptyOr(c.VhostHTTPTimeout, 60)
c.DetailedErrorsToClient = util.EmptyOr(c.DetailedErrorsToClient, lo.ToPtr(true))
c.UserConnTimeout = util.EmptyOr(c.UserConnTimeout, 10)
c.UDPPacketSize = util.EmptyOr(c.UDPPacketSize, 1500)
c.NatHoleAnalysisDataReserveHours = util.EmptyOr(c.NatHoleAnalysisDataReserveHours, 7*24)
return nil
}
type AuthServerConfig struct {
Method AuthMethod `json:"method,omitempty"`
AdditionalScopes []AuthScope `json:"additionalScopes,omitempty"`
Token string `json:"token,omitempty"`
TokenSource *ValueSource `json:"tokenSource,omitempty"`
OIDC AuthOIDCServerConfig `json:"oidc,omitempty"`
}
func (c *AuthServerConfig) Complete() error {
c.Method = util.EmptyOr(c.Method, "token")
return nil
}
type AuthOIDCServerConfig struct {
// Issuer specifies the issuer to verify OIDC tokens with. This issuer
// will be used to load public keys to verify signature and will be compared
// with the issuer claim in the OIDC token.
Issuer string `json:"issuer,omitempty"`
// Audience specifies the audience OIDC tokens should contain when validated.
// If this value is empty, audience ("client ID") verification will be skipped.
Audience string `json:"audience,omitempty"`
// SkipExpiryCheck specifies whether to skip checking if the OIDC token is
// expired.
SkipExpiryCheck bool `json:"skipExpiryCheck,omitempty"`
// SkipIssuerCheck specifies whether to skip checking if the OIDC token's
// issuer claim matches the issuer specified in OidcIssuer.
SkipIssuerCheck bool `json:"skipIssuerCheck,omitempty"`
}
type ServerTransportConfig struct {
// TCPMux toggles TCP stream multiplexing. This allows multiple requests
// from a client to share a single TCP connection. By default, this value
// is true.
// $HideFromDoc
TCPMux *bool `json:"tcpMux,omitempty"`
// TCPMuxKeepaliveInterval specifies the keep alive interval for TCP stream multiplier.
// If TCPMux is true, heartbeat of application layer is unnecessary because it can only rely on heartbeat in TCPMux.
TCPMuxKeepaliveInterval int64 `json:"tcpMuxKeepaliveInterval,omitempty"`
// TCPKeepAlive specifies the interval between keep-alive probes for an active network connection between frpc and frps.
// If negative, keep-alive probes are disabled.
TCPKeepAlive int64 `json:"tcpKeepalive,omitempty"`
// MaxPoolCount specifies the maximum pool size for each proxy. By default,
// this value is 5.
MaxPoolCount int64 `json:"maxPoolCount,omitempty"`
// HeartBeatTimeout specifies the maximum time to wait for a heartbeat
// before terminating the connection. It is not recommended to change this
// value. By default, this value is 90. Set negative value to disable it.
HeartbeatTimeout int64 `json:"heartbeatTimeout,omitempty"`
// QUIC options.
QUIC QUICOptions `json:"quic,omitempty"`
// TLS specifies TLS settings for the connection from the client.
TLS TLSServerConfig `json:"tls,omitempty"`
}
func (c *ServerTransportConfig) Complete() {
c.TCPMux = util.EmptyOr(c.TCPMux, lo.ToPtr(true))
c.TCPMuxKeepaliveInterval = util.EmptyOr(c.TCPMuxKeepaliveInterval, 30)
c.TCPKeepAlive = util.EmptyOr(c.TCPKeepAlive, 7200)
c.MaxPoolCount = util.EmptyOr(c.MaxPoolCount, 5)
if lo.FromPtr(c.TCPMux) {
// If TCPMux is enabled, heartbeat of application layer is unnecessary because we can rely on heartbeat in tcpmux.
c.HeartbeatTimeout = util.EmptyOr(c.HeartbeatTimeout, -1)
} else {
c.HeartbeatTimeout = util.EmptyOr(c.HeartbeatTimeout, 90)
}
c.QUIC.Complete()
if c.TLS.TrustedCaFile != "" {
c.TLS.Force = true
}
}
type TLSServerConfig struct {
// Force specifies whether to only accept TLS-encrypted connections.
Force bool `json:"force,omitempty"`
TLSConfig
}
type SSHTunnelGateway struct {
BindPort int `json:"bindPort,omitempty"`
PrivateKeyFile string `json:"privateKeyFile,omitempty"`
AutoGenPrivateKeyPath string `json:"autoGenPrivateKeyPath,omitempty"`
AuthorizedKeysFile string `json:"authorizedKeysFile,omitempty"`
}
func (c *SSHTunnelGateway) Complete() {
c.AutoGenPrivateKeyPath = util.EmptyOr(c.AutoGenPrivateKeyPath, "./.autogen_ssh_key")
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/config/v1/visitor.go | pkg/config/v1/visitor.go | // Copyright 2023 The frp Authors
//
// 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 v1
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"reflect"
"github.com/samber/lo"
"github.com/fatedier/frp/pkg/util/util"
)
type VisitorTransport struct {
UseEncryption bool `json:"useEncryption,omitempty"`
UseCompression bool `json:"useCompression,omitempty"`
}
type VisitorBaseConfig struct {
Name string `json:"name"`
Type string `json:"type"`
// Enabled controls whether this visitor is enabled. nil or true means enabled, false means disabled.
// This allows individual control over each visitor, complementing the global "start" field.
Enabled *bool `json:"enabled,omitempty"`
Transport VisitorTransport `json:"transport,omitempty"`
SecretKey string `json:"secretKey,omitempty"`
// if the server user is not set, it defaults to the current user
ServerUser string `json:"serverUser,omitempty"`
ServerName string `json:"serverName,omitempty"`
BindAddr string `json:"bindAddr,omitempty"`
// BindPort is the port that visitor listens on.
// It can be less than 0, it means don't bind to the port and only receive connections redirected from
// other visitors. (This is not supported for SUDP now)
BindPort int `json:"bindPort,omitempty"`
// Plugin specifies what plugin should be used.
Plugin TypedVisitorPluginOptions `json:"plugin,omitempty"`
}
func (c *VisitorBaseConfig) GetBaseConfig() *VisitorBaseConfig {
return c
}
func (c *VisitorBaseConfig) Complete(g *ClientCommonConfig) {
if c.BindAddr == "" {
c.BindAddr = "127.0.0.1"
}
namePrefix := ""
if g.User != "" {
namePrefix = g.User + "."
}
c.Name = namePrefix + c.Name
if c.ServerUser != "" {
c.ServerName = c.ServerUser + "." + c.ServerName
} else {
c.ServerName = namePrefix + c.ServerName
}
}
type VisitorConfigurer interface {
Complete(*ClientCommonConfig)
GetBaseConfig() *VisitorBaseConfig
}
type VisitorType string
const (
VisitorTypeSTCP VisitorType = "stcp"
VisitorTypeXTCP VisitorType = "xtcp"
VisitorTypeSUDP VisitorType = "sudp"
)
var visitorConfigTypeMap = map[VisitorType]reflect.Type{
VisitorTypeSTCP: reflect.TypeOf(STCPVisitorConfig{}),
VisitorTypeXTCP: reflect.TypeOf(XTCPVisitorConfig{}),
VisitorTypeSUDP: reflect.TypeOf(SUDPVisitorConfig{}),
}
type TypedVisitorConfig struct {
Type string `json:"type"`
VisitorConfigurer
}
func (c *TypedVisitorConfig) UnmarshalJSON(b []byte) error {
if len(b) == 4 && string(b) == "null" {
return errors.New("type is required")
}
typeStruct := struct {
Type string `json:"type"`
}{}
if err := json.Unmarshal(b, &typeStruct); err != nil {
return err
}
c.Type = typeStruct.Type
configurer := NewVisitorConfigurerByType(VisitorType(typeStruct.Type))
if configurer == nil {
return fmt.Errorf("unknown visitor type: %s", typeStruct.Type)
}
decoder := json.NewDecoder(bytes.NewBuffer(b))
if DisallowUnknownFields {
decoder.DisallowUnknownFields()
}
if err := decoder.Decode(configurer); err != nil {
return fmt.Errorf("unmarshal VisitorConfig error: %v", err)
}
c.VisitorConfigurer = configurer
return nil
}
func (c *TypedVisitorConfig) MarshalJSON() ([]byte, error) {
return json.Marshal(c.VisitorConfigurer)
}
func NewVisitorConfigurerByType(t VisitorType) VisitorConfigurer {
v, ok := visitorConfigTypeMap[t]
if !ok {
return nil
}
vc := reflect.New(v).Interface().(VisitorConfigurer)
vc.GetBaseConfig().Type = string(t)
return vc
}
var _ VisitorConfigurer = &STCPVisitorConfig{}
type STCPVisitorConfig struct {
VisitorBaseConfig
}
var _ VisitorConfigurer = &SUDPVisitorConfig{}
type SUDPVisitorConfig struct {
VisitorBaseConfig
}
var _ VisitorConfigurer = &XTCPVisitorConfig{}
type XTCPVisitorConfig struct {
VisitorBaseConfig
Protocol string `json:"protocol,omitempty"`
KeepTunnelOpen bool `json:"keepTunnelOpen,omitempty"`
MaxRetriesAnHour int `json:"maxRetriesAnHour,omitempty"`
MinRetryInterval int `json:"minRetryInterval,omitempty"`
FallbackTo string `json:"fallbackTo,omitempty"`
FallbackTimeoutMs int `json:"fallbackTimeoutMs,omitempty"`
// NatTraversal configuration for NAT traversal
NatTraversal *NatTraversalConfig `json:"natTraversal,omitempty"`
}
func (c *XTCPVisitorConfig) Complete(g *ClientCommonConfig) {
c.VisitorBaseConfig.Complete(g)
c.Protocol = util.EmptyOr(c.Protocol, "quic")
c.MaxRetriesAnHour = util.EmptyOr(c.MaxRetriesAnHour, 8)
c.MinRetryInterval = util.EmptyOr(c.MinRetryInterval, 90)
c.FallbackTimeoutMs = util.EmptyOr(c.FallbackTimeoutMs, 1000)
if c.FallbackTo != "" {
c.FallbackTo = lo.Ternary(g.User == "", "", g.User+".") + c.FallbackTo
}
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/config/v1/common.go | pkg/config/v1/common.go | // Copyright 2023 The frp Authors
//
// 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 v1
import (
"sync"
"github.com/fatedier/frp/pkg/util/util"
)
// TODO(fatedier): Due to the current implementation issue of the go json library, the UnmarshalJSON method
// of a custom struct cannot access the DisallowUnknownFields parameter of the parent decoder.
// Here, a global variable is temporarily used to control whether unknown fields are allowed.
// Once the v2 version is implemented by the community, we can switch to a standardized approach.
//
// https://github.com/golang/go/issues/41144
// https://github.com/golang/go/discussions/63397
var (
DisallowUnknownFields = false
DisallowUnknownFieldsMu sync.Mutex
)
type AuthScope string
const (
AuthScopeHeartBeats AuthScope = "HeartBeats"
AuthScopeNewWorkConns AuthScope = "NewWorkConns"
)
type AuthMethod string
const (
AuthMethodToken AuthMethod = "token"
AuthMethodOIDC AuthMethod = "oidc"
)
// QUIC protocol options
type QUICOptions struct {
KeepalivePeriod int `json:"keepalivePeriod,omitempty"`
MaxIdleTimeout int `json:"maxIdleTimeout,omitempty"`
MaxIncomingStreams int `json:"maxIncomingStreams,omitempty"`
}
func (c *QUICOptions) Complete() {
c.KeepalivePeriod = util.EmptyOr(c.KeepalivePeriod, 10)
c.MaxIdleTimeout = util.EmptyOr(c.MaxIdleTimeout, 30)
c.MaxIncomingStreams = util.EmptyOr(c.MaxIncomingStreams, 100000)
}
type WebServerConfig struct {
// This is the network address to bind on for serving the web interface and API.
// By default, this value is "127.0.0.1".
Addr string `json:"addr,omitempty"`
// Port specifies the port for the web server to listen on. If this
// value is 0, the admin server will not be started.
Port int `json:"port,omitempty"`
// User specifies the username that the web server will use for login.
User string `json:"user,omitempty"`
// Password specifies the password that the admin server will use for login.
Password string `json:"password,omitempty"`
// AssetsDir specifies the local directory that the admin server will load
// resources from. If this value is "", assets will be loaded from the
// bundled executable using embed package.
AssetsDir string `json:"assetsDir,omitempty"`
// Enable golang pprof handlers.
PprofEnable bool `json:"pprofEnable,omitempty"`
// Enable TLS if TLSConfig is not nil.
TLS *TLSConfig `json:"tls,omitempty"`
}
func (c *WebServerConfig) Complete() {
c.Addr = util.EmptyOr(c.Addr, "127.0.0.1")
}
type TLSConfig struct {
// CertFile specifies the path of the cert file that client will load.
CertFile string `json:"certFile,omitempty"`
// KeyFile specifies the path of the secret key file that client will load.
KeyFile string `json:"keyFile,omitempty"`
// TrustedCaFile specifies the path of the trusted ca file that will load.
TrustedCaFile string `json:"trustedCaFile,omitempty"`
// ServerName specifies the custom server name of tls certificate. By
// default, server name if same to ServerAddr.
ServerName string `json:"serverName,omitempty"`
}
// NatTraversalConfig defines configuration options for NAT traversal
type NatTraversalConfig struct {
// DisableAssistedAddrs disables the use of local network interfaces
// for assisted connections during NAT traversal. When enabled,
// only STUN-discovered public addresses will be used.
DisableAssistedAddrs bool `json:"disableAssistedAddrs,omitempty"`
}
type LogConfig struct {
// This is destination where frp should write the logs.
// If "console" is used, logs will be printed to stdout, otherwise,
// logs will be written to the specified file.
// By default, this value is "console".
To string `json:"to,omitempty"`
// Level specifies the minimum log level. Valid values are "trace",
// "debug", "info", "warn", and "error". By default, this value is "info".
Level string `json:"level,omitempty"`
// MaxDays specifies the maximum number of days to store log information
// before deletion.
MaxDays int64 `json:"maxDays"`
// DisablePrintColor disables log colors when log.to is "console".
DisablePrintColor bool `json:"disablePrintColor,omitempty"`
}
func (c *LogConfig) Complete() {
c.To = util.EmptyOr(c.To, "console")
c.Level = util.EmptyOr(c.Level, "info")
c.MaxDays = util.EmptyOr(c.MaxDays, 3)
}
type HTTPPluginOptions struct {
Name string `json:"name"`
Addr string `json:"addr"`
Path string `json:"path"`
Ops []string `json:"ops"`
TLSVerify bool `json:"tlsVerify,omitempty"`
}
type HeaderOperations struct {
Set map[string]string `json:"set,omitempty"`
}
type HTTPHeader struct {
Name string `json:"name"`
Value string `json:"value"`
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/config/v1/validation/proxy.go | pkg/config/v1/validation/proxy.go | // Copyright 2023 The frp Authors
//
// 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 validation
import (
"errors"
"fmt"
"slices"
"strings"
"k8s.io/apimachinery/pkg/util/validation"
v1 "github.com/fatedier/frp/pkg/config/v1"
)
func validateProxyBaseConfigForClient(c *v1.ProxyBaseConfig) error {
if c.Name == "" {
return errors.New("name should not be empty")
}
if err := ValidateAnnotations(c.Annotations); err != nil {
return err
}
if !slices.Contains([]string{"", "v1", "v2"}, c.Transport.ProxyProtocolVersion) {
return fmt.Errorf("not support proxy protocol version: %s", c.Transport.ProxyProtocolVersion)
}
if !slices.Contains([]string{"client", "server"}, c.Transport.BandwidthLimitMode) {
return fmt.Errorf("bandwidth limit mode should be client or server")
}
if c.Plugin.Type == "" {
if err := ValidatePort(c.LocalPort, "localPort"); err != nil {
return fmt.Errorf("localPort: %v", err)
}
}
if !slices.Contains([]string{"", "tcp", "http"}, c.HealthCheck.Type) {
return fmt.Errorf("not support health check type: %s", c.HealthCheck.Type)
}
if c.HealthCheck.Type != "" {
if c.HealthCheck.Type == "http" &&
c.HealthCheck.Path == "" {
return fmt.Errorf("health check path should not be empty")
}
}
if c.Plugin.Type != "" {
if err := ValidateClientPluginOptions(c.Plugin.ClientPluginOptions); err != nil {
return fmt.Errorf("plugin %s: %v", c.Plugin.Type, err)
}
}
return nil
}
func validateProxyBaseConfigForServer(c *v1.ProxyBaseConfig) error {
if err := ValidateAnnotations(c.Annotations); err != nil {
return err
}
return nil
}
func validateDomainConfigForClient(c *v1.DomainConfig) error {
if c.SubDomain == "" && len(c.CustomDomains) == 0 {
return errors.New("subdomain and custom domains should not be both empty")
}
return nil
}
func validateDomainConfigForServer(c *v1.DomainConfig, s *v1.ServerConfig) error {
for _, domain := range c.CustomDomains {
if s.SubDomainHost != "" && len(strings.Split(s.SubDomainHost, ".")) < len(strings.Split(domain, ".")) {
if strings.Contains(domain, s.SubDomainHost) {
return fmt.Errorf("custom domain [%s] should not belong to subdomain host [%s]", domain, s.SubDomainHost)
}
}
}
if c.SubDomain != "" {
if s.SubDomainHost == "" {
return errors.New("subdomain is not supported because this feature is not enabled in server")
}
if strings.Contains(c.SubDomain, ".") || strings.Contains(c.SubDomain, "*") {
return errors.New("'.' and '*' are not supported in subdomain")
}
}
return nil
}
func ValidateProxyConfigurerForClient(c v1.ProxyConfigurer) error {
base := c.GetBaseConfig()
if err := validateProxyBaseConfigForClient(base); err != nil {
return err
}
switch v := c.(type) {
case *v1.TCPProxyConfig:
return validateTCPProxyConfigForClient(v)
case *v1.UDPProxyConfig:
return validateUDPProxyConfigForClient(v)
case *v1.TCPMuxProxyConfig:
return validateTCPMuxProxyConfigForClient(v)
case *v1.HTTPProxyConfig:
return validateHTTPProxyConfigForClient(v)
case *v1.HTTPSProxyConfig:
return validateHTTPSProxyConfigForClient(v)
case *v1.STCPProxyConfig:
return validateSTCPProxyConfigForClient(v)
case *v1.XTCPProxyConfig:
return validateXTCPProxyConfigForClient(v)
case *v1.SUDPProxyConfig:
return validateSUDPProxyConfigForClient(v)
}
return errors.New("unknown proxy config type")
}
func validateTCPProxyConfigForClient(c *v1.TCPProxyConfig) error {
return nil
}
func validateUDPProxyConfigForClient(c *v1.UDPProxyConfig) error {
return nil
}
func validateTCPMuxProxyConfigForClient(c *v1.TCPMuxProxyConfig) error {
if err := validateDomainConfigForClient(&c.DomainConfig); err != nil {
return err
}
if !slices.Contains([]string{string(v1.TCPMultiplexerHTTPConnect)}, c.Multiplexer) {
return fmt.Errorf("not support multiplexer: %s", c.Multiplexer)
}
return nil
}
func validateHTTPProxyConfigForClient(c *v1.HTTPProxyConfig) error {
return validateDomainConfigForClient(&c.DomainConfig)
}
func validateHTTPSProxyConfigForClient(c *v1.HTTPSProxyConfig) error {
return validateDomainConfigForClient(&c.DomainConfig)
}
func validateSTCPProxyConfigForClient(c *v1.STCPProxyConfig) error {
return nil
}
func validateXTCPProxyConfigForClient(c *v1.XTCPProxyConfig) error {
return nil
}
func validateSUDPProxyConfigForClient(c *v1.SUDPProxyConfig) error {
return nil
}
func ValidateProxyConfigurerForServer(c v1.ProxyConfigurer, s *v1.ServerConfig) error {
base := c.GetBaseConfig()
if err := validateProxyBaseConfigForServer(base); err != nil {
return err
}
switch v := c.(type) {
case *v1.TCPProxyConfig:
return validateTCPProxyConfigForServer(v, s)
case *v1.UDPProxyConfig:
return validateUDPProxyConfigForServer(v, s)
case *v1.TCPMuxProxyConfig:
return validateTCPMuxProxyConfigForServer(v, s)
case *v1.HTTPProxyConfig:
return validateHTTPProxyConfigForServer(v, s)
case *v1.HTTPSProxyConfig:
return validateHTTPSProxyConfigForServer(v, s)
case *v1.STCPProxyConfig:
return validateSTCPProxyConfigForServer(v, s)
case *v1.XTCPProxyConfig:
return validateXTCPProxyConfigForServer(v, s)
case *v1.SUDPProxyConfig:
return validateSUDPProxyConfigForServer(v, s)
default:
return errors.New("unknown proxy config type")
}
}
func validateTCPProxyConfigForServer(c *v1.TCPProxyConfig, s *v1.ServerConfig) error {
return nil
}
func validateUDPProxyConfigForServer(c *v1.UDPProxyConfig, s *v1.ServerConfig) error {
return nil
}
func validateTCPMuxProxyConfigForServer(c *v1.TCPMuxProxyConfig, s *v1.ServerConfig) error {
if c.Multiplexer == string(v1.TCPMultiplexerHTTPConnect) &&
s.TCPMuxHTTPConnectPort == 0 {
return fmt.Errorf("tcpmux with multiplexer httpconnect not supported because this feature is not enabled in server")
}
return validateDomainConfigForServer(&c.DomainConfig, s)
}
func validateHTTPProxyConfigForServer(c *v1.HTTPProxyConfig, s *v1.ServerConfig) error {
if s.VhostHTTPPort == 0 {
return fmt.Errorf("type [http] not supported when vhost http port is not set")
}
return validateDomainConfigForServer(&c.DomainConfig, s)
}
func validateHTTPSProxyConfigForServer(c *v1.HTTPSProxyConfig, s *v1.ServerConfig) error {
if s.VhostHTTPSPort == 0 {
return fmt.Errorf("type [https] not supported when vhost https port is not set")
}
return validateDomainConfigForServer(&c.DomainConfig, s)
}
func validateSTCPProxyConfigForServer(c *v1.STCPProxyConfig, s *v1.ServerConfig) error {
return nil
}
func validateXTCPProxyConfigForServer(c *v1.XTCPProxyConfig, s *v1.ServerConfig) error {
return nil
}
func validateSUDPProxyConfigForServer(c *v1.SUDPProxyConfig, s *v1.ServerConfig) error {
return nil
}
// ValidateAnnotations validates that a set of annotations are correctly defined.
func ValidateAnnotations(annotations map[string]string) error {
if len(annotations) == 0 {
return nil
}
var errs error
for k := range annotations {
for _, msg := range validation.IsQualifiedName(strings.ToLower(k)) {
errs = AppendError(errs, fmt.Errorf("annotation key %s is invalid: %s", k, msg))
}
}
if err := ValidateAnnotationsSize(annotations); err != nil {
errs = AppendError(errs, err)
}
return errs
}
const TotalAnnotationSizeLimitB int = 256 * (1 << 10) // 256 kB
func ValidateAnnotationsSize(annotations map[string]string) error {
var totalSize int64
for k, v := range annotations {
totalSize += (int64)(len(k)) + (int64)(len(v))
}
if totalSize > (int64)(TotalAnnotationSizeLimitB) {
return fmt.Errorf("annotations size %d is larger than limit %d", totalSize, TotalAnnotationSizeLimitB)
}
return nil
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/config/v1/validation/client.go | pkg/config/v1/validation/client.go | // Copyright 2023 The frp Authors
//
// 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 validation
import (
"fmt"
"os"
"path/filepath"
"slices"
"github.com/samber/lo"
v1 "github.com/fatedier/frp/pkg/config/v1"
"github.com/fatedier/frp/pkg/policy/featuregate"
"github.com/fatedier/frp/pkg/policy/security"
)
func (v *ConfigValidator) ValidateClientCommonConfig(c *v1.ClientCommonConfig) (Warning, error) {
var (
warnings Warning
errs error
)
validators := []func() (Warning, error){
func() (Warning, error) { return validateFeatureGates(c) },
func() (Warning, error) { return v.validateAuthConfig(&c.Auth) },
func() (Warning, error) { return nil, validateLogConfig(&c.Log) },
func() (Warning, error) { return nil, validateWebServerConfig(&c.WebServer) },
func() (Warning, error) { return validateTransportConfig(&c.Transport) },
func() (Warning, error) { return validateIncludeFiles(c.IncludeConfigFiles) },
}
for _, validator := range validators {
w, err := validator()
warnings = AppendError(warnings, w)
errs = AppendError(errs, err)
}
return warnings, errs
}
func validateFeatureGates(c *v1.ClientCommonConfig) (Warning, error) {
if c.VirtualNet.Address != "" {
if !featuregate.Enabled(featuregate.VirtualNet) {
return nil, fmt.Errorf("VirtualNet feature is not enabled; enable it by setting the appropriate feature gate flag")
}
}
return nil, nil
}
func (v *ConfigValidator) validateAuthConfig(c *v1.AuthClientConfig) (Warning, error) {
var errs error
if !slices.Contains(SupportedAuthMethods, c.Method) {
errs = AppendError(errs, fmt.Errorf("invalid auth method, optional values are %v", SupportedAuthMethods))
}
if !lo.Every(SupportedAuthAdditionalScopes, c.AdditionalScopes) {
errs = AppendError(errs, fmt.Errorf("invalid auth additional scopes, optional values are %v", SupportedAuthAdditionalScopes))
}
// Validate token/tokenSource mutual exclusivity
if c.Token != "" && c.TokenSource != nil {
errs = AppendError(errs, fmt.Errorf("cannot specify both auth.token and auth.tokenSource"))
}
// Validate tokenSource if specified
if c.TokenSource != nil {
if c.TokenSource.Type == "exec" {
if err := v.ValidateUnsafeFeature(security.TokenSourceExec); err != nil {
errs = AppendError(errs, err)
}
}
if err := c.TokenSource.Validate(); err != nil {
errs = AppendError(errs, fmt.Errorf("invalid auth.tokenSource: %v", err))
}
}
if err := v.validateOIDCConfig(&c.OIDC); err != nil {
errs = AppendError(errs, err)
}
return nil, errs
}
func (v *ConfigValidator) validateOIDCConfig(c *v1.AuthOIDCClientConfig) error {
if c.TokenSource == nil {
return nil
}
var errs error
// Validate oidc.tokenSource mutual exclusivity with other fields of oidc
if c.ClientID != "" || c.ClientSecret != "" || c.Audience != "" ||
c.Scope != "" || c.TokenEndpointURL != "" || len(c.AdditionalEndpointParams) > 0 ||
c.TrustedCaFile != "" || c.InsecureSkipVerify || c.ProxyURL != "" {
errs = AppendError(errs, fmt.Errorf("cannot specify both auth.oidc.tokenSource and any other field of auth.oidc"))
}
if c.TokenSource.Type == "exec" {
if err := v.ValidateUnsafeFeature(security.TokenSourceExec); err != nil {
errs = AppendError(errs, err)
}
}
if err := c.TokenSource.Validate(); err != nil {
errs = AppendError(errs, fmt.Errorf("invalid auth.oidc.tokenSource: %v", err))
}
return errs
}
func validateTransportConfig(c *v1.ClientTransportConfig) (Warning, error) {
var (
warnings Warning
errs error
)
if c.HeartbeatTimeout > 0 && c.HeartbeatInterval > 0 {
if c.HeartbeatTimeout < c.HeartbeatInterval {
errs = AppendError(errs, fmt.Errorf("invalid transport.heartbeatTimeout, heartbeat timeout should not less than heartbeat interval"))
}
}
if !lo.FromPtr(c.TLS.Enable) {
checkTLSConfig := func(name string, value string) Warning {
if value != "" {
return fmt.Errorf("%s is invalid when transport.tls.enable is false", name)
}
return nil
}
warnings = AppendError(warnings, checkTLSConfig("transport.tls.certFile", c.TLS.CertFile))
warnings = AppendError(warnings, checkTLSConfig("transport.tls.keyFile", c.TLS.KeyFile))
warnings = AppendError(warnings, checkTLSConfig("transport.tls.trustedCaFile", c.TLS.TrustedCaFile))
}
if !slices.Contains(SupportedTransportProtocols, c.Protocol) {
errs = AppendError(errs, fmt.Errorf("invalid transport.protocol, optional values are %v", SupportedTransportProtocols))
}
return warnings, errs
}
func validateIncludeFiles(files []string) (Warning, error) {
var errs error
for _, f := range files {
absDir, err := filepath.Abs(filepath.Dir(f))
if err != nil {
errs = AppendError(errs, fmt.Errorf("include: parse directory of %s failed: %v", f, err))
continue
}
if _, err := os.Stat(absDir); os.IsNotExist(err) {
errs = AppendError(errs, fmt.Errorf("include: directory of %s not exist", f))
}
}
return nil, errs
}
func ValidateAllClientConfig(
c *v1.ClientCommonConfig,
proxyCfgs []v1.ProxyConfigurer,
visitorCfgs []v1.VisitorConfigurer,
unsafeFeatures *security.UnsafeFeatures,
) (Warning, error) {
validator := NewConfigValidator(unsafeFeatures)
var warnings Warning
if c != nil {
warning, err := validator.ValidateClientCommonConfig(c)
warnings = AppendError(warnings, warning)
if err != nil {
return warnings, err
}
}
for _, c := range proxyCfgs {
if err := ValidateProxyConfigurerForClient(c); err != nil {
return warnings, fmt.Errorf("proxy %s: %v", c.GetBaseConfig().Name, err)
}
}
for _, c := range visitorCfgs {
if err := ValidateVisitorConfigurer(c); err != nil {
return warnings, fmt.Errorf("visitor %s: %v", c.GetBaseConfig().Name, err)
}
}
return warnings, nil
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/config/v1/validation/validation.go | pkg/config/v1/validation/validation.go | // Copyright 2023 The frp Authors
//
// 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 validation
import (
"errors"
v1 "github.com/fatedier/frp/pkg/config/v1"
splugin "github.com/fatedier/frp/pkg/plugin/server"
)
var (
SupportedTransportProtocols = []string{
"tcp",
"kcp",
"quic",
"websocket",
"wss",
}
SupportedAuthMethods = []v1.AuthMethod{
"token",
"oidc",
}
SupportedAuthAdditionalScopes = []v1.AuthScope{
"HeartBeats",
"NewWorkConns",
}
SupportedLogLevels = []string{
"trace",
"debug",
"info",
"warn",
"error",
}
SupportedHTTPPluginOps = []string{
splugin.OpLogin,
splugin.OpNewProxy,
splugin.OpCloseProxy,
splugin.OpPing,
splugin.OpNewWorkConn,
splugin.OpNewUserConn,
}
)
type Warning error
func AppendError(err error, errs ...error) error {
if len(errs) == 0 {
return err
}
return errors.Join(append([]error{err}, errs...)...)
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/config/v1/validation/validator.go | pkg/config/v1/validation/validator.go | package validation
import (
"fmt"
"github.com/fatedier/frp/pkg/policy/security"
)
// ConfigValidator holds the context dependencies for configuration validation.
type ConfigValidator struct {
unsafeFeatures *security.UnsafeFeatures
}
// NewConfigValidator creates a new ConfigValidator instance.
func NewConfigValidator(unsafeFeatures *security.UnsafeFeatures) *ConfigValidator {
return &ConfigValidator{
unsafeFeatures: unsafeFeatures,
}
}
// ValidateUnsafeFeature checks if a specific unsafe feature is enabled.
func (v *ConfigValidator) ValidateUnsafeFeature(feature string) error {
if !v.unsafeFeatures.IsEnabled(feature) {
return fmt.Errorf("unsafe feature %q is not enabled. "+
"To enable it, ensure it is allowed in the configuration or command line flags", feature)
}
return nil
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/config/v1/validation/server.go | pkg/config/v1/validation/server.go | // Copyright 2023 The frp Authors
//
// 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 validation
import (
"fmt"
"slices"
"github.com/samber/lo"
v1 "github.com/fatedier/frp/pkg/config/v1"
"github.com/fatedier/frp/pkg/policy/security"
)
func (v *ConfigValidator) ValidateServerConfig(c *v1.ServerConfig) (Warning, error) {
var (
warnings Warning
errs error
)
if !slices.Contains(SupportedAuthMethods, c.Auth.Method) {
errs = AppendError(errs, fmt.Errorf("invalid auth method, optional values are %v", SupportedAuthMethods))
}
if !lo.Every(SupportedAuthAdditionalScopes, c.Auth.AdditionalScopes) {
errs = AppendError(errs, fmt.Errorf("invalid auth additional scopes, optional values are %v", SupportedAuthAdditionalScopes))
}
// Validate token/tokenSource mutual exclusivity
if c.Auth.Token != "" && c.Auth.TokenSource != nil {
errs = AppendError(errs, fmt.Errorf("cannot specify both auth.token and auth.tokenSource"))
}
// Validate tokenSource if specified
if c.Auth.TokenSource != nil {
if c.Auth.TokenSource.Type == "exec" {
if err := v.ValidateUnsafeFeature(security.TokenSourceExec); err != nil {
errs = AppendError(errs, err)
}
}
if err := c.Auth.TokenSource.Validate(); err != nil {
errs = AppendError(errs, fmt.Errorf("invalid auth.tokenSource: %v", err))
}
}
if err := validateLogConfig(&c.Log); err != nil {
errs = AppendError(errs, err)
}
if err := validateWebServerConfig(&c.WebServer); err != nil {
errs = AppendError(errs, err)
}
errs = AppendError(errs, ValidatePort(c.BindPort, "bindPort"))
errs = AppendError(errs, ValidatePort(c.KCPBindPort, "kcpBindPort"))
errs = AppendError(errs, ValidatePort(c.QUICBindPort, "quicBindPort"))
errs = AppendError(errs, ValidatePort(c.VhostHTTPPort, "vhostHTTPPort"))
errs = AppendError(errs, ValidatePort(c.VhostHTTPSPort, "vhostHTTPSPort"))
errs = AppendError(errs, ValidatePort(c.TCPMuxHTTPConnectPort, "tcpMuxHTTPConnectPort"))
for _, p := range c.HTTPPlugins {
if !lo.Every(SupportedHTTPPluginOps, p.Ops) {
errs = AppendError(errs, fmt.Errorf("invalid http plugin ops, optional values are %v", SupportedHTTPPluginOps))
}
}
return warnings, errs
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/config/v1/validation/plugin.go | pkg/config/v1/validation/plugin.go | // Copyright 2023 The frp Authors
//
// 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 validation
import (
"errors"
v1 "github.com/fatedier/frp/pkg/config/v1"
)
func ValidateClientPluginOptions(c v1.ClientPluginOptions) error {
switch v := c.(type) {
case *v1.HTTP2HTTPSPluginOptions:
return validateHTTP2HTTPSPluginOptions(v)
case *v1.HTTPS2HTTPPluginOptions:
return validateHTTPS2HTTPPluginOptions(v)
case *v1.HTTPS2HTTPSPluginOptions:
return validateHTTPS2HTTPSPluginOptions(v)
case *v1.StaticFilePluginOptions:
return validateStaticFilePluginOptions(v)
case *v1.UnixDomainSocketPluginOptions:
return validateUnixDomainSocketPluginOptions(v)
case *v1.TLS2RawPluginOptions:
return validateTLS2RawPluginOptions(v)
}
return nil
}
func validateHTTP2HTTPSPluginOptions(c *v1.HTTP2HTTPSPluginOptions) error {
if c.LocalAddr == "" {
return errors.New("localAddr is required")
}
return nil
}
func validateHTTPS2HTTPPluginOptions(c *v1.HTTPS2HTTPPluginOptions) error {
if c.LocalAddr == "" {
return errors.New("localAddr is required")
}
return nil
}
func validateHTTPS2HTTPSPluginOptions(c *v1.HTTPS2HTTPSPluginOptions) error {
if c.LocalAddr == "" {
return errors.New("localAddr is required")
}
return nil
}
func validateStaticFilePluginOptions(c *v1.StaticFilePluginOptions) error {
if c.LocalPath == "" {
return errors.New("localPath is required")
}
return nil
}
func validateUnixDomainSocketPluginOptions(c *v1.UnixDomainSocketPluginOptions) error {
if c.UnixPath == "" {
return errors.New("unixPath is required")
}
return nil
}
func validateTLS2RawPluginOptions(c *v1.TLS2RawPluginOptions) error {
if c.LocalAddr == "" {
return errors.New("localAddr is required")
}
return nil
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/config/v1/validation/visitor.go | pkg/config/v1/validation/visitor.go | // Copyright 2023 The frp Authors
//
// 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 validation
import (
"errors"
"fmt"
"slices"
v1 "github.com/fatedier/frp/pkg/config/v1"
)
func ValidateVisitorConfigurer(c v1.VisitorConfigurer) error {
base := c.GetBaseConfig()
if err := validateVisitorBaseConfig(base); err != nil {
return err
}
switch v := c.(type) {
case *v1.STCPVisitorConfig:
case *v1.SUDPVisitorConfig:
case *v1.XTCPVisitorConfig:
return validateXTCPVisitorConfig(v)
default:
return errors.New("unknown visitor config type")
}
return nil
}
func validateVisitorBaseConfig(c *v1.VisitorBaseConfig) error {
if c.Name == "" {
return errors.New("name is required")
}
if c.ServerName == "" {
return errors.New("server name is required")
}
if c.BindPort == 0 {
return errors.New("bind port is required")
}
return nil
}
func validateXTCPVisitorConfig(c *v1.XTCPVisitorConfig) error {
if !slices.Contains([]string{"kcp", "quic"}, c.Protocol) {
return fmt.Errorf("protocol should be kcp or quic")
}
return nil
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/config/v1/validation/common.go | pkg/config/v1/validation/common.go | // Copyright 2023 The frp Authors
//
// 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 validation
import (
"fmt"
"slices"
v1 "github.com/fatedier/frp/pkg/config/v1"
)
func validateWebServerConfig(c *v1.WebServerConfig) error {
if c.TLS != nil {
if c.TLS.CertFile == "" {
return fmt.Errorf("tls.certFile must be specified when tls is enabled")
}
if c.TLS.KeyFile == "" {
return fmt.Errorf("tls.keyFile must be specified when tls is enabled")
}
}
return ValidatePort(c.Port, "webServer.port")
}
// ValidatePort checks that the network port is in range
func ValidatePort(port int, fieldPath string) error {
if 0 <= port && port <= 65535 {
return nil
}
return fmt.Errorf("%s: port number %d must be in the range 0..65535", fieldPath, port)
}
func validateLogConfig(c *v1.LogConfig) error {
if !slices.Contains(SupportedLogLevels, c.Level) {
return fmt.Errorf("invalid log level, optional values are %v", SupportedLogLevels)
}
return nil
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/config/types/types_test.go | pkg/config/types/types_test.go | // Copyright 2019 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 types
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/require"
)
type Wrap struct {
B BandwidthQuantity `json:"b"`
Int int `json:"int"`
}
func TestBandwidthQuantity(t *testing.T) {
require := require.New(t)
var w Wrap
err := json.Unmarshal([]byte(`{"b":"1KB","int":5}`), &w)
require.NoError(err)
require.EqualValues(1*KB, w.B.Bytes())
buf, err := json.Marshal(&w)
require.NoError(err)
require.Equal(`{"b":"1KB","int":5}`, string(buf))
}
func TestPortsRangeSlice2String(t *testing.T) {
require := require.New(t)
ports := []PortsRange{
{
Start: 1000,
End: 2000,
},
{
Single: 3000,
},
}
str := PortsRangeSlice(ports).String()
require.Equal("1000-2000,3000", str)
}
func TestNewPortsRangeSliceFromString(t *testing.T) {
require := require.New(t)
ports, err := NewPortsRangeSliceFromString("1000-2000,3000")
require.NoError(err)
require.Equal([]PortsRange{
{
Start: 1000,
End: 2000,
},
{
Single: 3000,
},
}, ports)
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/config/types/types.go | pkg/config/types/types.go | // Copyright 2019 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 types
import (
"encoding/json"
"errors"
"fmt"
"strconv"
"strings"
)
const (
MB = 1024 * 1024
KB = 1024
BandwidthLimitModeClient = "client"
BandwidthLimitModeServer = "server"
)
type BandwidthQuantity struct {
s string // MB or KB
i int64 // bytes
}
func NewBandwidthQuantity(s string) (BandwidthQuantity, error) {
q := BandwidthQuantity{}
err := q.UnmarshalString(s)
if err != nil {
return q, err
}
return q, nil
}
func (q *BandwidthQuantity) Equal(u *BandwidthQuantity) bool {
if q == nil && u == nil {
return true
}
if q != nil && u != nil {
return q.i == u.i
}
return false
}
func (q *BandwidthQuantity) String() string {
return q.s
}
func (q *BandwidthQuantity) UnmarshalString(s string) error {
s = strings.TrimSpace(s)
if s == "" {
return nil
}
var (
base int64
f float64
err error
)
switch {
case strings.HasSuffix(s, "MB"):
base = MB
fstr := strings.TrimSuffix(s, "MB")
f, err = strconv.ParseFloat(fstr, 64)
if err != nil {
return err
}
case strings.HasSuffix(s, "KB"):
base = KB
fstr := strings.TrimSuffix(s, "KB")
f, err = strconv.ParseFloat(fstr, 64)
if err != nil {
return err
}
default:
return errors.New("unit not support")
}
q.s = s
q.i = int64(f * float64(base))
return nil
}
func (q *BandwidthQuantity) UnmarshalJSON(b []byte) error {
if len(b) == 4 && string(b) == "null" {
return nil
}
var str string
err := json.Unmarshal(b, &str)
if err != nil {
return err
}
return q.UnmarshalString(str)
}
func (q *BandwidthQuantity) MarshalJSON() ([]byte, error) {
return []byte("\"" + q.s + "\""), nil
}
func (q *BandwidthQuantity) Bytes() int64 {
return q.i
}
type PortsRange struct {
Start int `json:"start,omitempty"`
End int `json:"end,omitempty"`
Single int `json:"single,omitempty"`
}
type PortsRangeSlice []PortsRange
func (p PortsRangeSlice) String() string {
if len(p) == 0 {
return ""
}
strs := []string{}
for _, v := range p {
if v.Single > 0 {
strs = append(strs, strconv.Itoa(v.Single))
} else {
strs = append(strs, strconv.Itoa(v.Start)+"-"+strconv.Itoa(v.End))
}
}
return strings.Join(strs, ",")
}
// the format of str is like "1000-2000,3000,4000-5000"
func NewPortsRangeSliceFromString(str string) ([]PortsRange, error) {
str = strings.TrimSpace(str)
out := []PortsRange{}
numRanges := strings.Split(str, ",")
for _, numRangeStr := range numRanges {
// 1000-2000 or 2001
numArray := strings.Split(numRangeStr, "-")
// length: only 1 or 2 is correct
rangeType := len(numArray)
switch rangeType {
case 1:
// single number
singleNum, err := strconv.ParseInt(strings.TrimSpace(numArray[0]), 10, 64)
if err != nil {
return nil, fmt.Errorf("range number is invalid, %v", err)
}
out = append(out, PortsRange{Single: int(singleNum)})
case 2:
// range numbers
minNum, err := strconv.ParseInt(strings.TrimSpace(numArray[0]), 10, 64)
if err != nil {
return nil, fmt.Errorf("range number is invalid, %v", err)
}
maxNum, err := strconv.ParseInt(strings.TrimSpace(numArray[1]), 10, 64)
if err != nil {
return nil, fmt.Errorf("range number is invalid, %v", err)
}
if maxNum < minNum {
return nil, fmt.Errorf("range number is invalid")
}
out = append(out, PortsRange{Start: int(minNum), End: int(maxNum)})
default:
return nil, fmt.Errorf("range number is invalid")
}
}
return out, nil
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/config/legacy/proxy.go | pkg/config/legacy/proxy.go | // Copyright 2023 The frp Authors
//
// 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 legacy
import (
"fmt"
"reflect"
"gopkg.in/ini.v1"
"github.com/fatedier/frp/pkg/config/types"
)
type ProxyType string
const (
ProxyTypeTCP ProxyType = "tcp"
ProxyTypeUDP ProxyType = "udp"
ProxyTypeTCPMUX ProxyType = "tcpmux"
ProxyTypeHTTP ProxyType = "http"
ProxyTypeHTTPS ProxyType = "https"
ProxyTypeSTCP ProxyType = "stcp"
ProxyTypeXTCP ProxyType = "xtcp"
ProxyTypeSUDP ProxyType = "sudp"
)
// Proxy
var (
proxyConfTypeMap = map[ProxyType]reflect.Type{
ProxyTypeTCP: reflect.TypeOf(TCPProxyConf{}),
ProxyTypeUDP: reflect.TypeOf(UDPProxyConf{}),
ProxyTypeTCPMUX: reflect.TypeOf(TCPMuxProxyConf{}),
ProxyTypeHTTP: reflect.TypeOf(HTTPProxyConf{}),
ProxyTypeHTTPS: reflect.TypeOf(HTTPSProxyConf{}),
ProxyTypeSTCP: reflect.TypeOf(STCPProxyConf{}),
ProxyTypeXTCP: reflect.TypeOf(XTCPProxyConf{}),
ProxyTypeSUDP: reflect.TypeOf(SUDPProxyConf{}),
}
)
type ProxyConf interface {
// GetBaseConfig returns the BaseProxyConf for this config.
GetBaseConfig() *BaseProxyConf
// UnmarshalFromIni unmarshals a ini.Section into this config. This function
// will be called on the frpc side.
UnmarshalFromIni(string, string, *ini.Section) error
}
func NewConfByType(proxyType ProxyType) ProxyConf {
v, ok := proxyConfTypeMap[proxyType]
if !ok {
return nil
}
cfg := reflect.New(v).Interface().(ProxyConf)
return cfg
}
// Proxy Conf Loader
// DefaultProxyConf creates a empty ProxyConf object by proxyType.
// If proxyType doesn't exist, return nil.
func DefaultProxyConf(proxyType ProxyType) ProxyConf {
return NewConfByType(proxyType)
}
// Proxy loaded from ini
func NewProxyConfFromIni(prefix, name string, section *ini.Section) (ProxyConf, error) {
// section.Key: if key not exists, section will set it with default value.
proxyType := ProxyType(section.Key("type").String())
if proxyType == "" {
proxyType = ProxyTypeTCP
}
conf := DefaultProxyConf(proxyType)
if conf == nil {
return nil, fmt.Errorf("invalid type [%s]", proxyType)
}
if err := conf.UnmarshalFromIni(prefix, name, section); err != nil {
return nil, err
}
return conf, nil
}
// LocalSvrConf configures what location the client will to, or what
// plugin will be used.
type LocalSvrConf struct {
// LocalIP specifies the IP address or host name to to.
LocalIP string `ini:"local_ip" json:"local_ip"`
// LocalPort specifies the port to to.
LocalPort int `ini:"local_port" json:"local_port"`
// Plugin specifies what plugin should be used for ng. If this value
// is set, the LocalIp and LocalPort values will be ignored. By default,
// this value is "".
Plugin string `ini:"plugin" json:"plugin"`
// PluginParams specify parameters to be passed to the plugin, if one is
// being used. By default, this value is an empty map.
PluginParams map[string]string `ini:"-"`
}
// HealthCheckConf configures health checking. This can be useful for load
// balancing purposes to detect and remove proxies to failing services.
type HealthCheckConf struct {
// HealthCheckType specifies what protocol to use for health checking.
// Valid values include "tcp", "http", and "". If this value is "", health
// checking will not be performed. By default, this value is "".
//
// If the type is "tcp", a connection will be attempted to the target
// server. If a connection cannot be established, the health check fails.
//
// If the type is "http", a GET request will be made to the endpoint
// specified by HealthCheckURL. If the response is not a 200, the health
// check fails.
HealthCheckType string `ini:"health_check_type" json:"health_check_type"` // tcp | http
// HealthCheckTimeoutS specifies the number of seconds to wait for a health
// check attempt to connect. If the timeout is reached, this counts as a
// health check failure. By default, this value is 3.
HealthCheckTimeoutS int `ini:"health_check_timeout_s" json:"health_check_timeout_s"`
// HealthCheckMaxFailed specifies the number of allowed failures before the
// is stopped. By default, this value is 1.
HealthCheckMaxFailed int `ini:"health_check_max_failed" json:"health_check_max_failed"`
// HealthCheckIntervalS specifies the time in seconds between health
// checks. By default, this value is 10.
HealthCheckIntervalS int `ini:"health_check_interval_s" json:"health_check_interval_s"`
// HealthCheckURL specifies the address to send health checks to if the
// health check type is "http".
HealthCheckURL string `ini:"health_check_url" json:"health_check_url"`
// HealthCheckAddr specifies the address to connect to if the health check
// type is "tcp".
HealthCheckAddr string `ini:"-"`
}
// BaseProxyConf provides configuration info that is common to all types.
type BaseProxyConf struct {
// ProxyName is the name of this
ProxyName string `ini:"name" json:"name"`
// ProxyType specifies the type of this Valid values include "tcp",
// "udp", "http", "https", "stcp", and "xtcp". By default, this value is
// "tcp".
ProxyType string `ini:"type" json:"type"`
// UseEncryption controls whether or not communication with the server will
// be encrypted. Encryption is done using the tokens supplied in the server
// and client configuration. By default, this value is false.
UseEncryption bool `ini:"use_encryption" json:"use_encryption"`
// UseCompression controls whether or not communication with the server
// will be compressed. By default, this value is false.
UseCompression bool `ini:"use_compression" json:"use_compression"`
// Group specifies which group the is a part of. The server will use
// this information to load balance proxies in the same group. If the value
// is "", this will not be in a group. By default, this value is "".
Group string `ini:"group" json:"group"`
// GroupKey specifies a group key, which should be the same among proxies
// of the same group. By default, this value is "".
GroupKey string `ini:"group_key" json:"group_key"`
// ProxyProtocolVersion specifies which protocol version to use. Valid
// values include "v1", "v2", and "". If the value is "", a protocol
// version will be automatically selected. By default, this value is "".
ProxyProtocolVersion string `ini:"proxy_protocol_version" json:"proxy_protocol_version"`
// BandwidthLimit limit the bandwidth
// 0 means no limit
BandwidthLimit types.BandwidthQuantity `ini:"bandwidth_limit" json:"bandwidth_limit"`
// BandwidthLimitMode specifies whether to limit the bandwidth on the
// client or server side. Valid values include "client" and "server".
// By default, this value is "client".
BandwidthLimitMode string `ini:"bandwidth_limit_mode" json:"bandwidth_limit_mode"`
// meta info for each proxy
Metas map[string]string `ini:"-" json:"metas"`
LocalSvrConf `ini:",extends"`
HealthCheckConf `ini:",extends"`
}
// Base
func (cfg *BaseProxyConf) GetBaseConfig() *BaseProxyConf {
return cfg
}
// BaseProxyConf apply custom logic changes.
func (cfg *BaseProxyConf) decorate(_ string, name string, section *ini.Section) error {
cfg.ProxyName = name
// metas_xxx
cfg.Metas = GetMapWithoutPrefix(section.KeysHash(), "meta_")
// bandwidth_limit
if bandwidth, err := section.GetKey("bandwidth_limit"); err == nil {
cfg.BandwidthLimit, err = types.NewBandwidthQuantity(bandwidth.String())
if err != nil {
return err
}
}
// plugin_xxx
cfg.PluginParams = GetMapByPrefix(section.KeysHash(), "plugin_")
return nil
}
type DomainConf struct {
CustomDomains []string `ini:"custom_domains" json:"custom_domains"`
SubDomain string `ini:"subdomain" json:"subdomain"`
}
type RoleServerCommonConf struct {
Role string `ini:"role" json:"role"`
Sk string `ini:"sk" json:"sk"`
AllowUsers []string `ini:"allow_users" json:"allow_users"`
}
// HTTP
type HTTPProxyConf struct {
BaseProxyConf `ini:",extends"`
DomainConf `ini:",extends"`
Locations []string `ini:"locations" json:"locations"`
HTTPUser string `ini:"http_user" json:"http_user"`
HTTPPwd string `ini:"http_pwd" json:"http_pwd"`
HostHeaderRewrite string `ini:"host_header_rewrite" json:"host_header_rewrite"`
Headers map[string]string `ini:"-" json:"headers"`
RouteByHTTPUser string `ini:"route_by_http_user" json:"route_by_http_user"`
}
func (cfg *HTTPProxyConf) UnmarshalFromIni(prefix string, name string, section *ini.Section) error {
err := preUnmarshalFromIni(cfg, prefix, name, section)
if err != nil {
return err
}
// Add custom logic unmarshal if exists
cfg.Headers = GetMapWithoutPrefix(section.KeysHash(), "header_")
return nil
}
// HTTPS
type HTTPSProxyConf struct {
BaseProxyConf `ini:",extends"`
DomainConf `ini:",extends"`
}
func (cfg *HTTPSProxyConf) UnmarshalFromIni(prefix string, name string, section *ini.Section) error {
err := preUnmarshalFromIni(cfg, prefix, name, section)
if err != nil {
return err
}
// Add custom logic unmarshal if exists
return nil
}
// TCP
type TCPProxyConf struct {
BaseProxyConf `ini:",extends"`
RemotePort int `ini:"remote_port" json:"remote_port"`
}
func (cfg *TCPProxyConf) UnmarshalFromIni(prefix string, name string, section *ini.Section) error {
err := preUnmarshalFromIni(cfg, prefix, name, section)
if err != nil {
return err
}
// Add custom logic unmarshal if exists
return nil
}
// UDP
type UDPProxyConf struct {
BaseProxyConf `ini:",extends"`
RemotePort int `ini:"remote_port" json:"remote_port"`
}
func (cfg *UDPProxyConf) UnmarshalFromIni(prefix string, name string, section *ini.Section) error {
err := preUnmarshalFromIni(cfg, prefix, name, section)
if err != nil {
return err
}
// Add custom logic unmarshal if exists
return nil
}
// TCPMux
type TCPMuxProxyConf struct {
BaseProxyConf `ini:",extends"`
DomainConf `ini:",extends"`
HTTPUser string `ini:"http_user" json:"http_user,omitempty"`
HTTPPwd string `ini:"http_pwd" json:"http_pwd,omitempty"`
RouteByHTTPUser string `ini:"route_by_http_user" json:"route_by_http_user"`
Multiplexer string `ini:"multiplexer"`
}
func (cfg *TCPMuxProxyConf) UnmarshalFromIni(prefix string, name string, section *ini.Section) error {
err := preUnmarshalFromIni(cfg, prefix, name, section)
if err != nil {
return err
}
// Add custom logic unmarshal if exists
return nil
}
// STCP
type STCPProxyConf struct {
BaseProxyConf `ini:",extends"`
RoleServerCommonConf `ini:",extends"`
}
func (cfg *STCPProxyConf) UnmarshalFromIni(prefix string, name string, section *ini.Section) error {
err := preUnmarshalFromIni(cfg, prefix, name, section)
if err != nil {
return err
}
// Add custom logic unmarshal if exists
if cfg.Role == "" {
cfg.Role = "server"
}
return nil
}
// XTCP
type XTCPProxyConf struct {
BaseProxyConf `ini:",extends"`
RoleServerCommonConf `ini:",extends"`
}
func (cfg *XTCPProxyConf) UnmarshalFromIni(prefix string, name string, section *ini.Section) error {
err := preUnmarshalFromIni(cfg, prefix, name, section)
if err != nil {
return err
}
// Add custom logic unmarshal if exists
if cfg.Role == "" {
cfg.Role = "server"
}
return nil
}
// SUDP
type SUDPProxyConf struct {
BaseProxyConf `ini:",extends"`
RoleServerCommonConf `ini:",extends"`
}
func (cfg *SUDPProxyConf) UnmarshalFromIni(prefix string, name string, section *ini.Section) error {
err := preUnmarshalFromIni(cfg, prefix, name, section)
if err != nil {
return err
}
// Add custom logic unmarshal if exists
return nil
}
func preUnmarshalFromIni(cfg ProxyConf, prefix string, name string, section *ini.Section) error {
err := section.MapTo(cfg)
if err != nil {
return err
}
err = cfg.GetBaseConfig().decorate(prefix, name, section)
if err != nil {
return err
}
return nil
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/config/legacy/client.go | pkg/config/legacy/client.go | // Copyright 2023 The frp Authors
//
// 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 legacy
import (
"fmt"
"os"
"path/filepath"
"slices"
"strings"
"gopkg.in/ini.v1"
legacyauth "github.com/fatedier/frp/pkg/auth/legacy"
"github.com/fatedier/frp/pkg/util/util"
)
// ClientCommonConf is the configuration parsed from ini.
// It contains information for a client service. It is
// recommended to use GetDefaultClientConf instead of creating this object
// directly, so that all unspecified fields have reasonable default values.
type ClientCommonConf struct {
legacyauth.ClientConfig `ini:",extends"`
// ServerAddr specifies the address of the server to connect to. By
// default, this value is "0.0.0.0".
ServerAddr string `ini:"server_addr" json:"server_addr"`
// ServerPort specifies the port to connect to the server on. By default,
// this value is 7000.
ServerPort int `ini:"server_port" json:"server_port"`
// STUN server to help penetrate NAT hole.
NatHoleSTUNServer string `ini:"nat_hole_stun_server" json:"nat_hole_stun_server"`
// The maximum amount of time a dial to server will wait for a connect to complete.
DialServerTimeout int64 `ini:"dial_server_timeout" json:"dial_server_timeout"`
// DialServerKeepAlive specifies the interval between keep-alive probes for an active network connection between frpc and frps.
// If negative, keep-alive probes are disabled.
DialServerKeepAlive int64 `ini:"dial_server_keepalive" json:"dial_server_keepalive"`
// ConnectServerLocalIP specifies the address of the client bind when it connect to server.
// By default, this value is empty.
// this value only use in TCP/Websocket protocol. Not support in KCP protocol.
ConnectServerLocalIP string `ini:"connect_server_local_ip" json:"connect_server_local_ip"`
// HTTPProxy specifies a proxy address to connect to the server through. If
// this value is "", the server will be connected to directly. By default,
// this value is read from the "http_proxy" environment variable.
HTTPProxy string `ini:"http_proxy" json:"http_proxy"`
// LogFile specifies a file where logs will be written to. This value will
// only be used if LogWay is set appropriately. By default, this value is
// "console".
LogFile string `ini:"log_file" json:"log_file"`
// LogWay specifies the way logging is managed. Valid values are "console"
// or "file". If "console" is used, logs will be printed to stdout. If
// "file" is used, logs will be printed to LogFile. By default, this value
// is "console".
LogWay string `ini:"log_way" json:"log_way"`
// LogLevel specifies the minimum log level. Valid values are "trace",
// "debug", "info", "warn", and "error". By default, this value is "info".
LogLevel string `ini:"log_level" json:"log_level"`
// LogMaxDays specifies the maximum number of days to store log information
// before deletion. This is only used if LogWay == "file". By default, this
// value is 0.
LogMaxDays int64 `ini:"log_max_days" json:"log_max_days"`
// DisableLogColor disables log colors when LogWay == "console" when set to
// true. By default, this value is false.
DisableLogColor bool `ini:"disable_log_color" json:"disable_log_color"`
// AdminAddr specifies the address that the admin server binds to. By
// default, this value is "127.0.0.1".
AdminAddr string `ini:"admin_addr" json:"admin_addr"`
// AdminPort specifies the port for the admin server to listen on. If this
// value is 0, the admin server will not be started. By default, this value
// is 0.
AdminPort int `ini:"admin_port" json:"admin_port"`
// AdminUser specifies the username that the admin server will use for
// login.
AdminUser string `ini:"admin_user" json:"admin_user"`
// AdminPwd specifies the password that the admin server will use for
// login.
AdminPwd string `ini:"admin_pwd" json:"admin_pwd"`
// AssetsDir specifies the local directory that the admin server will load
// resources from. If this value is "", assets will be loaded from the
// bundled executable using statik. By default, this value is "".
AssetsDir string `ini:"assets_dir" json:"assets_dir"`
// PoolCount specifies the number of connections the client will make to
// the server in advance. By default, this value is 0.
PoolCount int `ini:"pool_count" json:"pool_count"`
// TCPMux toggles TCP stream multiplexing. This allows multiple requests
// from a client to share a single TCP connection. If this value is true,
// the server must have TCP multiplexing enabled as well. By default, this
// value is true.
TCPMux bool `ini:"tcp_mux" json:"tcp_mux"`
// TCPMuxKeepaliveInterval specifies the keep alive interval for TCP stream multiplier.
// If TCPMux is true, heartbeat of application layer is unnecessary because it can only rely on heartbeat in TCPMux.
TCPMuxKeepaliveInterval int64 `ini:"tcp_mux_keepalive_interval" json:"tcp_mux_keepalive_interval"`
// User specifies a prefix for proxy names to distinguish them from other
// clients. If this value is not "", proxy names will automatically be
// changed to "{user}.{proxy_name}". By default, this value is "".
User string `ini:"user" json:"user"`
// DNSServer specifies a DNS server address for FRPC to use. If this value
// is "", the default DNS will be used. By default, this value is "".
DNSServer string `ini:"dns_server" json:"dns_server"`
// LoginFailExit controls whether or not the client should exit after a
// failed login attempt. If false, the client will retry until a login
// attempt succeeds. By default, this value is true.
LoginFailExit bool `ini:"login_fail_exit" json:"login_fail_exit"`
// Start specifies a set of enabled proxies by name. If this set is empty,
// all supplied proxies are enabled. By default, this value is an empty
// set.
Start []string `ini:"start" json:"start"`
// Start map[string]struct{} `json:"start"`
// Protocol specifies the protocol to use when interacting with the server.
// Valid values are "tcp", "kcp", "quic", "websocket" and "wss". By default, this value
// is "tcp".
Protocol string `ini:"protocol" json:"protocol"`
// QUIC protocol options
QUICKeepalivePeriod int `ini:"quic_keepalive_period" json:"quic_keepalive_period"`
QUICMaxIdleTimeout int `ini:"quic_max_idle_timeout" json:"quic_max_idle_timeout"`
QUICMaxIncomingStreams int `ini:"quic_max_incoming_streams" json:"quic_max_incoming_streams"`
// TLSEnable specifies whether or not TLS should be used when communicating
// with the server. If "tls_cert_file" and "tls_key_file" are valid,
// client will load the supplied tls configuration.
// Since v0.50.0, the default value has been changed to true, and tls is enabled by default.
TLSEnable bool `ini:"tls_enable" json:"tls_enable"`
// TLSCertPath specifies the path of the cert file that client will
// load. It only works when "tls_enable" is true and "tls_key_file" is valid.
TLSCertFile string `ini:"tls_cert_file" json:"tls_cert_file"`
// TLSKeyPath specifies the path of the secret key file that client
// will load. It only works when "tls_enable" is true and "tls_cert_file"
// are valid.
TLSKeyFile string `ini:"tls_key_file" json:"tls_key_file"`
// TLSTrustedCaFile specifies the path of the trusted ca file that will load.
// It only works when "tls_enable" is valid and tls configuration of server
// has been specified.
TLSTrustedCaFile string `ini:"tls_trusted_ca_file" json:"tls_trusted_ca_file"`
// TLSServerName specifies the custom server name of tls certificate. By
// default, server name if same to ServerAddr.
TLSServerName string `ini:"tls_server_name" json:"tls_server_name"`
// If the disable_custom_tls_first_byte is set to false, frpc will establish a connection with frps using the
// first custom byte when tls is enabled.
// Since v0.50.0, the default value has been changed to true, and the first custom byte is disabled by default.
DisableCustomTLSFirstByte bool `ini:"disable_custom_tls_first_byte" json:"disable_custom_tls_first_byte"`
// HeartBeatInterval specifies at what interval heartbeats are sent to the
// server, in seconds. It is not recommended to change this value. By
// default, this value is 30. Set negative value to disable it.
HeartbeatInterval int64 `ini:"heartbeat_interval" json:"heartbeat_interval"`
// HeartBeatTimeout specifies the maximum allowed heartbeat response delay
// before the connection is terminated, in seconds. It is not recommended
// to change this value. By default, this value is 90. Set negative value to disable it.
HeartbeatTimeout int64 `ini:"heartbeat_timeout" json:"heartbeat_timeout"`
// Client meta info
Metas map[string]string `ini:"-" json:"metas"`
// UDPPacketSize specifies the udp packet size
// By default, this value is 1500
UDPPacketSize int64 `ini:"udp_packet_size" json:"udp_packet_size"`
// Include other config files for proxies.
IncludeConfigFiles []string `ini:"includes" json:"includes"`
// Enable golang pprof handlers in admin listener.
// Admin port must be set first.
PprofEnable bool `ini:"pprof_enable" json:"pprof_enable"`
}
// Supported sources including: string(file path), []byte, Reader interface.
func UnmarshalClientConfFromIni(source any) (ClientCommonConf, error) {
f, err := ini.LoadSources(ini.LoadOptions{
Insensitive: false,
InsensitiveSections: false,
InsensitiveKeys: false,
IgnoreInlineComment: true,
AllowBooleanKeys: true,
}, source)
if err != nil {
return ClientCommonConf{}, err
}
s, err := f.GetSection("common")
if err != nil {
return ClientCommonConf{}, fmt.Errorf("invalid configuration file, not found [common] section")
}
common := GetDefaultClientConf()
err = s.MapTo(&common)
if err != nil {
return ClientCommonConf{}, err
}
common.Metas = GetMapWithoutPrefix(s.KeysHash(), "meta_")
common.OidcAdditionalEndpointParams = GetMapWithoutPrefix(s.KeysHash(), "oidc_additional_")
return common, nil
}
// if len(startProxy) is 0, start all
// otherwise just start proxies in startProxy map
func LoadAllProxyConfsFromIni(
prefix string,
source any,
start []string,
) (map[string]ProxyConf, map[string]VisitorConf, error) {
f, err := ini.LoadSources(ini.LoadOptions{
Insensitive: false,
InsensitiveSections: false,
InsensitiveKeys: false,
IgnoreInlineComment: true,
AllowBooleanKeys: true,
}, source)
if err != nil {
return nil, nil, err
}
proxyConfs := make(map[string]ProxyConf)
visitorConfs := make(map[string]VisitorConf)
if prefix != "" {
prefix += "."
}
startProxy := make(map[string]struct{})
for _, s := range start {
startProxy[s] = struct{}{}
}
startAll := len(startProxy) == 0
// Build template sections from range section And append to ini.File.
rangeSections := make([]*ini.Section, 0)
for _, section := range f.Sections() {
if !strings.HasPrefix(section.Name(), "range:") {
continue
}
rangeSections = append(rangeSections, section)
}
for _, section := range rangeSections {
err = renderRangeProxyTemplates(f, section)
if err != nil {
return nil, nil, fmt.Errorf("failed to render template for proxy %s: %v", section.Name(), err)
}
}
for _, section := range f.Sections() {
name := section.Name()
if name == ini.DefaultSection || name == "common" || strings.HasPrefix(name, "range:") {
continue
}
_, shouldStart := startProxy[name]
if !startAll && !shouldStart {
continue
}
roleType := section.Key("role").String()
if roleType == "" {
roleType = "server"
}
switch roleType {
case "server":
newConf, newErr := NewProxyConfFromIni(prefix, name, section)
if newErr != nil {
return nil, nil, fmt.Errorf("failed to parse proxy %s, err: %v", name, newErr)
}
proxyConfs[prefix+name] = newConf
case "visitor":
newConf, newErr := NewVisitorConfFromIni(prefix, name, section)
if newErr != nil {
return nil, nil, fmt.Errorf("failed to parse visitor %s, err: %v", name, newErr)
}
visitorConfs[prefix+name] = newConf
default:
return nil, nil, fmt.Errorf("proxy %s role should be 'server' or 'visitor'", name)
}
}
return proxyConfs, visitorConfs, nil
}
func renderRangeProxyTemplates(f *ini.File, section *ini.Section) error {
// Validation
localPortStr := section.Key("local_port").String()
remotePortStr := section.Key("remote_port").String()
if localPortStr == "" || remotePortStr == "" {
return fmt.Errorf("local_port or remote_port is empty")
}
localPorts, err := util.ParseRangeNumbers(localPortStr)
if err != nil {
return err
}
remotePorts, err := util.ParseRangeNumbers(remotePortStr)
if err != nil {
return err
}
if len(localPorts) != len(remotePorts) {
return fmt.Errorf("local ports number should be same with remote ports number")
}
if len(localPorts) == 0 {
return fmt.Errorf("local_port and remote_port is necessary")
}
// Templates
prefix := strings.TrimSpace(strings.TrimPrefix(section.Name(), "range:"))
for i := range localPorts {
tmpname := fmt.Sprintf("%s_%d", prefix, i)
tmpsection, err := f.NewSection(tmpname)
if err != nil {
return err
}
copySection(section, tmpsection)
if _, err := tmpsection.NewKey("local_port", fmt.Sprintf("%d", localPorts[i])); err != nil {
return fmt.Errorf("local_port new key in section error: %v", err)
}
if _, err := tmpsection.NewKey("remote_port", fmt.Sprintf("%d", remotePorts[i])); err != nil {
return fmt.Errorf("remote_port new key in section error: %v", err)
}
}
return nil
}
func copySection(source, target *ini.Section) {
for key, value := range source.KeysHash() {
_, _ = target.NewKey(key, value)
}
}
// GetDefaultClientConf returns a client configuration with default values.
// Note: Some default values here will be set to empty and will be converted to them
// new configuration through the 'Complete' function to set them as the default
// values of the new configuration.
func GetDefaultClientConf() ClientCommonConf {
return ClientCommonConf{
ClientConfig: legacyauth.GetDefaultClientConf(),
TCPMux: true,
LoginFailExit: true,
Protocol: "tcp",
Start: make([]string, 0),
TLSEnable: true,
DisableCustomTLSFirstByte: true,
Metas: make(map[string]string),
IncludeConfigFiles: make([]string, 0),
}
}
func (cfg *ClientCommonConf) Validate() error {
if cfg.HeartbeatTimeout > 0 && cfg.HeartbeatInterval > 0 {
if cfg.HeartbeatTimeout < cfg.HeartbeatInterval {
return fmt.Errorf("invalid heartbeat_timeout, heartbeat_timeout is less than heartbeat_interval")
}
}
if !cfg.TLSEnable {
if cfg.TLSCertFile != "" {
fmt.Println("WARNING! tls_cert_file is invalid when tls_enable is false")
}
if cfg.TLSKeyFile != "" {
fmt.Println("WARNING! tls_key_file is invalid when tls_enable is false")
}
if cfg.TLSTrustedCaFile != "" {
fmt.Println("WARNING! tls_trusted_ca_file is invalid when tls_enable is false")
}
}
if !slices.Contains([]string{"tcp", "kcp", "quic", "websocket", "wss"}, cfg.Protocol) {
return fmt.Errorf("invalid protocol")
}
for _, f := range cfg.IncludeConfigFiles {
absDir, err := filepath.Abs(filepath.Dir(f))
if err != nil {
return fmt.Errorf("include: parse directory of %s failed: %v", f, err)
}
if _, err := os.Stat(absDir); os.IsNotExist(err) {
return fmt.Errorf("include: directory of %s not exist", f)
}
}
return nil
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/config/legacy/utils.go | pkg/config/legacy/utils.go | // Copyright 2020 The frp Authors
//
// 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 legacy
import (
"strings"
)
func GetMapWithoutPrefix(set map[string]string, prefix string) map[string]string {
m := make(map[string]string)
for key, value := range set {
if strings.HasPrefix(key, prefix) {
m[strings.TrimPrefix(key, prefix)] = value
}
}
if len(m) == 0 {
return nil
}
return m
}
func GetMapByPrefix(set map[string]string, prefix string) map[string]string {
m := make(map[string]string)
for key, value := range set {
if strings.HasPrefix(key, prefix) {
m[key] = value
}
}
if len(m) == 0 {
return nil
}
return m
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/config/legacy/conversion.go | pkg/config/legacy/conversion.go | // Copyright 2023 The frp Authors
//
// 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 legacy
import (
"strings"
"github.com/samber/lo"
"github.com/fatedier/frp/pkg/config/types"
v1 "github.com/fatedier/frp/pkg/config/v1"
)
func Convert_ClientCommonConf_To_v1(conf *ClientCommonConf) *v1.ClientCommonConfig {
out := &v1.ClientCommonConfig{}
out.User = conf.User
out.Auth.Method = v1.AuthMethod(conf.AuthenticationMethod)
out.Auth.Token = conf.Token
if conf.AuthenticateHeartBeats {
out.Auth.AdditionalScopes = append(out.Auth.AdditionalScopes, v1.AuthScopeHeartBeats)
}
if conf.AuthenticateNewWorkConns {
out.Auth.AdditionalScopes = append(out.Auth.AdditionalScopes, v1.AuthScopeNewWorkConns)
}
out.Auth.OIDC.ClientID = conf.OidcClientID
out.Auth.OIDC.ClientSecret = conf.OidcClientSecret
out.Auth.OIDC.Audience = conf.OidcAudience
out.Auth.OIDC.Scope = conf.OidcScope
out.Auth.OIDC.TokenEndpointURL = conf.OidcTokenEndpointURL
out.Auth.OIDC.AdditionalEndpointParams = conf.OidcAdditionalEndpointParams
out.ServerAddr = conf.ServerAddr
out.ServerPort = conf.ServerPort
out.NatHoleSTUNServer = conf.NatHoleSTUNServer
out.Transport.DialServerTimeout = conf.DialServerTimeout
out.Transport.DialServerKeepAlive = conf.DialServerKeepAlive
out.Transport.ConnectServerLocalIP = conf.ConnectServerLocalIP
out.Transport.ProxyURL = conf.HTTPProxy
out.Transport.PoolCount = conf.PoolCount
out.Transport.TCPMux = lo.ToPtr(conf.TCPMux)
out.Transport.TCPMuxKeepaliveInterval = conf.TCPMuxKeepaliveInterval
out.Transport.Protocol = conf.Protocol
out.Transport.HeartbeatInterval = conf.HeartbeatInterval
out.Transport.HeartbeatTimeout = conf.HeartbeatTimeout
out.Transport.QUIC.KeepalivePeriod = conf.QUICKeepalivePeriod
out.Transport.QUIC.MaxIdleTimeout = conf.QUICMaxIdleTimeout
out.Transport.QUIC.MaxIncomingStreams = conf.QUICMaxIncomingStreams
out.Transport.TLS.Enable = lo.ToPtr(conf.TLSEnable)
out.Transport.TLS.DisableCustomTLSFirstByte = lo.ToPtr(conf.DisableCustomTLSFirstByte)
out.Transport.TLS.CertFile = conf.TLSCertFile
out.Transport.TLS.KeyFile = conf.TLSKeyFile
out.Transport.TLS.TrustedCaFile = conf.TLSTrustedCaFile
out.Transport.TLS.ServerName = conf.TLSServerName
out.Log.To = conf.LogFile
out.Log.Level = conf.LogLevel
out.Log.MaxDays = conf.LogMaxDays
out.Log.DisablePrintColor = conf.DisableLogColor
out.WebServer.Addr = conf.AdminAddr
out.WebServer.Port = conf.AdminPort
out.WebServer.User = conf.AdminUser
out.WebServer.Password = conf.AdminPwd
out.WebServer.AssetsDir = conf.AssetsDir
out.WebServer.PprofEnable = conf.PprofEnable
out.DNSServer = conf.DNSServer
out.LoginFailExit = lo.ToPtr(conf.LoginFailExit)
out.Start = conf.Start
out.UDPPacketSize = conf.UDPPacketSize
out.Metadatas = conf.Metas
out.IncludeConfigFiles = conf.IncludeConfigFiles
return out
}
func Convert_ServerCommonConf_To_v1(conf *ServerCommonConf) *v1.ServerConfig {
out := &v1.ServerConfig{}
out.Auth.Method = v1.AuthMethod(conf.AuthenticationMethod)
out.Auth.Token = conf.Token
if conf.AuthenticateHeartBeats {
out.Auth.AdditionalScopes = append(out.Auth.AdditionalScopes, v1.AuthScopeHeartBeats)
}
if conf.AuthenticateNewWorkConns {
out.Auth.AdditionalScopes = append(out.Auth.AdditionalScopes, v1.AuthScopeNewWorkConns)
}
out.Auth.OIDC.Audience = conf.OidcAudience
out.Auth.OIDC.Issuer = conf.OidcIssuer
out.Auth.OIDC.SkipExpiryCheck = conf.OidcSkipExpiryCheck
out.Auth.OIDC.SkipIssuerCheck = conf.OidcSkipIssuerCheck
out.BindAddr = conf.BindAddr
out.BindPort = conf.BindPort
out.KCPBindPort = conf.KCPBindPort
out.QUICBindPort = conf.QUICBindPort
out.Transport.QUIC.KeepalivePeriod = conf.QUICKeepalivePeriod
out.Transport.QUIC.MaxIdleTimeout = conf.QUICMaxIdleTimeout
out.Transport.QUIC.MaxIncomingStreams = conf.QUICMaxIncomingStreams
out.ProxyBindAddr = conf.ProxyBindAddr
out.VhostHTTPPort = conf.VhostHTTPPort
out.VhostHTTPSPort = conf.VhostHTTPSPort
out.TCPMuxHTTPConnectPort = conf.TCPMuxHTTPConnectPort
out.TCPMuxPassthrough = conf.TCPMuxPassthrough
out.VhostHTTPTimeout = conf.VhostHTTPTimeout
out.WebServer.Addr = conf.DashboardAddr
out.WebServer.Port = conf.DashboardPort
out.WebServer.User = conf.DashboardUser
out.WebServer.Password = conf.DashboardPwd
out.WebServer.AssetsDir = conf.AssetsDir
if conf.DashboardTLSMode {
out.WebServer.TLS = &v1.TLSConfig{}
out.WebServer.TLS.CertFile = conf.DashboardTLSCertFile
out.WebServer.TLS.KeyFile = conf.DashboardTLSKeyFile
out.WebServer.PprofEnable = conf.PprofEnable
}
out.EnablePrometheus = conf.EnablePrometheus
out.Log.To = conf.LogFile
out.Log.Level = conf.LogLevel
out.Log.MaxDays = conf.LogMaxDays
out.Log.DisablePrintColor = conf.DisableLogColor
out.DetailedErrorsToClient = lo.ToPtr(conf.DetailedErrorsToClient)
out.SubDomainHost = conf.SubDomainHost
out.Custom404Page = conf.Custom404Page
out.UserConnTimeout = conf.UserConnTimeout
out.UDPPacketSize = conf.UDPPacketSize
out.NatHoleAnalysisDataReserveHours = conf.NatHoleAnalysisDataReserveHours
out.Transport.TCPMux = lo.ToPtr(conf.TCPMux)
out.Transport.TCPMuxKeepaliveInterval = conf.TCPMuxKeepaliveInterval
out.Transport.TCPKeepAlive = conf.TCPKeepAlive
out.Transport.MaxPoolCount = conf.MaxPoolCount
out.Transport.HeartbeatTimeout = conf.HeartbeatTimeout
out.Transport.TLS.Force = conf.TLSOnly
out.Transport.TLS.CertFile = conf.TLSCertFile
out.Transport.TLS.KeyFile = conf.TLSKeyFile
out.Transport.TLS.TrustedCaFile = conf.TLSTrustedCaFile
out.MaxPortsPerClient = conf.MaxPortsPerClient
for _, v := range conf.HTTPPlugins {
out.HTTPPlugins = append(out.HTTPPlugins, v1.HTTPPluginOptions{
Name: v.Name,
Addr: v.Addr,
Path: v.Path,
Ops: v.Ops,
TLSVerify: v.TLSVerify,
})
}
out.AllowPorts, _ = types.NewPortsRangeSliceFromString(conf.AllowPortsStr)
return out
}
func transformHeadersFromPluginParams(params map[string]string) v1.HeaderOperations {
out := v1.HeaderOperations{}
for k, v := range params {
if !strings.HasPrefix(k, "plugin_header_") {
continue
}
if k = strings.TrimPrefix(k, "plugin_header_"); k != "" {
if out.Set == nil {
out.Set = make(map[string]string)
}
out.Set[k] = v
}
}
return out
}
func Convert_ProxyConf_To_v1_Base(conf ProxyConf) *v1.ProxyBaseConfig {
out := &v1.ProxyBaseConfig{}
base := conf.GetBaseConfig()
out.Name = base.ProxyName
out.Type = base.ProxyType
out.Metadatas = base.Metas
out.Transport.UseEncryption = base.UseEncryption
out.Transport.UseCompression = base.UseCompression
out.Transport.BandwidthLimit = base.BandwidthLimit
out.Transport.BandwidthLimitMode = base.BandwidthLimitMode
out.Transport.ProxyProtocolVersion = base.ProxyProtocolVersion
out.LoadBalancer.Group = base.Group
out.LoadBalancer.GroupKey = base.GroupKey
out.HealthCheck.Type = base.HealthCheckType
out.HealthCheck.TimeoutSeconds = base.HealthCheckTimeoutS
out.HealthCheck.MaxFailed = base.HealthCheckMaxFailed
out.HealthCheck.IntervalSeconds = base.HealthCheckIntervalS
out.HealthCheck.Path = base.HealthCheckURL
out.LocalIP = base.LocalIP
out.LocalPort = base.LocalPort
switch base.Plugin {
case "http2https":
out.Plugin.ClientPluginOptions = &v1.HTTP2HTTPSPluginOptions{
LocalAddr: base.PluginParams["plugin_local_addr"],
HostHeaderRewrite: base.PluginParams["plugin_host_header_rewrite"],
RequestHeaders: transformHeadersFromPluginParams(base.PluginParams),
}
case "http_proxy":
out.Plugin.ClientPluginOptions = &v1.HTTPProxyPluginOptions{
HTTPUser: base.PluginParams["plugin_http_user"],
HTTPPassword: base.PluginParams["plugin_http_passwd"],
}
case "https2http":
out.Plugin.ClientPluginOptions = &v1.HTTPS2HTTPPluginOptions{
LocalAddr: base.PluginParams["plugin_local_addr"],
HostHeaderRewrite: base.PluginParams["plugin_host_header_rewrite"],
RequestHeaders: transformHeadersFromPluginParams(base.PluginParams),
CrtPath: base.PluginParams["plugin_crt_path"],
KeyPath: base.PluginParams["plugin_key_path"],
}
case "https2https":
out.Plugin.ClientPluginOptions = &v1.HTTPS2HTTPSPluginOptions{
LocalAddr: base.PluginParams["plugin_local_addr"],
HostHeaderRewrite: base.PluginParams["plugin_host_header_rewrite"],
RequestHeaders: transformHeadersFromPluginParams(base.PluginParams),
CrtPath: base.PluginParams["plugin_crt_path"],
KeyPath: base.PluginParams["plugin_key_path"],
}
case "socks5":
out.Plugin.ClientPluginOptions = &v1.Socks5PluginOptions{
Username: base.PluginParams["plugin_user"],
Password: base.PluginParams["plugin_passwd"],
}
case "static_file":
out.Plugin.ClientPluginOptions = &v1.StaticFilePluginOptions{
LocalPath: base.PluginParams["plugin_local_path"],
StripPrefix: base.PluginParams["plugin_strip_prefix"],
HTTPUser: base.PluginParams["plugin_http_user"],
HTTPPassword: base.PluginParams["plugin_http_passwd"],
}
case "unix_domain_socket":
out.Plugin.ClientPluginOptions = &v1.UnixDomainSocketPluginOptions{
UnixPath: base.PluginParams["plugin_unix_path"],
}
}
out.Plugin.Type = base.Plugin
return out
}
func Convert_ProxyConf_To_v1(conf ProxyConf) v1.ProxyConfigurer {
outBase := Convert_ProxyConf_To_v1_Base(conf)
var out v1.ProxyConfigurer
switch v := conf.(type) {
case *TCPProxyConf:
c := &v1.TCPProxyConfig{ProxyBaseConfig: *outBase}
c.RemotePort = v.RemotePort
out = c
case *UDPProxyConf:
c := &v1.UDPProxyConfig{ProxyBaseConfig: *outBase}
c.RemotePort = v.RemotePort
out = c
case *HTTPProxyConf:
c := &v1.HTTPProxyConfig{ProxyBaseConfig: *outBase}
c.CustomDomains = v.CustomDomains
c.SubDomain = v.SubDomain
c.Locations = v.Locations
c.HTTPUser = v.HTTPUser
c.HTTPPassword = v.HTTPPwd
c.HostHeaderRewrite = v.HostHeaderRewrite
c.RequestHeaders.Set = v.Headers
c.RouteByHTTPUser = v.RouteByHTTPUser
out = c
case *HTTPSProxyConf:
c := &v1.HTTPSProxyConfig{ProxyBaseConfig: *outBase}
c.CustomDomains = v.CustomDomains
c.SubDomain = v.SubDomain
out = c
case *TCPMuxProxyConf:
c := &v1.TCPMuxProxyConfig{ProxyBaseConfig: *outBase}
c.CustomDomains = v.CustomDomains
c.SubDomain = v.SubDomain
c.HTTPUser = v.HTTPUser
c.HTTPPassword = v.HTTPPwd
c.RouteByHTTPUser = v.RouteByHTTPUser
c.Multiplexer = v.Multiplexer
out = c
case *STCPProxyConf:
c := &v1.STCPProxyConfig{ProxyBaseConfig: *outBase}
c.Secretkey = v.Sk
c.AllowUsers = v.AllowUsers
out = c
case *SUDPProxyConf:
c := &v1.SUDPProxyConfig{ProxyBaseConfig: *outBase}
c.Secretkey = v.Sk
c.AllowUsers = v.AllowUsers
out = c
case *XTCPProxyConf:
c := &v1.XTCPProxyConfig{ProxyBaseConfig: *outBase}
c.Secretkey = v.Sk
c.AllowUsers = v.AllowUsers
out = c
}
return out
}
func Convert_VisitorConf_To_v1_Base(conf VisitorConf) *v1.VisitorBaseConfig {
out := &v1.VisitorBaseConfig{}
base := conf.GetBaseConfig()
out.Name = base.ProxyName
out.Type = base.ProxyType
out.Transport.UseEncryption = base.UseEncryption
out.Transport.UseCompression = base.UseCompression
out.SecretKey = base.Sk
out.ServerUser = base.ServerUser
out.ServerName = base.ServerName
out.BindAddr = base.BindAddr
out.BindPort = base.BindPort
return out
}
func Convert_VisitorConf_To_v1(conf VisitorConf) v1.VisitorConfigurer {
outBase := Convert_VisitorConf_To_v1_Base(conf)
var out v1.VisitorConfigurer
switch v := conf.(type) {
case *STCPVisitorConf:
c := &v1.STCPVisitorConfig{VisitorBaseConfig: *outBase}
out = c
case *SUDPVisitorConf:
c := &v1.SUDPVisitorConfig{VisitorBaseConfig: *outBase}
out = c
case *XTCPVisitorConf:
c := &v1.XTCPVisitorConfig{VisitorBaseConfig: *outBase}
c.Protocol = v.Protocol
c.KeepTunnelOpen = v.KeepTunnelOpen
c.MaxRetriesAnHour = v.MaxRetriesAnHour
c.MinRetryInterval = v.MinRetryInterval
c.FallbackTo = v.FallbackTo
c.FallbackTimeoutMs = v.FallbackTimeoutMs
out = c
}
return out
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/config/legacy/server.go | pkg/config/legacy/server.go | // Copyright 2023 The frp Authors
//
// 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 legacy
import (
"strings"
"gopkg.in/ini.v1"
legacyauth "github.com/fatedier/frp/pkg/auth/legacy"
)
type HTTPPluginOptions struct {
Name string `ini:"name"`
Addr string `ini:"addr"`
Path string `ini:"path"`
Ops []string `ini:"ops"`
TLSVerify bool `ini:"tlsVerify"`
}
// ServerCommonConf contains information for a server service. It is
// recommended to use GetDefaultServerConf instead of creating this object
// directly, so that all unspecified fields have reasonable default values.
type ServerCommonConf struct {
legacyauth.ServerConfig `ini:",extends"`
// BindAddr specifies the address that the server binds to. By default,
// this value is "0.0.0.0".
BindAddr string `ini:"bind_addr" json:"bind_addr"`
// BindPort specifies the port that the server listens on. By default, this
// value is 7000.
BindPort int `ini:"bind_port" json:"bind_port"`
// KCPBindPort specifies the KCP port that the server listens on. If this
// value is 0, the server will not listen for KCP connections. By default,
// this value is 0.
KCPBindPort int `ini:"kcp_bind_port" json:"kcp_bind_port"`
// QUICBindPort specifies the QUIC port that the server listens on.
// Set this value to 0 will disable this feature.
// By default, the value is 0.
QUICBindPort int `ini:"quic_bind_port" json:"quic_bind_port"`
// QUIC protocol options
QUICKeepalivePeriod int `ini:"quic_keepalive_period" json:"quic_keepalive_period"`
QUICMaxIdleTimeout int `ini:"quic_max_idle_timeout" json:"quic_max_idle_timeout"`
QUICMaxIncomingStreams int `ini:"quic_max_incoming_streams" json:"quic_max_incoming_streams"`
// ProxyBindAddr specifies the address that the proxy binds to. This value
// may be the same as BindAddr.
ProxyBindAddr string `ini:"proxy_bind_addr" json:"proxy_bind_addr"`
// VhostHTTPPort specifies the port that the server listens for HTTP Vhost
// requests. If this value is 0, the server will not listen for HTTP
// requests. By default, this value is 0.
VhostHTTPPort int `ini:"vhost_http_port" json:"vhost_http_port"`
// VhostHTTPSPort specifies the port that the server listens for HTTPS
// Vhost requests. If this value is 0, the server will not listen for HTTPS
// requests. By default, this value is 0.
VhostHTTPSPort int `ini:"vhost_https_port" json:"vhost_https_port"`
// TCPMuxHTTPConnectPort specifies the port that the server listens for TCP
// HTTP CONNECT requests. If the value is 0, the server will not multiplex TCP
// requests on one single port. If it's not - it will listen on this value for
// HTTP CONNECT requests. By default, this value is 0.
TCPMuxHTTPConnectPort int `ini:"tcpmux_httpconnect_port" json:"tcpmux_httpconnect_port"`
// If TCPMuxPassthrough is true, frps won't do any update on traffic.
TCPMuxPassthrough bool `ini:"tcpmux_passthrough" json:"tcpmux_passthrough"`
// VhostHTTPTimeout specifies the response header timeout for the Vhost
// HTTP server, in seconds. By default, this value is 60.
VhostHTTPTimeout int64 `ini:"vhost_http_timeout" json:"vhost_http_timeout"`
// DashboardAddr specifies the address that the dashboard binds to. By
// default, this value is "0.0.0.0".
DashboardAddr string `ini:"dashboard_addr" json:"dashboard_addr"`
// DashboardPort specifies the port that the dashboard listens on. If this
// value is 0, the dashboard will not be started. By default, this value is
// 0.
DashboardPort int `ini:"dashboard_port" json:"dashboard_port"`
// DashboardTLSCertFile specifies the path of the cert file that the server will
// load. If "dashboard_tls_cert_file", "dashboard_tls_key_file" are valid, the server will use this
// supplied tls configuration.
DashboardTLSCertFile string `ini:"dashboard_tls_cert_file" json:"dashboard_tls_cert_file"`
// DashboardTLSKeyFile specifies the path of the secret key that the server will
// load. If "dashboard_tls_cert_file", "dashboard_tls_key_file" are valid, the server will use this
// supplied tls configuration.
DashboardTLSKeyFile string `ini:"dashboard_tls_key_file" json:"dashboard_tls_key_file"`
// DashboardTLSMode specifies the mode of the dashboard between HTTP or HTTPS modes. By
// default, this value is false, which is HTTP mode.
DashboardTLSMode bool `ini:"dashboard_tls_mode" json:"dashboard_tls_mode"`
// DashboardUser specifies the username that the dashboard will use for
// login.
DashboardUser string `ini:"dashboard_user" json:"dashboard_user"`
// DashboardPwd specifies the password that the dashboard will use for
// login.
DashboardPwd string `ini:"dashboard_pwd" json:"dashboard_pwd"`
// EnablePrometheus will export prometheus metrics on {dashboard_addr}:{dashboard_port}
// in /metrics api.
EnablePrometheus bool `ini:"enable_prometheus" json:"enable_prometheus"`
// AssetsDir specifies the local directory that the dashboard will load
// resources from. If this value is "", assets will be loaded from the
// bundled executable using statik. By default, this value is "".
AssetsDir string `ini:"assets_dir" json:"assets_dir"`
// LogFile specifies a file where logs will be written to. This value will
// only be used if LogWay is set appropriately. By default, this value is
// "console".
LogFile string `ini:"log_file" json:"log_file"`
// LogWay specifies the way logging is managed. Valid values are "console"
// or "file". If "console" is used, logs will be printed to stdout. If
// "file" is used, logs will be printed to LogFile. By default, this value
// is "console".
LogWay string `ini:"log_way" json:"log_way"`
// LogLevel specifies the minimum log level. Valid values are "trace",
// "debug", "info", "warn", and "error". By default, this value is "info".
LogLevel string `ini:"log_level" json:"log_level"`
// LogMaxDays specifies the maximum number of days to store log information
// before deletion. This is only used if LogWay == "file". By default, this
// value is 0.
LogMaxDays int64 `ini:"log_max_days" json:"log_max_days"`
// DisableLogColor disables log colors when LogWay == "console" when set to
// true. By default, this value is false.
DisableLogColor bool `ini:"disable_log_color" json:"disable_log_color"`
// DetailedErrorsToClient defines whether to send the specific error (with
// debug info) to frpc. By default, this value is true.
DetailedErrorsToClient bool `ini:"detailed_errors_to_client" json:"detailed_errors_to_client"`
// SubDomainHost specifies the domain that will be attached to sub-domains
// requested by the client when using Vhost proxying. For example, if this
// value is set to "frps.com" and the client requested the subdomain
// "test", the resulting URL would be "test.frps.com". By default, this
// value is "".
SubDomainHost string `ini:"subdomain_host" json:"subdomain_host"`
// TCPMux toggles TCP stream multiplexing. This allows multiple requests
// from a client to share a single TCP connection. By default, this value
// is true.
TCPMux bool `ini:"tcp_mux" json:"tcp_mux"`
// TCPMuxKeepaliveInterval specifies the keep alive interval for TCP stream multiplier.
// If TCPMux is true, heartbeat of application layer is unnecessary because it can only rely on heartbeat in TCPMux.
TCPMuxKeepaliveInterval int64 `ini:"tcp_mux_keepalive_interval" json:"tcp_mux_keepalive_interval"`
// TCPKeepAlive specifies the interval between keep-alive probes for an active network connection between frpc and frps.
// If negative, keep-alive probes are disabled.
TCPKeepAlive int64 `ini:"tcp_keepalive" json:"tcp_keepalive"`
// Custom404Page specifies a path to a custom 404 page to display. If this
// value is "", a default page will be displayed. By default, this value is
// "".
Custom404Page string `ini:"custom_404_page" json:"custom_404_page"`
// AllowPorts specifies a set of ports that clients are able to proxy to.
// If the length of this value is 0, all ports are allowed. By default,
// this value is an empty set.
AllowPorts map[int]struct{} `ini:"-" json:"-"`
// Original string.
AllowPortsStr string `ini:"-" json:"-"`
// MaxPoolCount specifies the maximum pool size for each proxy. By default,
// this value is 5.
MaxPoolCount int64 `ini:"max_pool_count" json:"max_pool_count"`
// MaxPortsPerClient specifies the maximum number of ports a single client
// may proxy to. If this value is 0, no limit will be applied. By default,
// this value is 0.
MaxPortsPerClient int64 `ini:"max_ports_per_client" json:"max_ports_per_client"`
// TLSOnly specifies whether to only accept TLS-encrypted connections.
// By default, the value is false.
TLSOnly bool `ini:"tls_only" json:"tls_only"`
// TLSCertFile specifies the path of the cert file that the server will
// load. If "tls_cert_file", "tls_key_file" are valid, the server will use this
// supplied tls configuration. Otherwise, the server will use the tls
// configuration generated by itself.
TLSCertFile string `ini:"tls_cert_file" json:"tls_cert_file"`
// TLSKeyFile specifies the path of the secret key that the server will
// load. If "tls_cert_file", "tls_key_file" are valid, the server will use this
// supplied tls configuration. Otherwise, the server will use the tls
// configuration generated by itself.
TLSKeyFile string `ini:"tls_key_file" json:"tls_key_file"`
// TLSTrustedCaFile specifies the paths of the client cert files that the
// server will load. It only works when "tls_only" is true. If
// "tls_trusted_ca_file" is valid, the server will verify each client's
// certificate.
TLSTrustedCaFile string `ini:"tls_trusted_ca_file" json:"tls_trusted_ca_file"`
// HeartBeatTimeout specifies the maximum time to wait for a heartbeat
// before terminating the connection. It is not recommended to change this
// value. By default, this value is 90. Set negative value to disable it.
HeartbeatTimeout int64 `ini:"heartbeat_timeout" json:"heartbeat_timeout"`
// UserConnTimeout specifies the maximum time to wait for a work
// connection. By default, this value is 10.
UserConnTimeout int64 `ini:"user_conn_timeout" json:"user_conn_timeout"`
// HTTPPlugins specify the server plugins support HTTP protocol.
HTTPPlugins map[string]HTTPPluginOptions `ini:"-" json:"http_plugins"`
// UDPPacketSize specifies the UDP packet size
// By default, this value is 1500
UDPPacketSize int64 `ini:"udp_packet_size" json:"udp_packet_size"`
// Enable golang pprof handlers in dashboard listener.
// Dashboard port must be set first.
PprofEnable bool `ini:"pprof_enable" json:"pprof_enable"`
// NatHoleAnalysisDataReserveHours specifies the hours to reserve nat hole analysis data.
NatHoleAnalysisDataReserveHours int64 `ini:"nat_hole_analysis_data_reserve_hours" json:"nat_hole_analysis_data_reserve_hours"`
}
// GetDefaultServerConf returns a server configuration with reasonable defaults.
// Note: Some default values here will be set to empty and will be converted to them
// new configuration through the 'Complete' function to set them as the default
// values of the new configuration.
func GetDefaultServerConf() ServerCommonConf {
return ServerCommonConf{
ServerConfig: legacyauth.GetDefaultServerConf(),
DashboardAddr: "0.0.0.0",
LogFile: "console",
LogWay: "console",
DetailedErrorsToClient: true,
TCPMux: true,
AllowPorts: make(map[int]struct{}),
HTTPPlugins: make(map[string]HTTPPluginOptions),
}
}
func UnmarshalServerConfFromIni(source any) (ServerCommonConf, error) {
f, err := ini.LoadSources(ini.LoadOptions{
Insensitive: false,
InsensitiveSections: false,
InsensitiveKeys: false,
IgnoreInlineComment: true,
AllowBooleanKeys: true,
}, source)
if err != nil {
return ServerCommonConf{}, err
}
s, err := f.GetSection("common")
if err != nil {
return ServerCommonConf{}, err
}
common := GetDefaultServerConf()
err = s.MapTo(&common)
if err != nil {
return ServerCommonConf{}, err
}
// allow_ports
allowPortStr := s.Key("allow_ports").String()
if allowPortStr != "" {
common.AllowPortsStr = allowPortStr
}
// plugin.xxx
pluginOpts := make(map[string]HTTPPluginOptions)
for _, section := range f.Sections() {
name := section.Name()
if !strings.HasPrefix(name, "plugin.") {
continue
}
opt, err := loadHTTPPluginOpt(section)
if err != nil {
return ServerCommonConf{}, err
}
pluginOpts[opt.Name] = *opt
}
common.HTTPPlugins = pluginOpts
return common, nil
}
func loadHTTPPluginOpt(section *ini.Section) (*HTTPPluginOptions, error) {
name := strings.TrimSpace(strings.TrimPrefix(section.Name(), "plugin."))
opt := &HTTPPluginOptions{}
err := section.MapTo(opt)
if err != nil {
return nil, err
}
opt.Name = name
return opt, nil
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/config/legacy/value.go | pkg/config/legacy/value.go | // Copyright 2020 The frp Authors
//
// 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 legacy
import (
"bytes"
"os"
"strings"
"text/template"
)
var glbEnvs map[string]string
func init() {
glbEnvs = make(map[string]string)
envs := os.Environ()
for _, env := range envs {
pair := strings.SplitN(env, "=", 2)
if len(pair) != 2 {
continue
}
glbEnvs[pair[0]] = pair[1]
}
}
type Values struct {
Envs map[string]string // environment vars
}
func GetValues() *Values {
return &Values{
Envs: glbEnvs,
}
}
func RenderContent(in []byte) (out []byte, err error) {
tmpl, errRet := template.New("frp").Parse(string(in))
if errRet != nil {
err = errRet
return
}
buffer := bytes.NewBufferString("")
v := GetValues()
err = tmpl.Execute(buffer, v)
if err != nil {
return
}
out = buffer.Bytes()
return
}
func GetRenderedConfFromFile(path string) (out []byte, err error) {
var b []byte
b, err = os.ReadFile(path)
if err != nil {
return
}
out, err = RenderContent(b)
return
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/config/legacy/parse.go | pkg/config/legacy/parse.go | // Copyright 2021 The frp Authors
//
// 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 legacy
import (
"bytes"
"fmt"
"os"
"path/filepath"
)
func ParseClientConfig(filePath string) (
cfg ClientCommonConf,
proxyCfgs map[string]ProxyConf,
visitorCfgs map[string]VisitorConf,
err error,
) {
var content []byte
content, err = GetRenderedConfFromFile(filePath)
if err != nil {
return
}
configBuffer := bytes.NewBuffer(nil)
configBuffer.Write(content)
// Parse common section.
cfg, err = UnmarshalClientConfFromIni(content)
if err != nil {
return
}
if err = cfg.Validate(); err != nil {
err = fmt.Errorf("parse config error: %v", err)
return
}
// Aggregate proxy configs from include files.
var buf []byte
buf, err = getIncludeContents(cfg.IncludeConfigFiles)
if err != nil {
err = fmt.Errorf("getIncludeContents error: %v", err)
return
}
configBuffer.WriteString("\n")
configBuffer.Write(buf)
// Parse all proxy and visitor configs.
proxyCfgs, visitorCfgs, err = LoadAllProxyConfsFromIni(cfg.User, configBuffer.Bytes(), cfg.Start)
if err != nil {
return
}
return
}
// getIncludeContents renders all configs from paths.
// files format can be a single file path or directory or regex path.
func getIncludeContents(paths []string) ([]byte, error) {
out := bytes.NewBuffer(nil)
for _, path := range paths {
absDir, err := filepath.Abs(filepath.Dir(path))
if err != nil {
return nil, err
}
if _, err := os.Stat(absDir); os.IsNotExist(err) {
return nil, err
}
files, err := os.ReadDir(absDir)
if err != nil {
return nil, err
}
for _, fi := range files {
if fi.IsDir() {
continue
}
absFile := filepath.Join(absDir, fi.Name())
if matched, _ := filepath.Match(filepath.Join(absDir, filepath.Base(path)), absFile); matched {
tmpContent, err := GetRenderedConfFromFile(absFile)
if err != nil {
return nil, fmt.Errorf("render extra config %s error: %v", absFile, err)
}
out.Write(tmpContent)
out.WriteString("\n")
}
}
}
return out.Bytes(), nil
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/config/legacy/visitor.go | pkg/config/legacy/visitor.go | // Copyright 2023 The frp Authors
//
// 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 legacy
import (
"fmt"
"reflect"
"gopkg.in/ini.v1"
)
type VisitorType string
const (
VisitorTypeSTCP VisitorType = "stcp"
VisitorTypeXTCP VisitorType = "xtcp"
VisitorTypeSUDP VisitorType = "sudp"
)
// Visitor
var (
visitorConfTypeMap = map[VisitorType]reflect.Type{
VisitorTypeSTCP: reflect.TypeOf(STCPVisitorConf{}),
VisitorTypeXTCP: reflect.TypeOf(XTCPVisitorConf{}),
VisitorTypeSUDP: reflect.TypeOf(SUDPVisitorConf{}),
}
)
type VisitorConf interface {
// GetBaseConfig returns the base config of visitor.
GetBaseConfig() *BaseVisitorConf
// UnmarshalFromIni unmarshals config from ini.
UnmarshalFromIni(prefix string, name string, section *ini.Section) error
}
// DefaultVisitorConf creates a empty VisitorConf object by visitorType.
// If visitorType doesn't exist, return nil.
func DefaultVisitorConf(visitorType VisitorType) VisitorConf {
v, ok := visitorConfTypeMap[visitorType]
if !ok {
return nil
}
return reflect.New(v).Interface().(VisitorConf)
}
type BaseVisitorConf struct {
ProxyName string `ini:"name" json:"name"`
ProxyType string `ini:"type" json:"type"`
UseEncryption bool `ini:"use_encryption" json:"use_encryption"`
UseCompression bool `ini:"use_compression" json:"use_compression"`
Role string `ini:"role" json:"role"`
Sk string `ini:"sk" json:"sk"`
// if the server user is not set, it defaults to the current user
ServerUser string `ini:"server_user" json:"server_user"`
ServerName string `ini:"server_name" json:"server_name"`
BindAddr string `ini:"bind_addr" json:"bind_addr"`
// BindPort is the port that visitor listens on.
// It can be less than 0, it means don't bind to the port and only receive connections redirected from
// other visitors. (This is not supported for SUDP now)
BindPort int `ini:"bind_port" json:"bind_port"`
}
// Base
func (cfg *BaseVisitorConf) GetBaseConfig() *BaseVisitorConf {
return cfg
}
func (cfg *BaseVisitorConf) unmarshalFromIni(_ string, name string, _ *ini.Section) error {
// Custom decoration after basic unmarshal:
cfg.ProxyName = name
// bind_addr
if cfg.BindAddr == "" {
cfg.BindAddr = "127.0.0.1"
}
return nil
}
func preVisitorUnmarshalFromIni(cfg VisitorConf, prefix string, name string, section *ini.Section) error {
err := section.MapTo(cfg)
if err != nil {
return err
}
err = cfg.GetBaseConfig().unmarshalFromIni(prefix, name, section)
if err != nil {
return err
}
return nil
}
type SUDPVisitorConf struct {
BaseVisitorConf `ini:",extends"`
}
func (cfg *SUDPVisitorConf) UnmarshalFromIni(prefix string, name string, section *ini.Section) (err error) {
err = preVisitorUnmarshalFromIni(cfg, prefix, name, section)
if err != nil {
return
}
// Add custom logic unmarshal, if exists
return
}
type STCPVisitorConf struct {
BaseVisitorConf `ini:",extends"`
}
func (cfg *STCPVisitorConf) UnmarshalFromIni(prefix string, name string, section *ini.Section) (err error) {
err = preVisitorUnmarshalFromIni(cfg, prefix, name, section)
if err != nil {
return
}
// Add custom logic unmarshal, if exists
return
}
type XTCPVisitorConf struct {
BaseVisitorConf `ini:",extends"`
Protocol string `ini:"protocol" json:"protocol,omitempty"`
KeepTunnelOpen bool `ini:"keep_tunnel_open" json:"keep_tunnel_open,omitempty"`
MaxRetriesAnHour int `ini:"max_retries_an_hour" json:"max_retries_an_hour,omitempty"`
MinRetryInterval int `ini:"min_retry_interval" json:"min_retry_interval,omitempty"`
FallbackTo string `ini:"fallback_to" json:"fallback_to,omitempty"`
FallbackTimeoutMs int `ini:"fallback_timeout_ms" json:"fallback_timeout_ms,omitempty"`
}
func (cfg *XTCPVisitorConf) UnmarshalFromIni(prefix string, name string, section *ini.Section) (err error) {
err = preVisitorUnmarshalFromIni(cfg, prefix, name, section)
if err != nil {
return
}
// Add custom logic unmarshal, if exists
if cfg.Protocol == "" {
cfg.Protocol = "quic"
}
if cfg.MaxRetriesAnHour <= 0 {
cfg.MaxRetriesAnHour = 8
}
if cfg.MinRetryInterval <= 0 {
cfg.MinRetryInterval = 90
}
if cfg.FallbackTimeoutMs <= 0 {
cfg.FallbackTimeoutMs = 1000
}
return
}
// Visitor loaded from ini
func NewVisitorConfFromIni(prefix string, name string, section *ini.Section) (VisitorConf, error) {
// section.Key: if key not exists, section will set it with default value.
visitorType := VisitorType(section.Key("type").String())
if visitorType == "" {
return nil, fmt.Errorf("type shouldn't be empty")
}
conf := DefaultVisitorConf(visitorType)
if conf == nil {
return nil, fmt.Errorf("type [%s] error", visitorType)
}
if err := conf.UnmarshalFromIni(prefix, name, section); err != nil {
return nil, fmt.Errorf("type [%s] error", visitorType)
}
return conf, nil
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/transport/message.go | pkg/transport/message.go | // Copyright 2023 The frp Authors
//
// 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 transport
import (
"context"
"reflect"
"sync"
"github.com/fatedier/golib/errors"
"github.com/fatedier/frp/pkg/msg"
)
type MessageTransporter interface {
Send(msg.Message) error
// Recv(ctx context.Context, laneKey string, msgType string) (Message, error)
// Do will first send msg, then recv msg with the same laneKey and specified msgType.
Do(ctx context.Context, req msg.Message, laneKey, recvMsgType string) (msg.Message, error)
// Dispatch will dispatch message to related channel registered in Do function by its message type and laneKey.
Dispatch(m msg.Message, laneKey string) bool
// Same with Dispatch but with specified message type.
DispatchWithType(m msg.Message, msgType, laneKey string) bool
}
type MessageSender interface {
Send(msg.Message) error
}
func NewMessageTransporter(sender MessageSender) MessageTransporter {
return &transporterImpl{
sender: sender,
registry: make(map[string]map[string]chan msg.Message),
}
}
type transporterImpl struct {
sender MessageSender
// First key is message type and second key is lane key.
// Dispatch will dispatch message to related channel by its message type
// and lane key.
registry map[string]map[string]chan msg.Message
mu sync.RWMutex
}
func (impl *transporterImpl) Send(m msg.Message) error {
return impl.sender.Send(m)
}
func (impl *transporterImpl) Do(ctx context.Context, req msg.Message, laneKey, recvMsgType string) (msg.Message, error) {
ch := make(chan msg.Message, 1)
defer close(ch)
unregisterFn := impl.registerMsgChan(ch, laneKey, recvMsgType)
defer unregisterFn()
if err := impl.Send(req); err != nil {
return nil, err
}
select {
case <-ctx.Done():
return nil, ctx.Err()
case resp := <-ch:
return resp, nil
}
}
func (impl *transporterImpl) DispatchWithType(m msg.Message, msgType, laneKey string) bool {
var ch chan msg.Message
impl.mu.RLock()
byLaneKey, ok := impl.registry[msgType]
if ok {
ch = byLaneKey[laneKey]
}
impl.mu.RUnlock()
if ch == nil {
return false
}
if err := errors.PanicToError(func() {
ch <- m
}); err != nil {
return false
}
return true
}
func (impl *transporterImpl) Dispatch(m msg.Message, laneKey string) bool {
msgType := reflect.TypeOf(m).Elem().Name()
return impl.DispatchWithType(m, msgType, laneKey)
}
func (impl *transporterImpl) registerMsgChan(recvCh chan msg.Message, laneKey string, msgType string) (unregister func()) {
impl.mu.Lock()
byLaneKey, ok := impl.registry[msgType]
if !ok {
byLaneKey = make(map[string]chan msg.Message)
impl.registry[msgType] = byLaneKey
}
byLaneKey[laneKey] = recvCh
impl.mu.Unlock()
unregister = func() {
impl.mu.Lock()
delete(byLaneKey, laneKey)
impl.mu.Unlock()
}
return
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/transport/tls.go | pkg/transport/tls.go | // Copyright 2023 The frp Authors
//
// 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 transport
import (
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"encoding/pem"
"math/big"
"os"
"time"
)
func newCustomTLSKeyPair(certfile, keyfile string) (*tls.Certificate, error) {
tlsCert, err := tls.LoadX509KeyPair(certfile, keyfile)
if err != nil {
return nil, err
}
return &tlsCert, nil
}
func newRandomTLSKeyPair() (*tls.Certificate, error) {
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, err
}
// Generate a random positive serial number with 128 bits of entropy.
// RFC 5280 requires serial numbers to be positive integers (not zero).
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return nil, err
}
// Ensure serial number is positive (not zero)
if serialNumber.Sign() == 0 {
serialNumber = big.NewInt(1)
}
template := x509.Certificate{
SerialNumber: serialNumber,
NotBefore: time.Now().Add(-1 * time.Hour),
NotAfter: time.Now().Add(365 * 24 * time.Hour * 10),
}
certDER, err := x509.CreateCertificate(
rand.Reader,
&template,
&template,
&key.PublicKey,
key)
if err != nil {
return nil, err
}
keyPEM := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)})
certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certDER})
tlsCert, err := tls.X509KeyPair(certPEM, keyPEM)
if err != nil {
return nil, err
}
return &tlsCert, nil
}
// Only support one ca file to add
func newCertPool(caPath string) (*x509.CertPool, error) {
pool := x509.NewCertPool()
caCrt, err := os.ReadFile(caPath)
if err != nil {
return nil, err
}
pool.AppendCertsFromPEM(caCrt)
return pool, nil
}
func NewServerTLSConfig(certPath, keyPath, caPath string) (*tls.Config, error) {
base := &tls.Config{}
if certPath == "" || keyPath == "" {
// server will generate tls conf by itself
cert, err := newRandomTLSKeyPair()
if err != nil {
return nil, err
}
base.Certificates = []tls.Certificate{*cert}
} else {
cert, err := newCustomTLSKeyPair(certPath, keyPath)
if err != nil {
return nil, err
}
base.Certificates = []tls.Certificate{*cert}
}
if caPath != "" {
pool, err := newCertPool(caPath)
if err != nil {
return nil, err
}
base.ClientAuth = tls.RequireAndVerifyClientCert
base.ClientCAs = pool
}
return base, nil
}
func NewClientTLSConfig(certPath, keyPath, caPath, serverName string) (*tls.Config, error) {
base := &tls.Config{}
if certPath != "" && keyPath != "" {
cert, err := newCustomTLSKeyPair(certPath, keyPath)
if err != nil {
return nil, err
}
base.Certificates = []tls.Certificate{*cert}
}
base.ServerName = serverName
if caPath != "" {
pool, err := newCertPool(caPath)
if err != nil {
return nil, err
}
base.RootCAs = pool
base.InsecureSkipVerify = false
} else {
base.InsecureSkipVerify = true
}
return base, nil
}
func NewRandomPrivateKey() ([]byte, error) {
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, err
}
keyPEM := pem.EncodeToMemory(&pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(key),
})
return keyPEM, nil
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/nathole/utils.go | pkg/nathole/utils.go | // Copyright 2023 The frp Authors
//
// 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 nathole
import (
"bytes"
"fmt"
"net"
"strconv"
"github.com/fatedier/golib/crypto"
"github.com/pion/stun/v2"
"github.com/fatedier/frp/pkg/msg"
)
func EncodeMessage(m msg.Message, key []byte) ([]byte, error) {
buffer := bytes.NewBuffer(nil)
if err := msg.WriteMsg(buffer, m); err != nil {
return nil, err
}
buf, err := crypto.Encode(buffer.Bytes(), key)
if err != nil {
return nil, err
}
return buf, nil
}
func DecodeMessageInto(data, key []byte, m msg.Message) error {
buf, err := crypto.Decode(data, key)
if err != nil {
return err
}
return msg.ReadMsgInto(bytes.NewReader(buf), m)
}
type ChangedAddress struct {
IP net.IP
Port int
}
func (s *ChangedAddress) GetFrom(m *stun.Message) error {
a := (*stun.MappedAddress)(s)
return a.GetFromAs(m, stun.AttrChangedAddress)
}
func (s *ChangedAddress) String() string {
return net.JoinHostPort(s.IP.String(), strconv.Itoa(s.Port))
}
func ListAllLocalIPs() ([]net.IP, error) {
addrs, err := net.InterfaceAddrs()
if err != nil {
return nil, err
}
ips := make([]net.IP, 0, len(addrs))
for _, addr := range addrs {
ip, _, err := net.ParseCIDR(addr.String())
if err != nil {
continue
}
ips = append(ips, ip)
}
return ips, nil
}
func ListLocalIPsForNatHole(maxItems int) ([]string, error) {
if maxItems <= 0 {
return nil, fmt.Errorf("maxItems must be greater than 0")
}
ips, err := ListAllLocalIPs()
if err != nil {
return nil, err
}
filtered := make([]string, 0, maxItems)
for _, ip := range ips {
if len(filtered) >= maxItems {
break
}
// ignore ipv6 address
if ip.To4() == nil {
continue
}
// ignore localhost IP
if ip.IsLoopback() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() {
continue
}
filtered = append(filtered, ip.String())
}
return filtered, nil
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/nathole/classify.go | pkg/nathole/classify.go | // Copyright 2023 The frp Authors
//
// 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 nathole
import (
"fmt"
"net"
"slices"
"strconv"
)
const (
EasyNAT = "EasyNAT"
HardNAT = "HardNAT"
BehaviorNoChange = "BehaviorNoChange"
BehaviorIPChanged = "BehaviorIPChanged"
BehaviorPortChanged = "BehaviorPortChanged"
BehaviorBothChanged = "BehaviorBothChanged"
)
type NatFeature struct {
NatType string
Behavior string
PortsDifference int
RegularPortsChange bool
PublicNetwork bool
}
func ClassifyNATFeature(addresses []string, localIPs []string) (*NatFeature, error) {
if len(addresses) <= 1 {
return nil, fmt.Errorf("not enough addresses")
}
natFeature := &NatFeature{}
ipChanged := false
portChanged := false
var baseIP, basePort string
var portMax, portMin int
for _, addr := range addresses {
ip, port, err := net.SplitHostPort(addr)
if err != nil {
return nil, err
}
portNum, err := strconv.Atoi(port)
if err != nil {
return nil, err
}
if slices.Contains(localIPs, ip) {
natFeature.PublicNetwork = true
}
if baseIP == "" {
baseIP = ip
basePort = port
portMax = portNum
portMin = portNum
continue
}
if portNum > portMax {
portMax = portNum
}
if portNum < portMin {
portMin = portNum
}
if baseIP != ip {
ipChanged = true
}
if basePort != port {
portChanged = true
}
}
switch {
case ipChanged && portChanged:
natFeature.NatType = HardNAT
natFeature.Behavior = BehaviorBothChanged
case ipChanged:
natFeature.NatType = HardNAT
natFeature.Behavior = BehaviorIPChanged
case portChanged:
natFeature.NatType = HardNAT
natFeature.Behavior = BehaviorPortChanged
default:
natFeature.NatType = EasyNAT
natFeature.Behavior = BehaviorNoChange
}
if natFeature.Behavior == BehaviorPortChanged {
natFeature.PortsDifference = portMax - portMin
if natFeature.PortsDifference <= 5 && natFeature.PortsDifference >= 1 {
natFeature.RegularPortsChange = true
}
}
return natFeature, nil
}
func ClassifyFeatureCount(features []*NatFeature) (int, int, int) {
easyCount := 0
hardCount := 0
// for HardNAT
portsChangedRegularCount := 0
for _, feature := range features {
if feature.NatType == EasyNAT {
easyCount++
continue
}
hardCount++
if feature.RegularPortsChange {
portsChangedRegularCount++
}
}
return easyCount, hardCount, portsChangedRegularCount
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/nathole/controller.go | pkg/nathole/controller.go | // Copyright 2023 The frp Authors
//
// 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 nathole
import (
"context"
"crypto/md5"
"encoding/hex"
"fmt"
"net"
"slices"
"strconv"
"sync"
"time"
"github.com/fatedier/golib/errors"
"github.com/samber/lo"
"golang.org/x/sync/errgroup"
"github.com/fatedier/frp/pkg/msg"
"github.com/fatedier/frp/pkg/transport"
"github.com/fatedier/frp/pkg/util/log"
"github.com/fatedier/frp/pkg/util/util"
)
// NatHoleTimeout seconds.
var NatHoleTimeout int64 = 10
func NewTransactionID() string {
id, _ := util.RandID()
return fmt.Sprintf("%d%s", time.Now().Unix(), id)
}
type ClientCfg struct {
name string
sk string
allowUsers []string
sidCh chan string
}
type Session struct {
sid string
analysisKey string
recommandMode int
recommandIndex int
visitorMsg *msg.NatHoleVisitor
visitorTransporter transport.MessageTransporter
vResp *msg.NatHoleResp
vNatFeature *NatFeature
vBehavior RecommandBehavior
clientMsg *msg.NatHoleClient
clientTransporter transport.MessageTransporter
cResp *msg.NatHoleResp
cNatFeature *NatFeature
cBehavior RecommandBehavior
notifyCh chan struct{}
}
func (s *Session) genAnalysisKey() {
hash := md5.New()
vIPs := slices.Compact(parseIPs(s.visitorMsg.MappedAddrs))
if len(vIPs) > 0 {
hash.Write([]byte(vIPs[0]))
}
hash.Write([]byte(s.vNatFeature.NatType))
hash.Write([]byte(s.vNatFeature.Behavior))
hash.Write([]byte(strconv.FormatBool(s.vNatFeature.RegularPortsChange)))
cIPs := slices.Compact(parseIPs(s.clientMsg.MappedAddrs))
if len(cIPs) > 0 {
hash.Write([]byte(cIPs[0]))
}
hash.Write([]byte(s.cNatFeature.NatType))
hash.Write([]byte(s.cNatFeature.Behavior))
hash.Write([]byte(strconv.FormatBool(s.cNatFeature.RegularPortsChange)))
s.analysisKey = hex.EncodeToString(hash.Sum(nil))
}
type Controller struct {
clientCfgs map[string]*ClientCfg
sessions map[string]*Session
analyzer *Analyzer
mu sync.RWMutex
}
func NewController(analysisDataReserveDuration time.Duration) (*Controller, error) {
return &Controller{
clientCfgs: make(map[string]*ClientCfg),
sessions: make(map[string]*Session),
analyzer: NewAnalyzer(analysisDataReserveDuration),
}, nil
}
func (c *Controller) CleanWorker(ctx context.Context) {
ticker := time.NewTicker(time.Hour)
defer ticker.Stop()
for {
select {
case <-ticker.C:
start := time.Now()
count, total := c.analyzer.Clean()
log.Tracef("clean %d/%d nathole analysis data, cost %v", count, total, time.Since(start))
case <-ctx.Done():
return
}
}
}
func (c *Controller) ListenClient(name string, sk string, allowUsers []string) (chan string, error) {
cfg := &ClientCfg{
name: name,
sk: sk,
allowUsers: allowUsers,
sidCh: make(chan string),
}
c.mu.Lock()
defer c.mu.Unlock()
if _, ok := c.clientCfgs[name]; ok {
return nil, fmt.Errorf("proxy [%s] is repeated", name)
}
c.clientCfgs[name] = cfg
return cfg.sidCh, nil
}
func (c *Controller) CloseClient(name string) {
c.mu.Lock()
defer c.mu.Unlock()
delete(c.clientCfgs, name)
}
func (c *Controller) GenSid() string {
t := time.Now().Unix()
id, _ := util.RandID()
return fmt.Sprintf("%d%s", t, id)
}
func (c *Controller) HandleVisitor(m *msg.NatHoleVisitor, transporter transport.MessageTransporter, visitorUser string) {
if m.PreCheck {
cfg, ok := c.clientCfgs[m.ProxyName]
if !ok {
_ = transporter.Send(c.GenNatHoleResponse(m.TransactionID, nil, fmt.Sprintf("xtcp server for [%s] doesn't exist", m.ProxyName)))
return
}
if !slices.Contains(cfg.allowUsers, visitorUser) && !slices.Contains(cfg.allowUsers, "*") {
_ = transporter.Send(c.GenNatHoleResponse(m.TransactionID, nil, fmt.Sprintf("xtcp visitor user [%s] not allowed for [%s]", visitorUser, m.ProxyName)))
return
}
_ = transporter.Send(c.GenNatHoleResponse(m.TransactionID, nil, ""))
return
}
sid := c.GenSid()
session := &Session{
sid: sid,
visitorMsg: m,
visitorTransporter: transporter,
notifyCh: make(chan struct{}, 1),
}
var (
clientCfg *ClientCfg
ok bool
)
err := func() error {
c.mu.Lock()
defer c.mu.Unlock()
clientCfg, ok = c.clientCfgs[m.ProxyName]
if !ok {
return fmt.Errorf("xtcp server for [%s] doesn't exist", m.ProxyName)
}
if !util.ConstantTimeEqString(m.SignKey, util.GetAuthKey(clientCfg.sk, m.Timestamp)) {
return fmt.Errorf("xtcp connection of [%s] auth failed", m.ProxyName)
}
c.sessions[sid] = session
return nil
}()
if err != nil {
log.Warnf("handle visitorMsg error: %v", err)
_ = transporter.Send(c.GenNatHoleResponse(m.TransactionID, nil, err.Error()))
return
}
log.Tracef("handle visitor message, sid [%s], server name: %s", sid, m.ProxyName)
defer func() {
c.mu.Lock()
defer c.mu.Unlock()
delete(c.sessions, sid)
}()
if err := errors.PanicToError(func() {
clientCfg.sidCh <- sid
}); err != nil {
return
}
// wait for NatHoleClient message
select {
case <-session.notifyCh:
case <-time.After(time.Duration(NatHoleTimeout) * time.Second):
log.Debugf("wait for NatHoleClient message timeout, sid [%s]", sid)
return
}
// Make hole-punching decisions based on the NAT information of the client and visitor.
vResp, cResp, err := c.analysis(session)
if err != nil {
log.Debugf("sid [%s] analysis error: %v", err)
vResp = c.GenNatHoleResponse(session.visitorMsg.TransactionID, nil, err.Error())
cResp = c.GenNatHoleResponse(session.clientMsg.TransactionID, nil, err.Error())
}
session.cResp = cResp
session.vResp = vResp
// send response to visitor and client
var g errgroup.Group
g.Go(func() error {
// if it's sender, wait for a while to make sure the client has send the detect messages
if vResp.DetectBehavior.Role == "sender" {
time.Sleep(1 * time.Second)
}
_ = session.visitorTransporter.Send(vResp)
return nil
})
g.Go(func() error {
// if it's sender, wait for a while to make sure the client has send the detect messages
if cResp.DetectBehavior.Role == "sender" {
time.Sleep(1 * time.Second)
}
_ = session.clientTransporter.Send(cResp)
return nil
})
_ = g.Wait()
time.Sleep(time.Duration(cResp.DetectBehavior.ReadTimeoutMs+30000) * time.Millisecond)
}
func (c *Controller) HandleClient(m *msg.NatHoleClient, transporter transport.MessageTransporter) {
c.mu.RLock()
session, ok := c.sessions[m.Sid]
c.mu.RUnlock()
if !ok {
return
}
log.Tracef("handle client message, sid [%s], server name: %s", session.sid, m.ProxyName)
session.clientMsg = m
session.clientTransporter = transporter
select {
case session.notifyCh <- struct{}{}:
default:
}
}
func (c *Controller) HandleReport(m *msg.NatHoleReport) {
c.mu.RLock()
session, ok := c.sessions[m.Sid]
c.mu.RUnlock()
if !ok {
log.Tracef("sid [%s] report make hole success: %v, but session not found", m.Sid, m.Success)
return
}
if m.Success {
c.analyzer.ReportSuccess(session.analysisKey, session.recommandMode, session.recommandIndex)
}
log.Infof("sid [%s] report make hole success: %v, mode %v, index %v",
m.Sid, m.Success, session.recommandMode, session.recommandIndex)
}
func (c *Controller) GenNatHoleResponse(transactionID string, session *Session, errInfo string) *msg.NatHoleResp {
var sid string
if session != nil {
sid = session.sid
}
return &msg.NatHoleResp{
TransactionID: transactionID,
Sid: sid,
Error: errInfo,
}
}
// analysis analyzes the NAT type and behavior of the visitor and client, then makes hole-punching decisions.
// return the response to the visitor and client.
func (c *Controller) analysis(session *Session) (*msg.NatHoleResp, *msg.NatHoleResp, error) {
cm := session.clientMsg
vm := session.visitorMsg
cNatFeature, err := ClassifyNATFeature(cm.MappedAddrs, parseIPs(cm.AssistedAddrs))
if err != nil {
return nil, nil, fmt.Errorf("classify client nat feature error: %v", err)
}
vNatFeature, err := ClassifyNATFeature(vm.MappedAddrs, parseIPs(vm.AssistedAddrs))
if err != nil {
return nil, nil, fmt.Errorf("classify visitor nat feature error: %v", err)
}
session.cNatFeature = cNatFeature
session.vNatFeature = vNatFeature
session.genAnalysisKey()
mode, index, cBehavior, vBehavior := c.analyzer.GetRecommandBehaviors(session.analysisKey, cNatFeature, vNatFeature)
session.recommandMode = mode
session.recommandIndex = index
session.cBehavior = cBehavior
session.vBehavior = vBehavior
timeoutMs := max(cBehavior.SendDelayMs, vBehavior.SendDelayMs) + 5000
if cBehavior.ListenRandomPorts > 0 || vBehavior.ListenRandomPorts > 0 {
timeoutMs += 30000
}
protocol := vm.Protocol
vResp := &msg.NatHoleResp{
TransactionID: vm.TransactionID,
Sid: session.sid,
Protocol: protocol,
CandidateAddrs: slices.Compact(cm.MappedAddrs),
AssistedAddrs: slices.Compact(cm.AssistedAddrs),
DetectBehavior: msg.NatHoleDetectBehavior{
Mode: mode,
Role: vBehavior.Role,
TTL: vBehavior.TTL,
SendDelayMs: vBehavior.SendDelayMs,
ReadTimeoutMs: timeoutMs - vBehavior.SendDelayMs,
SendRandomPorts: vBehavior.PortsRandomNumber,
ListenRandomPorts: vBehavior.ListenRandomPorts,
CandidatePorts: getRangePorts(cm.MappedAddrs, cNatFeature.PortsDifference, vBehavior.PortsRangeNumber),
},
}
cResp := &msg.NatHoleResp{
TransactionID: cm.TransactionID,
Sid: session.sid,
Protocol: protocol,
CandidateAddrs: slices.Compact(vm.MappedAddrs),
AssistedAddrs: slices.Compact(vm.AssistedAddrs),
DetectBehavior: msg.NatHoleDetectBehavior{
Mode: mode,
Role: cBehavior.Role,
TTL: cBehavior.TTL,
SendDelayMs: cBehavior.SendDelayMs,
ReadTimeoutMs: timeoutMs - cBehavior.SendDelayMs,
SendRandomPorts: cBehavior.PortsRandomNumber,
ListenRandomPorts: cBehavior.ListenRandomPorts,
CandidatePorts: getRangePorts(vm.MappedAddrs, vNatFeature.PortsDifference, cBehavior.PortsRangeNumber),
},
}
log.Debugf("sid [%s] visitor nat: %+v, candidateAddrs: %v; client nat: %+v, candidateAddrs: %v, protocol: %s",
session.sid, *vNatFeature, vm.MappedAddrs, *cNatFeature, cm.MappedAddrs, protocol)
log.Debugf("sid [%s] visitor detect behavior: %+v", session.sid, vResp.DetectBehavior)
log.Debugf("sid [%s] client detect behavior: %+v", session.sid, cResp.DetectBehavior)
return vResp, cResp, nil
}
func getRangePorts(addrs []string, difference, maxNumber int) []msg.PortsRange {
if maxNumber <= 0 {
return nil
}
addr, isLast := lo.Last(addrs)
if !isLast {
return nil
}
var ports []msg.PortsRange
_, portStr, err := net.SplitHostPort(addr)
if err != nil {
return nil
}
port, err := strconv.Atoi(portStr)
if err != nil {
return nil
}
ports = append(ports, msg.PortsRange{
From: max(port-difference-5, port-maxNumber, 1),
To: min(port+difference+5, port+maxNumber, 65535),
})
return ports
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/nathole/nathole.go | pkg/nathole/nathole.go | // Copyright 2023 The frp Authors
//
// 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 nathole
import (
"context"
"fmt"
"math/rand/v2"
"net"
"slices"
"strconv"
"strings"
"time"
"github.com/fatedier/golib/pool"
"golang.org/x/net/ipv4"
"k8s.io/apimachinery/pkg/util/sets"
"github.com/fatedier/frp/pkg/msg"
"github.com/fatedier/frp/pkg/transport"
"github.com/fatedier/frp/pkg/util/xlog"
)
var (
// mode 0: simple detect mode, usually for both EasyNAT or HardNAT & EasyNAT(Public Network)
// a. receiver sends detect message with low TTL
// b. sender sends normal detect message to receiver
// c. receiver receives detect message and sends back a message to sender
//
// mode 1: For HardNAT & EasyNAT, send detect messages to multiple guessed ports.
// Usually applicable to scenarios where port changes are regular.
// Most of the steps are the same as mode 0, but EasyNAT is fixed as the receiver and will send detect messages
// with low TTL to multiple guessed ports of the sender.
//
// mode 2: For HardNAT & EasyNAT, ports changes are not regular.
// a. HardNAT machine will listen on multiple ports and send detect messages with low TTL to EasyNAT machine
// b. EasyNAT machine will send detect messages to random ports of HardNAT machine.
//
// mode 3: For HardNAT & HardNAT, both changes in the ports are regular.
// Most of the steps are the same as mode 1, but the sender also needs to send detect messages to multiple guessed
// ports of the receiver.
//
// mode 4: For HardNAT & HardNAT, one of the changes in the ports is regular.
// Regular port changes are usually on the sender side.
// a. Receiver listens on multiple ports and sends detect messages with low TTL to the sender's guessed range ports.
// b. Sender sends detect messages to random ports of the receiver.
SupportedModes = []int{DetectMode0, DetectMode1, DetectMode2, DetectMode3, DetectMode4}
SupportedRoles = []string{DetectRoleSender, DetectRoleReceiver}
DetectMode0 = 0
DetectMode1 = 1
DetectMode2 = 2
DetectMode3 = 3
DetectMode4 = 4
DetectRoleSender = "sender"
DetectRoleReceiver = "receiver"
)
// PrepareOptions defines options for NAT traversal preparation
type PrepareOptions struct {
// DisableAssistedAddrs disables the use of local network interfaces
// for assisted connections during NAT traversal
DisableAssistedAddrs bool
}
type PrepareResult struct {
Addrs []string
AssistedAddrs []string
ListenConn *net.UDPConn
NatType string
Behavior string
}
// PreCheck is used to check if the proxy is ready for penetration.
// Call this function before calling Prepare to avoid unnecessary preparation work.
func PreCheck(
ctx context.Context, transporter transport.MessageTransporter,
proxyName string, timeout time.Duration,
) error {
timeoutCtx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
var natHoleRespMsg *msg.NatHoleResp
transactionID := NewTransactionID()
m, err := transporter.Do(timeoutCtx, &msg.NatHoleVisitor{
TransactionID: transactionID,
ProxyName: proxyName,
PreCheck: true,
}, transactionID, msg.TypeNameNatHoleResp)
if err != nil {
return fmt.Errorf("get natHoleRespMsg error: %v", err)
}
mm, ok := m.(*msg.NatHoleResp)
if !ok {
return fmt.Errorf("get natHoleRespMsg error: invalid message type")
}
natHoleRespMsg = mm
if natHoleRespMsg.Error != "" {
return fmt.Errorf("%s", natHoleRespMsg.Error)
}
return nil
}
// Prepare is used to do some preparation work before penetration.
func Prepare(stunServers []string, opts PrepareOptions) (*PrepareResult, error) {
// discover for Nat type
addrs, localAddr, err := Discover(stunServers, "")
if err != nil {
return nil, fmt.Errorf("discover error: %v", err)
}
if len(addrs) < 2 {
return nil, fmt.Errorf("discover error: not enough addresses")
}
localIPs, _ := ListLocalIPsForNatHole(10)
natFeature, err := ClassifyNATFeature(addrs, localIPs)
if err != nil {
return nil, fmt.Errorf("classify nat feature error: %v", err)
}
laddr, err := net.ResolveUDPAddr("udp4", localAddr.String())
if err != nil {
return nil, fmt.Errorf("resolve local udp addr error: %v", err)
}
listenConn, err := net.ListenUDP("udp4", laddr)
if err != nil {
return nil, fmt.Errorf("listen local udp addr error: %v", err)
}
// Apply NAT traversal options
var assistedAddrs []string
if !opts.DisableAssistedAddrs {
assistedAddrs = make([]string, 0, len(localIPs))
for _, ip := range localIPs {
assistedAddrs = append(assistedAddrs, net.JoinHostPort(ip, strconv.Itoa(laddr.Port)))
}
}
return &PrepareResult{
Addrs: addrs,
AssistedAddrs: assistedAddrs,
ListenConn: listenConn,
NatType: natFeature.NatType,
Behavior: natFeature.Behavior,
}, nil
}
// ExchangeInfo is used to exchange information between client and visitor.
// 1. Send input message to server by msgTransporter.
// 2. Server will gather information from client and visitor and analyze it. Then send back a NatHoleResp message to them to tell them how to do next.
// 3. Receive NatHoleResp message from server.
func ExchangeInfo(
ctx context.Context, transporter transport.MessageTransporter,
laneKey string, m msg.Message, timeout time.Duration,
) (*msg.NatHoleResp, error) {
timeoutCtx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
var natHoleRespMsg *msg.NatHoleResp
m, err := transporter.Do(timeoutCtx, m, laneKey, msg.TypeNameNatHoleResp)
if err != nil {
return nil, fmt.Errorf("get natHoleRespMsg error: %v", err)
}
mm, ok := m.(*msg.NatHoleResp)
if !ok {
return nil, fmt.Errorf("get natHoleRespMsg error: invalid message type")
}
natHoleRespMsg = mm
if natHoleRespMsg.Error != "" {
return nil, fmt.Errorf("natHoleRespMsg get error info: %s", natHoleRespMsg.Error)
}
if len(natHoleRespMsg.CandidateAddrs) == 0 {
return nil, fmt.Errorf("natHoleRespMsg get empty candidate addresses")
}
return natHoleRespMsg, nil
}
// MakeHole is used to make a NAT hole between client and visitor.
func MakeHole(ctx context.Context, listenConn *net.UDPConn, m *msg.NatHoleResp, key []byte) (*net.UDPConn, *net.UDPAddr, error) {
xl := xlog.FromContextSafe(ctx)
transactionID := NewTransactionID()
sendToRangePortsFunc := func(conn *net.UDPConn, addr string) error {
return sendSidMessage(ctx, conn, m.Sid, transactionID, addr, key, m.DetectBehavior.TTL)
}
listenConns := []*net.UDPConn{listenConn}
var detectAddrs []string
if m.DetectBehavior.Role == DetectRoleSender {
// sender
if m.DetectBehavior.SendDelayMs > 0 {
time.Sleep(time.Duration(m.DetectBehavior.SendDelayMs) * time.Millisecond)
}
detectAddrs = m.AssistedAddrs
detectAddrs = append(detectAddrs, m.CandidateAddrs...)
} else {
// receiver
if len(m.DetectBehavior.CandidatePorts) == 0 {
detectAddrs = m.CandidateAddrs
}
if m.DetectBehavior.ListenRandomPorts > 0 {
for i := 0; i < m.DetectBehavior.ListenRandomPorts; i++ {
tmpConn, err := net.ListenUDP("udp4", nil)
if err != nil {
xl.Warnf("listen random udp addr error: %v", err)
continue
}
listenConns = append(listenConns, tmpConn)
}
}
}
detectAddrs = slices.Compact(detectAddrs)
for _, detectAddr := range detectAddrs {
for _, conn := range listenConns {
if err := sendSidMessage(ctx, conn, m.Sid, transactionID, detectAddr, key, m.DetectBehavior.TTL); err != nil {
xl.Tracef("send sid message from %s to %s error: %v", conn.LocalAddr(), detectAddr, err)
}
}
}
if len(m.DetectBehavior.CandidatePorts) > 0 {
for _, conn := range listenConns {
sendSidMessageToRangePorts(ctx, conn, m.CandidateAddrs, m.DetectBehavior.CandidatePorts, sendToRangePortsFunc)
}
}
if m.DetectBehavior.SendRandomPorts > 0 {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
for i := range listenConns {
go sendSidMessageToRandomPorts(ctx, listenConns[i], m.CandidateAddrs, m.DetectBehavior.SendRandomPorts, sendToRangePortsFunc)
}
}
timeout := 5 * time.Second
if m.DetectBehavior.ReadTimeoutMs > 0 {
timeout = time.Duration(m.DetectBehavior.ReadTimeoutMs) * time.Millisecond
}
if len(listenConns) == 1 {
raddr, err := waitDetectMessage(ctx, listenConns[0], m.Sid, key, timeout, m.DetectBehavior.Role)
if err != nil {
return nil, nil, fmt.Errorf("wait detect message error: %v", err)
}
return listenConns[0], raddr, nil
}
type result struct {
lConn *net.UDPConn
raddr *net.UDPAddr
}
resultCh := make(chan result)
for _, conn := range listenConns {
go func(lConn *net.UDPConn) {
addr, err := waitDetectMessage(ctx, lConn, m.Sid, key, timeout, m.DetectBehavior.Role)
if err != nil {
lConn.Close()
return
}
select {
case resultCh <- result{lConn: lConn, raddr: addr}:
default:
lConn.Close()
}
}(conn)
}
select {
case result := <-resultCh:
return result.lConn, result.raddr, nil
case <-time.After(timeout):
return nil, nil, fmt.Errorf("wait detect message timeout")
case <-ctx.Done():
return nil, nil, fmt.Errorf("wait detect message canceled")
}
}
func waitDetectMessage(
ctx context.Context, conn *net.UDPConn, sid string, key []byte,
timeout time.Duration, role string,
) (*net.UDPAddr, error) {
xl := xlog.FromContextSafe(ctx)
for {
buf := pool.GetBuf(1024)
_ = conn.SetReadDeadline(time.Now().Add(timeout))
n, raddr, err := conn.ReadFromUDP(buf)
_ = conn.SetReadDeadline(time.Time{})
if err != nil {
return nil, err
}
xl.Debugf("get udp message local %s, from %s", conn.LocalAddr(), raddr)
var m msg.NatHoleSid
if err := DecodeMessageInto(buf[:n], key, &m); err != nil {
xl.Warnf("decode sid message error: %v", err)
continue
}
pool.PutBuf(buf)
if m.Sid != sid {
xl.Warnf("get sid message with wrong sid: %s, expect: %s", m.Sid, sid)
continue
}
if !m.Response {
// only wait for response messages if we are a sender
if role == DetectRoleSender {
continue
}
m.Response = true
buf2, err := EncodeMessage(&m, key)
if err != nil {
xl.Warnf("encode sid message error: %v", err)
continue
}
_, _ = conn.WriteToUDP(buf2, raddr)
}
return raddr, nil
}
}
func sendSidMessage(
ctx context.Context, conn *net.UDPConn,
sid string, transactionID string, addr string, key []byte, ttl int,
) error {
xl := xlog.FromContextSafe(ctx)
ttlStr := ""
if ttl > 0 {
ttlStr = fmt.Sprintf(" with ttl %d", ttl)
}
xl.Tracef("send sid message from %s to %s%s", conn.LocalAddr(), addr, ttlStr)
raddr, err := net.ResolveUDPAddr("udp4", addr)
if err != nil {
return err
}
if transactionID == "" {
transactionID = NewTransactionID()
}
m := &msg.NatHoleSid{
TransactionID: transactionID,
Sid: sid,
Response: false,
Nonce: strings.Repeat("0", rand.IntN(20)),
}
buf, err := EncodeMessage(m, key)
if err != nil {
return err
}
if ttl > 0 {
uConn := ipv4.NewConn(conn)
original, err := uConn.TTL()
if err != nil {
xl.Tracef("get ttl error %v", err)
return err
}
xl.Tracef("original ttl %d", original)
err = uConn.SetTTL(ttl)
if err != nil {
xl.Tracef("set ttl error %v", err)
} else {
defer func() {
_ = uConn.SetTTL(original)
}()
}
}
if _, err := conn.WriteToUDP(buf, raddr); err != nil {
return err
}
return nil
}
func sendSidMessageToRangePorts(
ctx context.Context, conn *net.UDPConn, addrs []string, ports []msg.PortsRange,
sendFunc func(*net.UDPConn, string) error,
) {
xl := xlog.FromContextSafe(ctx)
for _, ip := range slices.Compact(parseIPs(addrs)) {
for _, portsRange := range ports {
for i := portsRange.From; i <= portsRange.To; i++ {
detectAddr := net.JoinHostPort(ip, strconv.Itoa(i))
if err := sendFunc(conn, detectAddr); err != nil {
xl.Tracef("send sid message from %s to %s error: %v", conn.LocalAddr(), detectAddr, err)
}
time.Sleep(2 * time.Millisecond)
}
}
}
}
func sendSidMessageToRandomPorts(
ctx context.Context, conn *net.UDPConn, addrs []string, count int,
sendFunc func(*net.UDPConn, string) error,
) {
xl := xlog.FromContextSafe(ctx)
used := sets.New[int]()
getUnusedPort := func() int {
for i := 0; i < 10; i++ {
port := rand.IntN(65535-1024) + 1024
if !used.Has(port) {
used.Insert(port)
return port
}
}
return 0
}
for i := 0; i < count; i++ {
select {
case <-ctx.Done():
return
default:
}
port := getUnusedPort()
if port == 0 {
continue
}
for _, ip := range slices.Compact(parseIPs(addrs)) {
detectAddr := net.JoinHostPort(ip, strconv.Itoa(port))
if err := sendFunc(conn, detectAddr); err != nil {
xl.Tracef("send sid message from %s to %s error: %v", conn.LocalAddr(), detectAddr, err)
}
time.Sleep(time.Millisecond * 15)
}
}
}
func parseIPs(addrs []string) []string {
var ips []string
for _, addr := range addrs {
if ip, _, err := net.SplitHostPort(addr); err == nil {
ips = append(ips, ip)
}
}
return ips
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/nathole/discovery.go | pkg/nathole/discovery.go | // Copyright 2023 The frp Authors
//
// 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 nathole
import (
"fmt"
"net"
"time"
"github.com/pion/stun/v2"
)
var responseTimeout = 3 * time.Second
type Message struct {
Body []byte
Addr string
}
// If the localAddr is empty, it will listen on a random port.
func Discover(stunServers []string, localAddr string) ([]string, net.Addr, error) {
// create a discoverConn and get response from messageChan
discoverConn, err := listen(localAddr)
if err != nil {
return nil, nil, err
}
defer discoverConn.Close()
go discoverConn.readLoop()
addresses := make([]string, 0, len(stunServers))
for _, addr := range stunServers {
// get external address from stun server
externalAddrs, err := discoverConn.discoverFromStunServer(addr)
if err != nil {
return nil, nil, err
}
addresses = append(addresses, externalAddrs...)
}
return addresses, discoverConn.localAddr, nil
}
type stunResponse struct {
externalAddr string
otherAddr string
}
type discoverConn struct {
conn *net.UDPConn
localAddr net.Addr
messageChan chan *Message
}
func listen(localAddr string) (*discoverConn, error) {
var local *net.UDPAddr
if localAddr != "" {
addr, err := net.ResolveUDPAddr("udp4", localAddr)
if err != nil {
return nil, err
}
local = addr
}
conn, err := net.ListenUDP("udp4", local)
if err != nil {
return nil, err
}
return &discoverConn{
conn: conn,
localAddr: conn.LocalAddr(),
messageChan: make(chan *Message, 10),
}, nil
}
func (c *discoverConn) Close() error {
if c.messageChan != nil {
close(c.messageChan)
c.messageChan = nil
}
return c.conn.Close()
}
func (c *discoverConn) readLoop() {
for {
buf := make([]byte, 1024)
n, addr, err := c.conn.ReadFromUDP(buf)
if err != nil {
return
}
buf = buf[:n]
c.messageChan <- &Message{
Body: buf,
Addr: addr.String(),
}
}
}
func (c *discoverConn) doSTUNRequest(addr string) (*stunResponse, error) {
serverAddr, err := net.ResolveUDPAddr("udp4", addr)
if err != nil {
return nil, err
}
request, err := stun.Build(stun.TransactionID, stun.BindingRequest)
if err != nil {
return nil, err
}
if err = request.NewTransactionID(); err != nil {
return nil, err
}
if _, err := c.conn.WriteTo(request.Raw, serverAddr); err != nil {
return nil, err
}
var m stun.Message
select {
case msg := <-c.messageChan:
m.Raw = msg.Body
if err := m.Decode(); err != nil {
return nil, err
}
case <-time.After(responseTimeout):
return nil, fmt.Errorf("wait response from stun server timeout")
}
xorAddrGetter := &stun.XORMappedAddress{}
mappedAddrGetter := &stun.MappedAddress{}
changedAddrGetter := ChangedAddress{}
otherAddrGetter := &stun.OtherAddress{}
resp := &stunResponse{}
if err := mappedAddrGetter.GetFrom(&m); err == nil {
resp.externalAddr = mappedAddrGetter.String()
}
if err := xorAddrGetter.GetFrom(&m); err == nil {
resp.externalAddr = xorAddrGetter.String()
}
if err := changedAddrGetter.GetFrom(&m); err == nil {
resp.otherAddr = changedAddrGetter.String()
}
if err := otherAddrGetter.GetFrom(&m); err == nil {
resp.otherAddr = otherAddrGetter.String()
}
return resp, nil
}
func (c *discoverConn) discoverFromStunServer(addr string) ([]string, error) {
resp, err := c.doSTUNRequest(addr)
if err != nil {
return nil, err
}
if resp.externalAddr == "" {
return nil, fmt.Errorf("no external address found")
}
externalAddrs := make([]string, 0, 2)
externalAddrs = append(externalAddrs, resp.externalAddr)
if resp.otherAddr == "" {
return externalAddrs, nil
}
// find external address from changed address
resp, err = c.doSTUNRequest(resp.otherAddr)
if err != nil {
return nil, err
}
if resp.externalAddr != "" {
externalAddrs = append(externalAddrs, resp.externalAddr)
}
return externalAddrs, nil
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/nathole/analysis.go | pkg/nathole/analysis.go | // Copyright 2023 The frp Authors
//
// 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 nathole
import (
"cmp"
"slices"
"sync"
"time"
"github.com/samber/lo"
)
var (
// mode 0, both EasyNAT, PublicNetwork is always receiver
// sender | receiver, ttl 7
// receiver, ttl 7 | sender
// sender | receiver, ttl 4
// receiver, ttl 4 | sender
// sender | receiver
// receiver | sender
// sender, sendDelayMs 5000 | receiver
// sender, sendDelayMs 10000 | receiver
// receiver | sender, sendDelayMs 5000
// receiver | sender, sendDelayMs 10000
mode0Behaviors = []lo.Tuple2[RecommandBehavior, RecommandBehavior]{
lo.T2(RecommandBehavior{Role: DetectRoleSender}, RecommandBehavior{Role: DetectRoleReceiver, TTL: 7}),
lo.T2(RecommandBehavior{Role: DetectRoleReceiver, TTL: 7}, RecommandBehavior{Role: DetectRoleSender}),
lo.T2(RecommandBehavior{Role: DetectRoleSender}, RecommandBehavior{Role: DetectRoleReceiver, TTL: 4}),
lo.T2(RecommandBehavior{Role: DetectRoleReceiver, TTL: 4}, RecommandBehavior{Role: DetectRoleSender}),
lo.T2(RecommandBehavior{Role: DetectRoleSender}, RecommandBehavior{Role: DetectRoleReceiver}),
lo.T2(RecommandBehavior{Role: DetectRoleReceiver}, RecommandBehavior{Role: DetectRoleSender}),
lo.T2(RecommandBehavior{Role: DetectRoleSender, SendDelayMs: 5000}, RecommandBehavior{Role: DetectRoleReceiver}),
lo.T2(RecommandBehavior{Role: DetectRoleSender, SendDelayMs: 10000}, RecommandBehavior{Role: DetectRoleReceiver}),
lo.T2(RecommandBehavior{Role: DetectRoleReceiver}, RecommandBehavior{Role: DetectRoleSender, SendDelayMs: 5000}),
lo.T2(RecommandBehavior{Role: DetectRoleReceiver}, RecommandBehavior{Role: DetectRoleSender, SendDelayMs: 10000}),
}
// mode 1, HardNAT is sender, EasyNAT is receiver, port changes is regular
// sender | receiver, ttl 7, portsRangeNumber max 10
// sender, sendDelayMs 2000 | receiver, ttl 7, portsRangeNumber max 10
// sender | receiver, ttl 4, portsRangeNumber max 10
// sender, sendDelayMs 2000 | receiver, ttl 4, portsRangeNumber max 10
// sender | receiver, portsRangeNumber max 10
// sender, sendDelayMs 2000 | receiver, portsRangeNumber max 10
mode1Behaviors = []lo.Tuple2[RecommandBehavior, RecommandBehavior]{
lo.T2(RecommandBehavior{Role: DetectRoleSender}, RecommandBehavior{Role: DetectRoleReceiver, TTL: 7, PortsRangeNumber: 10}),
lo.T2(RecommandBehavior{Role: DetectRoleSender, SendDelayMs: 2000}, RecommandBehavior{Role: DetectRoleReceiver, TTL: 7, PortsRangeNumber: 10}),
lo.T2(RecommandBehavior{Role: DetectRoleSender}, RecommandBehavior{Role: DetectRoleReceiver, TTL: 4, PortsRangeNumber: 10}),
lo.T2(RecommandBehavior{Role: DetectRoleSender, SendDelayMs: 2000}, RecommandBehavior{Role: DetectRoleReceiver, TTL: 4, PortsRangeNumber: 10}),
lo.T2(RecommandBehavior{Role: DetectRoleSender}, RecommandBehavior{Role: DetectRoleReceiver, PortsRangeNumber: 10}),
lo.T2(RecommandBehavior{Role: DetectRoleSender, SendDelayMs: 2000}, RecommandBehavior{Role: DetectRoleReceiver, PortsRangeNumber: 10}),
}
// mode 2, HardNAT is receiver, EasyNAT is sender
// sender, portsRandomNumber 1000, sendDelayMs 3000 | receiver, listen 256 ports, ttl 7
// sender, portsRandomNumber 1000, sendDelayMs 3000 | receiver, listen 256 ports, ttl 4
// sender, portsRandomNumber 1000, sendDelayMs 3000 | receiver, listen 256 ports
mode2Behaviors = []lo.Tuple2[RecommandBehavior, RecommandBehavior]{
lo.T2(
RecommandBehavior{Role: DetectRoleSender, PortsRandomNumber: 1000, SendDelayMs: 3000},
RecommandBehavior{Role: DetectRoleReceiver, ListenRandomPorts: 256, TTL: 7},
),
lo.T2(
RecommandBehavior{Role: DetectRoleSender, PortsRandomNumber: 1000, SendDelayMs: 3000},
RecommandBehavior{Role: DetectRoleReceiver, ListenRandomPorts: 256, TTL: 4},
),
lo.T2(
RecommandBehavior{Role: DetectRoleSender, PortsRandomNumber: 1000, SendDelayMs: 3000},
RecommandBehavior{Role: DetectRoleReceiver, ListenRandomPorts: 256},
),
}
// mode 3, For HardNAT & HardNAT, both changes in the ports are regular
// sender, portsRangeNumber 10 | receiver, ttl 7, portsRangeNumber 10
// sender, portsRangeNumber 10 | receiver, ttl 4, portsRangeNumber 10
// sender, portsRangeNumber 10 | receiver, portsRangeNumber 10
// receiver, ttl 7, portsRangeNumber 10 | sender, portsRangeNumber 10
// receiver, ttl 4, portsRangeNumber 10 | sender, portsRangeNumber 10
// receiver, portsRangeNumber 10 | sender, portsRangeNumber 10
mode3Behaviors = []lo.Tuple2[RecommandBehavior, RecommandBehavior]{
lo.T2(RecommandBehavior{Role: DetectRoleSender, PortsRangeNumber: 10}, RecommandBehavior{Role: DetectRoleReceiver, TTL: 7, PortsRangeNumber: 10}),
lo.T2(RecommandBehavior{Role: DetectRoleSender, PortsRangeNumber: 10}, RecommandBehavior{Role: DetectRoleReceiver, TTL: 4, PortsRangeNumber: 10}),
lo.T2(RecommandBehavior{Role: DetectRoleSender, PortsRangeNumber: 10}, RecommandBehavior{Role: DetectRoleReceiver, PortsRangeNumber: 10}),
lo.T2(RecommandBehavior{Role: DetectRoleReceiver, TTL: 7, PortsRangeNumber: 10}, RecommandBehavior{Role: DetectRoleSender, PortsRangeNumber: 10}),
lo.T2(RecommandBehavior{Role: DetectRoleReceiver, TTL: 4, PortsRangeNumber: 10}, RecommandBehavior{Role: DetectRoleSender, PortsRangeNumber: 10}),
lo.T2(RecommandBehavior{Role: DetectRoleReceiver, PortsRangeNumber: 10}, RecommandBehavior{Role: DetectRoleSender, PortsRangeNumber: 10}),
}
// mode 4, Regular ports changes are usually the sender.
// sender, portsRandomNumber 1000, sendDelayMs: 2000 | receiver, listen 256 ports, ttl 7, portsRangeNumber 2
// sender, portsRandomNumber 1000, sendDelayMs: 2000 | receiver, listen 256 ports, ttl 4, portsRangeNumber 2
// sender, portsRandomNumber 1000, SendDelayMs: 2000 | receiver, listen 256 ports, portsRangeNumber 2
mode4Behaviors = []lo.Tuple2[RecommandBehavior, RecommandBehavior]{
lo.T2(
RecommandBehavior{Role: DetectRoleSender, PortsRandomNumber: 1000, SendDelayMs: 3000},
RecommandBehavior{Role: DetectRoleReceiver, ListenRandomPorts: 256, TTL: 7, PortsRangeNumber: 2},
),
lo.T2(
RecommandBehavior{Role: DetectRoleSender, PortsRandomNumber: 1000, SendDelayMs: 3000},
RecommandBehavior{Role: DetectRoleReceiver, ListenRandomPorts: 256, TTL: 4, PortsRangeNumber: 2},
),
lo.T2(
RecommandBehavior{Role: DetectRoleSender, PortsRandomNumber: 1000, SendDelayMs: 3000},
RecommandBehavior{Role: DetectRoleReceiver, ListenRandomPorts: 256, PortsRangeNumber: 2},
),
}
)
func getBehaviorByMode(mode int) []lo.Tuple2[RecommandBehavior, RecommandBehavior] {
switch mode {
case 0:
return mode0Behaviors
case 1:
return mode1Behaviors
case 2:
return mode2Behaviors
case 3:
return mode3Behaviors
case 4:
return mode4Behaviors
}
// default
return mode0Behaviors
}
func getBehaviorByModeAndIndex(mode int, index int) (RecommandBehavior, RecommandBehavior) {
behaviors := getBehaviorByMode(mode)
if index >= len(behaviors) {
return RecommandBehavior{}, RecommandBehavior{}
}
return behaviors[index].A, behaviors[index].B
}
func getBehaviorScoresByMode(mode int, defaultScore int) []*BehaviorScore {
return getBehaviorScoresByMode2(mode, defaultScore, defaultScore)
}
func getBehaviorScoresByMode2(mode int, senderScore, receiverScore int) []*BehaviorScore {
behaviors := getBehaviorByMode(mode)
scores := make([]*BehaviorScore, 0, len(behaviors))
for i := 0; i < len(behaviors); i++ {
score := receiverScore
if behaviors[i].A.Role == DetectRoleSender {
score = senderScore
}
scores = append(scores, &BehaviorScore{Mode: mode, Index: i, Score: score})
}
return scores
}
type RecommandBehavior struct {
Role string
TTL int
SendDelayMs int
PortsRangeNumber int
PortsRandomNumber int
ListenRandomPorts int
}
type MakeHoleRecords struct {
mu sync.Mutex
scores []*BehaviorScore
LastUpdateTime time.Time
}
func NewMakeHoleRecords(c, v *NatFeature) *MakeHoleRecords {
scores := []*BehaviorScore{}
easyCount, hardCount, portsChangedRegularCount := ClassifyFeatureCount([]*NatFeature{c, v})
appendMode0 := func() {
switch {
case c.PublicNetwork:
scores = append(scores, getBehaviorScoresByMode2(DetectMode0, 0, 1)...)
case v.PublicNetwork:
scores = append(scores, getBehaviorScoresByMode2(DetectMode0, 1, 0)...)
default:
scores = append(scores, getBehaviorScoresByMode(DetectMode0, 0)...)
}
}
switch {
case easyCount == 2:
appendMode0()
case hardCount == 1 && portsChangedRegularCount == 1:
scores = append(scores, getBehaviorScoresByMode(DetectMode1, 0)...)
scores = append(scores, getBehaviorScoresByMode(DetectMode2, 0)...)
appendMode0()
case hardCount == 1 && portsChangedRegularCount == 0:
scores = append(scores, getBehaviorScoresByMode(DetectMode2, 0)...)
scores = append(scores, getBehaviorScoresByMode(DetectMode1, 0)...)
appendMode0()
case hardCount == 2 && portsChangedRegularCount == 2:
scores = append(scores, getBehaviorScoresByMode(DetectMode3, 0)...)
scores = append(scores, getBehaviorScoresByMode(DetectMode4, 0)...)
case hardCount == 2 && portsChangedRegularCount == 1:
scores = append(scores, getBehaviorScoresByMode(DetectMode4, 0)...)
default:
// hard to make hole, just trying it out.
scores = append(scores, getBehaviorScoresByMode(DetectMode0, 1)...)
scores = append(scores, getBehaviorScoresByMode(DetectMode1, 1)...)
scores = append(scores, getBehaviorScoresByMode(DetectMode3, 1)...)
}
return &MakeHoleRecords{scores: scores, LastUpdateTime: time.Now()}
}
func (mhr *MakeHoleRecords) ReportSuccess(mode int, index int) {
mhr.mu.Lock()
defer mhr.mu.Unlock()
mhr.LastUpdateTime = time.Now()
for i := range mhr.scores {
score := mhr.scores[i]
if score.Mode != mode || score.Index != index {
continue
}
score.Score += 2
score.Score = min(score.Score, 10)
return
}
}
func (mhr *MakeHoleRecords) Recommand() (mode, index int) {
mhr.mu.Lock()
defer mhr.mu.Unlock()
if len(mhr.scores) == 0 {
return 0, 0
}
maxScore := slices.MaxFunc(mhr.scores, func(a, b *BehaviorScore) int {
return cmp.Compare(a.Score, b.Score)
})
maxScore.Score--
mhr.LastUpdateTime = time.Now()
return maxScore.Mode, maxScore.Index
}
type BehaviorScore struct {
Mode int
Index int
// between -10 and 10
Score int
}
type Analyzer struct {
// key is client ip + visitor ip
records map[string]*MakeHoleRecords
dataReserveDuration time.Duration
mu sync.Mutex
}
func NewAnalyzer(dataReserveDuration time.Duration) *Analyzer {
return &Analyzer{
records: make(map[string]*MakeHoleRecords),
dataReserveDuration: dataReserveDuration,
}
}
func (a *Analyzer) GetRecommandBehaviors(key string, c, v *NatFeature) (mode, index int, _ RecommandBehavior, _ RecommandBehavior) {
a.mu.Lock()
records, ok := a.records[key]
if !ok {
records = NewMakeHoleRecords(c, v)
a.records[key] = records
}
a.mu.Unlock()
mode, index = records.Recommand()
cBehavior, vBehavior := getBehaviorByModeAndIndex(mode, index)
switch mode {
case DetectMode1:
// HardNAT is always the sender
if c.NatType == EasyNAT {
cBehavior, vBehavior = vBehavior, cBehavior
}
case DetectMode2:
// HardNAT is always the receiver
if c.NatType == HardNAT {
cBehavior, vBehavior = vBehavior, cBehavior
}
case DetectMode4:
// Regular ports changes is always the sender
if !c.RegularPortsChange {
cBehavior, vBehavior = vBehavior, cBehavior
}
}
return mode, index, cBehavior, vBehavior
}
func (a *Analyzer) ReportSuccess(key string, mode, index int) {
a.mu.Lock()
records, ok := a.records[key]
a.mu.Unlock()
if !ok {
return
}
records.ReportSuccess(mode, index)
}
func (a *Analyzer) Clean() (int, int) {
now := time.Now()
total := 0
count := 0
// cleanup 10w records may take 5ms
a.mu.Lock()
defer a.mu.Unlock()
total = len(a.records)
// clean up records that have not been used for a period of time.
for key, records := range a.records {
if now.Sub(records.LastUpdateTime) > a.dataReserveDuration {
delete(a.records, key)
count++
}
}
return count, total
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/msg/msg.go | pkg/msg/msg.go | // Copyright 2016 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 msg
import (
"net"
"reflect"
)
const (
TypeLogin = 'o'
TypeLoginResp = '1'
TypeNewProxy = 'p'
TypeNewProxyResp = '2'
TypeCloseProxy = 'c'
TypeNewWorkConn = 'w'
TypeReqWorkConn = 'r'
TypeStartWorkConn = 's'
TypeNewVisitorConn = 'v'
TypeNewVisitorConnResp = '3'
TypePing = 'h'
TypePong = '4'
TypeUDPPacket = 'u'
TypeNatHoleVisitor = 'i'
TypeNatHoleClient = 'n'
TypeNatHoleResp = 'm'
TypeNatHoleSid = '5'
TypeNatHoleReport = '6'
)
var msgTypeMap = map[byte]any{
TypeLogin: Login{},
TypeLoginResp: LoginResp{},
TypeNewProxy: NewProxy{},
TypeNewProxyResp: NewProxyResp{},
TypeCloseProxy: CloseProxy{},
TypeNewWorkConn: NewWorkConn{},
TypeReqWorkConn: ReqWorkConn{},
TypeStartWorkConn: StartWorkConn{},
TypeNewVisitorConn: NewVisitorConn{},
TypeNewVisitorConnResp: NewVisitorConnResp{},
TypePing: Ping{},
TypePong: Pong{},
TypeUDPPacket: UDPPacket{},
TypeNatHoleVisitor: NatHoleVisitor{},
TypeNatHoleClient: NatHoleClient{},
TypeNatHoleResp: NatHoleResp{},
TypeNatHoleSid: NatHoleSid{},
TypeNatHoleReport: NatHoleReport{},
}
var TypeNameNatHoleResp = reflect.TypeOf(&NatHoleResp{}).Elem().Name()
type ClientSpec struct {
// Due to the support of VirtualClient, frps needs to know the client type in order to
// differentiate the processing logic.
// Optional values: ssh-tunnel
Type string `json:"type,omitempty"`
// If the value is true, the client will not require authentication.
AlwaysAuthPass bool `json:"always_auth_pass,omitempty"`
}
// When frpc start, client send this message to login to server.
type Login struct {
Version string `json:"version,omitempty"`
Hostname string `json:"hostname,omitempty"`
Os string `json:"os,omitempty"`
Arch string `json:"arch,omitempty"`
User string `json:"user,omitempty"`
PrivilegeKey string `json:"privilege_key,omitempty"`
Timestamp int64 `json:"timestamp,omitempty"`
RunID string `json:"run_id,omitempty"`
Metas map[string]string `json:"metas,omitempty"`
// Currently only effective for VirtualClient.
ClientSpec ClientSpec `json:"client_spec,omitempty"`
// Some global configures.
PoolCount int `json:"pool_count,omitempty"`
}
type LoginResp struct {
Version string `json:"version,omitempty"`
RunID string `json:"run_id,omitempty"`
Error string `json:"error,omitempty"`
}
// When frpc login success, send this message to frps for running a new proxy.
type NewProxy struct {
ProxyName string `json:"proxy_name,omitempty"`
ProxyType string `json:"proxy_type,omitempty"`
UseEncryption bool `json:"use_encryption,omitempty"`
UseCompression bool `json:"use_compression,omitempty"`
BandwidthLimit string `json:"bandwidth_limit,omitempty"`
BandwidthLimitMode string `json:"bandwidth_limit_mode,omitempty"`
Group string `json:"group,omitempty"`
GroupKey string `json:"group_key,omitempty"`
Metas map[string]string `json:"metas,omitempty"`
Annotations map[string]string `json:"annotations,omitempty"`
// tcp and udp only
RemotePort int `json:"remote_port,omitempty"`
// http and https only
CustomDomains []string `json:"custom_domains,omitempty"`
SubDomain string `json:"subdomain,omitempty"`
Locations []string `json:"locations,omitempty"`
HTTPUser string `json:"http_user,omitempty"`
HTTPPwd string `json:"http_pwd,omitempty"`
HostHeaderRewrite string `json:"host_header_rewrite,omitempty"`
Headers map[string]string `json:"headers,omitempty"`
ResponseHeaders map[string]string `json:"response_headers,omitempty"`
RouteByHTTPUser string `json:"route_by_http_user,omitempty"`
// stcp, sudp, xtcp
Sk string `json:"sk,omitempty"`
AllowUsers []string `json:"allow_users,omitempty"`
// tcpmux
Multiplexer string `json:"multiplexer,omitempty"`
}
type NewProxyResp struct {
ProxyName string `json:"proxy_name,omitempty"`
RemoteAddr string `json:"remote_addr,omitempty"`
Error string `json:"error,omitempty"`
}
type CloseProxy struct {
ProxyName string `json:"proxy_name,omitempty"`
}
type NewWorkConn struct {
RunID string `json:"run_id,omitempty"`
PrivilegeKey string `json:"privilege_key,omitempty"`
Timestamp int64 `json:"timestamp,omitempty"`
}
type ReqWorkConn struct{}
type StartWorkConn struct {
ProxyName string `json:"proxy_name,omitempty"`
SrcAddr string `json:"src_addr,omitempty"`
DstAddr string `json:"dst_addr,omitempty"`
SrcPort uint16 `json:"src_port,omitempty"`
DstPort uint16 `json:"dst_port,omitempty"`
Error string `json:"error,omitempty"`
}
type NewVisitorConn struct {
RunID string `json:"run_id,omitempty"`
ProxyName string `json:"proxy_name,omitempty"`
SignKey string `json:"sign_key,omitempty"`
Timestamp int64 `json:"timestamp,omitempty"`
UseEncryption bool `json:"use_encryption,omitempty"`
UseCompression bool `json:"use_compression,omitempty"`
}
type NewVisitorConnResp struct {
ProxyName string `json:"proxy_name,omitempty"`
Error string `json:"error,omitempty"`
}
type Ping struct {
PrivilegeKey string `json:"privilege_key,omitempty"`
Timestamp int64 `json:"timestamp,omitempty"`
}
type Pong struct {
Error string `json:"error,omitempty"`
}
type UDPPacket struct {
Content string `json:"c,omitempty"`
LocalAddr *net.UDPAddr `json:"l,omitempty"`
RemoteAddr *net.UDPAddr `json:"r,omitempty"`
}
type NatHoleVisitor struct {
TransactionID string `json:"transaction_id,omitempty"`
ProxyName string `json:"proxy_name,omitempty"`
PreCheck bool `json:"pre_check,omitempty"`
Protocol string `json:"protocol,omitempty"`
SignKey string `json:"sign_key,omitempty"`
Timestamp int64 `json:"timestamp,omitempty"`
MappedAddrs []string `json:"mapped_addrs,omitempty"`
AssistedAddrs []string `json:"assisted_addrs,omitempty"`
}
type NatHoleClient struct {
TransactionID string `json:"transaction_id,omitempty"`
ProxyName string `json:"proxy_name,omitempty"`
Sid string `json:"sid,omitempty"`
MappedAddrs []string `json:"mapped_addrs,omitempty"`
AssistedAddrs []string `json:"assisted_addrs,omitempty"`
}
type PortsRange struct {
From int `json:"from,omitempty"`
To int `json:"to,omitempty"`
}
type NatHoleDetectBehavior struct {
Role string `json:"role,omitempty"` // sender or receiver
Mode int `json:"mode,omitempty"` // 0, 1, 2...
TTL int `json:"ttl,omitempty"`
SendDelayMs int `json:"send_delay_ms,omitempty"`
ReadTimeoutMs int `json:"read_timeout,omitempty"`
CandidatePorts []PortsRange `json:"candidate_ports,omitempty"`
SendRandomPorts int `json:"send_random_ports,omitempty"`
ListenRandomPorts int `json:"listen_random_ports,omitempty"`
}
type NatHoleResp struct {
TransactionID string `json:"transaction_id,omitempty"`
Sid string `json:"sid,omitempty"`
Protocol string `json:"protocol,omitempty"`
CandidateAddrs []string `json:"candidate_addrs,omitempty"`
AssistedAddrs []string `json:"assisted_addrs,omitempty"`
DetectBehavior NatHoleDetectBehavior `json:"detect_behavior,omitempty"`
Error string `json:"error,omitempty"`
}
type NatHoleSid struct {
TransactionID string `json:"transaction_id,omitempty"`
Sid string `json:"sid,omitempty"`
Response bool `json:"response,omitempty"`
Nonce string `json:"nonce,omitempty"`
}
type NatHoleReport struct {
Sid string `json:"sid,omitempty"`
Success bool `json:"success,omitempty"`
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/msg/handler.go | pkg/msg/handler.go | // Copyright 2023 The frp Authors
//
// 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 msg
import (
"io"
"reflect"
)
func AsyncHandler(f func(Message)) func(Message) {
return func(m Message) {
go f(m)
}
}
// Dispatcher is used to send messages to net.Conn or register handlers for messages read from net.Conn.
type Dispatcher struct {
rw io.ReadWriter
sendCh chan Message
doneCh chan struct{}
msgHandlers map[reflect.Type]func(Message)
defaultHandler func(Message)
}
func NewDispatcher(rw io.ReadWriter) *Dispatcher {
return &Dispatcher{
rw: rw,
sendCh: make(chan Message, 100),
doneCh: make(chan struct{}),
msgHandlers: make(map[reflect.Type]func(Message)),
}
}
// Run will block until io.EOF or some error occurs.
func (d *Dispatcher) Run() {
go d.sendLoop()
go d.readLoop()
}
func (d *Dispatcher) sendLoop() {
for {
select {
case <-d.doneCh:
return
case m := <-d.sendCh:
_ = WriteMsg(d.rw, m)
}
}
}
func (d *Dispatcher) readLoop() {
for {
m, err := ReadMsg(d.rw)
if err != nil {
close(d.doneCh)
return
}
if handler, ok := d.msgHandlers[reflect.TypeOf(m)]; ok {
handler(m)
} else if d.defaultHandler != nil {
d.defaultHandler(m)
}
}
}
func (d *Dispatcher) Send(m Message) error {
select {
case <-d.doneCh:
return io.EOF
case d.sendCh <- m:
return nil
}
}
func (d *Dispatcher) RegisterHandler(msg Message, handler func(Message)) {
d.msgHandlers[reflect.TypeOf(msg)] = handler
}
func (d *Dispatcher) RegisterDefaultHandler(handler func(Message)) {
d.defaultHandler = handler
}
func (d *Dispatcher) Done() chan struct{} {
return d.doneCh
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/msg/ctl.go | pkg/msg/ctl.go | // Copyright 2018 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 msg
import (
"io"
jsonMsg "github.com/fatedier/golib/msg/json"
)
type Message = jsonMsg.Message
var msgCtl *jsonMsg.MsgCtl
func init() {
msgCtl = jsonMsg.NewMsgCtl()
for typeByte, msg := range msgTypeMap {
msgCtl.RegisterMsg(typeByte, msg)
}
}
func ReadMsg(c io.Reader) (msg Message, err error) {
return msgCtl.ReadMsg(c)
}
func ReadMsgInto(c io.Reader, msg Message) (err error) {
return msgCtl.ReadMsgInto(c, msg)
}
func WriteMsg(c io.Writer, msg any) (err error) {
return msgCtl.WriteMsg(c, msg)
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/sdk/client/client.go | pkg/sdk/client/client.go | package client
import (
"context"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"net/url"
"strconv"
"strings"
"github.com/fatedier/frp/client"
httppkg "github.com/fatedier/frp/pkg/util/http"
)
type Client struct {
address string
authUser string
authPwd string
}
func New(host string, port int) *Client {
return &Client{
address: net.JoinHostPort(host, strconv.Itoa(port)),
}
}
func (c *Client) SetAuth(user, pwd string) {
c.authUser = user
c.authPwd = pwd
}
func (c *Client) GetProxyStatus(ctx context.Context, name string) (*client.ProxyStatusResp, error) {
req, err := http.NewRequestWithContext(ctx, "GET", "http://"+c.address+"/api/status", nil)
if err != nil {
return nil, err
}
content, err := c.do(req)
if err != nil {
return nil, err
}
allStatus := make(client.StatusResp)
if err = json.Unmarshal([]byte(content), &allStatus); err != nil {
return nil, fmt.Errorf("unmarshal http response error: %s", strings.TrimSpace(content))
}
for _, pss := range allStatus {
for _, ps := range pss {
if ps.Name == name {
return &ps, nil
}
}
}
return nil, fmt.Errorf("no proxy status found")
}
func (c *Client) GetAllProxyStatus(ctx context.Context) (client.StatusResp, error) {
req, err := http.NewRequestWithContext(ctx, "GET", "http://"+c.address+"/api/status", nil)
if err != nil {
return nil, err
}
content, err := c.do(req)
if err != nil {
return nil, err
}
allStatus := make(client.StatusResp)
if err = json.Unmarshal([]byte(content), &allStatus); err != nil {
return nil, fmt.Errorf("unmarshal http response error: %s", strings.TrimSpace(content))
}
return allStatus, nil
}
func (c *Client) Reload(ctx context.Context, strictMode bool) error {
v := url.Values{}
if strictMode {
v.Set("strictConfig", "true")
}
queryStr := ""
if len(v) > 0 {
queryStr = "?" + v.Encode()
}
req, err := http.NewRequestWithContext(ctx, "GET", "http://"+c.address+"/api/reload"+queryStr, nil)
if err != nil {
return err
}
_, err = c.do(req)
return err
}
func (c *Client) Stop(ctx context.Context) error {
req, err := http.NewRequestWithContext(ctx, "POST", "http://"+c.address+"/api/stop", nil)
if err != nil {
return err
}
_, err = c.do(req)
return err
}
func (c *Client) GetConfig(ctx context.Context) (string, error) {
req, err := http.NewRequestWithContext(ctx, "GET", "http://"+c.address+"/api/config", nil)
if err != nil {
return "", err
}
return c.do(req)
}
func (c *Client) UpdateConfig(ctx context.Context, content string) error {
req, err := http.NewRequestWithContext(ctx, "PUT", "http://"+c.address+"/api/config", strings.NewReader(content))
if err != nil {
return err
}
_, err = c.do(req)
return err
}
func (c *Client) setAuthHeader(req *http.Request) {
if c.authUser != "" || c.authPwd != "" {
req.Header.Set("Authorization", httppkg.BasicAuth(c.authUser, c.authPwd))
}
}
func (c *Client) do(req *http.Request) (string, error) {
c.setAuthHeader(req)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return "", fmt.Errorf("api status code [%d]", resp.StatusCode)
}
buf, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(buf), nil
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/policy/security/unsafe.go | pkg/policy/security/unsafe.go | package security
const (
TokenSourceExec = "TokenSourceExec"
)
var (
ClientUnsafeFeatures = []string{
TokenSourceExec,
}
ServerUnsafeFeatures = []string{
TokenSourceExec,
}
)
type UnsafeFeatures struct {
features map[string]bool
}
func NewUnsafeFeatures(allowed []string) *UnsafeFeatures {
features := make(map[string]bool)
for _, f := range allowed {
features[f] = true
}
return &UnsafeFeatures{features: features}
}
func (u *UnsafeFeatures) IsEnabled(feature string) bool {
if u == nil {
return false
}
return u.features[feature]
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/policy/featuregate/feature_gate.go | pkg/policy/featuregate/feature_gate.go | // Copyright 2025 The frp Authors
//
// 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 featuregate
import (
"fmt"
"sort"
"strings"
"sync"
"sync/atomic"
)
// Feature represents a feature gate name
type Feature string
// FeatureStage represents the maturity level of a feature
type FeatureStage string
const (
// Alpha means the feature is experimental and disabled by default
Alpha FeatureStage = "ALPHA"
// Beta means the feature is more stable but still might change and is disabled by default
Beta FeatureStage = "BETA"
// GA means the feature is generally available and enabled by default
GA FeatureStage = ""
)
// FeatureSpec describes a feature and its properties
type FeatureSpec struct {
// Default is the default enablement state for the feature
Default bool
// LockToDefault indicates the feature cannot be changed from its default
LockToDefault bool
// Stage indicates the maturity level of the feature
Stage FeatureStage
}
// Define all available features here
var (
VirtualNet = Feature("VirtualNet")
)
// defaultFeatures defines default features with their specifications
var defaultFeatures = map[Feature]FeatureSpec{
// Actual features
VirtualNet: {Default: false, Stage: Alpha},
}
// FeatureGate indicates whether a given feature is enabled or not
type FeatureGate interface {
// Enabled returns true if the key is enabled
Enabled(key Feature) bool
// KnownFeatures returns a slice of strings describing the known features
KnownFeatures() []string
}
// MutableFeatureGate allows for dynamic feature gate configuration
type MutableFeatureGate interface {
FeatureGate
// SetFromMap sets feature gate values from a map[string]bool
SetFromMap(m map[string]bool) error
// Add adds features to the feature gate
Add(features map[Feature]FeatureSpec) error
// String returns a string representing the feature gate configuration
String() string
}
// featureGate implements the FeatureGate and MutableFeatureGate interfaces
type featureGate struct {
// lock guards writes to known, enabled, and reads/writes of closed
lock sync.Mutex
// known holds a map[Feature]FeatureSpec
known atomic.Value
// enabled holds a map[Feature]bool
enabled atomic.Value
// closed is set to true once the feature gates are considered immutable
closed bool
}
// NewFeatureGate creates a new feature gate with the default features
func NewFeatureGate() MutableFeatureGate {
known := map[Feature]FeatureSpec{}
for k, v := range defaultFeatures {
known[k] = v
}
f := &featureGate{}
f.known.Store(known)
f.enabled.Store(map[Feature]bool{})
return f
}
// SetFromMap sets feature gate values from a map[string]bool
func (f *featureGate) SetFromMap(m map[string]bool) error {
f.lock.Lock()
defer f.lock.Unlock()
// Copy existing state
known := map[Feature]FeatureSpec{}
for k, v := range f.known.Load().(map[Feature]FeatureSpec) {
known[k] = v
}
enabled := map[Feature]bool{}
for k, v := range f.enabled.Load().(map[Feature]bool) {
enabled[k] = v
}
// Apply the new settings
for k, v := range m {
k := Feature(k)
featureSpec, ok := known[k]
if !ok {
return fmt.Errorf("unrecognized feature gate: %s", k)
}
if featureSpec.LockToDefault && featureSpec.Default != v {
return fmt.Errorf("cannot set feature gate %v to %v, feature is locked to %v", k, v, featureSpec.Default)
}
enabled[k] = v
}
// Persist the changes
f.known.Store(known)
f.enabled.Store(enabled)
return nil
}
// Add adds features to the feature gate
func (f *featureGate) Add(features map[Feature]FeatureSpec) error {
f.lock.Lock()
defer f.lock.Unlock()
if f.closed {
return fmt.Errorf("cannot add feature gates after the feature gate is closed")
}
// Copy existing state
known := map[Feature]FeatureSpec{}
for k, v := range f.known.Load().(map[Feature]FeatureSpec) {
known[k] = v
}
// Add new features
for name, spec := range features {
if existingSpec, found := known[name]; found {
if existingSpec == spec {
continue
}
return fmt.Errorf("feature gate %q with different spec already exists: %v", name, existingSpec)
}
known[name] = spec
}
// Persist changes
f.known.Store(known)
return nil
}
// String returns a string containing all enabled feature gates, formatted as "key1=value1,key2=value2,..."
func (f *featureGate) String() string {
pairs := []string{}
for k, v := range f.enabled.Load().(map[Feature]bool) {
pairs = append(pairs, fmt.Sprintf("%s=%t", k, v))
}
sort.Strings(pairs)
return strings.Join(pairs, ",")
}
// Enabled returns true if the key is enabled
func (f *featureGate) Enabled(key Feature) bool {
if v, ok := f.enabled.Load().(map[Feature]bool)[key]; ok {
return v
}
if v, ok := f.known.Load().(map[Feature]FeatureSpec)[key]; ok {
return v.Default
}
return false
}
// KnownFeatures returns a slice of strings describing the FeatureGate's known features
// GA features are hidden from the list
func (f *featureGate) KnownFeatures() []string {
knownFeatures := f.known.Load().(map[Feature]FeatureSpec)
known := make([]string, 0, len(knownFeatures))
for k, v := range knownFeatures {
if v.Stage == GA {
continue
}
known = append(known, fmt.Sprintf("%s=true|false (%s - default=%t)", k, v.Stage, v.Default))
}
sort.Strings(known)
return known
}
// Default feature gates instance
var DefaultFeatureGates = NewFeatureGate()
// Enabled checks if a feature is enabled in the default feature gates
func Enabled(name Feature) bool {
return DefaultFeatureGates.Enabled(name)
}
// SetFromMap sets feature gate values from a map in the default feature gates
func SetFromMap(featureMap map[string]bool) error {
return DefaultFeatureGates.SetFromMap(featureMap)
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/cmd/frps/verify.go | cmd/frps/verify.go | // Copyright 2021 The frp Authors
//
// 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 main
import (
"fmt"
"os"
"github.com/spf13/cobra"
"github.com/fatedier/frp/pkg/config"
"github.com/fatedier/frp/pkg/config/v1/validation"
"github.com/fatedier/frp/pkg/policy/security"
)
func init() {
rootCmd.AddCommand(verifyCmd)
}
var verifyCmd = &cobra.Command{
Use: "verify",
Short: "Verify that the configures is valid",
RunE: func(cmd *cobra.Command, args []string) error {
if cfgFile == "" {
fmt.Println("frps: the configuration file is not specified")
return nil
}
svrCfg, _, err := config.LoadServerConfig(cfgFile, strictConfigMode)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
unsafeFeatures := security.NewUnsafeFeatures(allowUnsafe)
validator := validation.NewConfigValidator(unsafeFeatures)
warning, err := validator.ValidateServerConfig(svrCfg)
if warning != nil {
fmt.Printf("WARNING: %v\n", warning)
}
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Printf("frps: the configuration file %s syntax is ok\n", cfgFile)
return nil
},
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/cmd/frps/root.go | cmd/frps/root.go | // Copyright 2018 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 main
import (
"context"
"fmt"
"os"
"strings"
"github.com/spf13/cobra"
"github.com/fatedier/frp/pkg/config"
v1 "github.com/fatedier/frp/pkg/config/v1"
"github.com/fatedier/frp/pkg/config/v1/validation"
"github.com/fatedier/frp/pkg/policy/security"
"github.com/fatedier/frp/pkg/util/log"
"github.com/fatedier/frp/pkg/util/version"
"github.com/fatedier/frp/server"
)
var (
cfgFile string
showVersion bool
strictConfigMode bool
allowUnsafe []string
serverCfg v1.ServerConfig
)
func init() {
rootCmd.PersistentFlags().StringVarP(&cfgFile, "config", "c", "", "config file of frps")
rootCmd.PersistentFlags().BoolVarP(&showVersion, "version", "v", false, "version of frps")
rootCmd.PersistentFlags().BoolVarP(&strictConfigMode, "strict_config", "", true, "strict config parsing mode, unknown fields will cause errors")
rootCmd.PersistentFlags().StringSliceVarP(&allowUnsafe, "allow-unsafe", "", []string{},
fmt.Sprintf("allowed unsafe features, one or more of: %s", strings.Join(security.ServerUnsafeFeatures, ", ")))
config.RegisterServerConfigFlags(rootCmd, &serverCfg)
}
var rootCmd = &cobra.Command{
Use: "frps",
Short: "frps is the server of frp (https://github.com/fatedier/frp)",
RunE: func(cmd *cobra.Command, args []string) error {
if showVersion {
fmt.Println(version.Full())
return nil
}
var (
svrCfg *v1.ServerConfig
isLegacyFormat bool
err error
)
if cfgFile != "" {
svrCfg, isLegacyFormat, err = config.LoadServerConfig(cfgFile, strictConfigMode)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
if isLegacyFormat {
fmt.Printf("WARNING: ini format is deprecated and the support will be removed in the future, " +
"please use yaml/json/toml format instead!\n")
}
} else {
if err := serverCfg.Complete(); err != nil {
fmt.Printf("failed to complete server config: %v\n", err)
os.Exit(1)
}
svrCfg = &serverCfg
}
unsafeFeatures := security.NewUnsafeFeatures(allowUnsafe)
validator := validation.NewConfigValidator(unsafeFeatures)
warning, err := validator.ValidateServerConfig(svrCfg)
if warning != nil {
fmt.Printf("WARNING: %v\n", warning)
}
if err != nil {
fmt.Println(err)
os.Exit(1)
}
if err := runServer(svrCfg); err != nil {
fmt.Println(err)
os.Exit(1)
}
return nil
},
}
func Execute() {
rootCmd.SetGlobalNormalizationFunc(config.WordSepNormalizeFunc)
if err := rootCmd.Execute(); err != nil {
os.Exit(1)
}
}
func runServer(cfg *v1.ServerConfig) (err error) {
log.InitLogger(cfg.Log.To, cfg.Log.Level, int(cfg.Log.MaxDays), cfg.Log.DisablePrintColor)
if cfgFile != "" {
log.Infof("frps uses config file: %s", cfgFile)
} else {
log.Infof("frps uses command line arguments for config")
}
svr, err := server.NewService(cfg)
if err != nil {
return err
}
log.Infof("frps started successfully")
svr.Run(context.Background())
return
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/cmd/frps/main.go | cmd/frps/main.go | // Copyright 2018 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 main
import (
_ "github.com/fatedier/frp/assets/frps"
_ "github.com/fatedier/frp/pkg/metrics"
"github.com/fatedier/frp/pkg/util/system"
)
func main() {
system.EnableCompatibilityMode()
Execute()
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/cmd/frpc/main.go | cmd/frpc/main.go | // Copyright 2016 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 main
import (
_ "github.com/fatedier/frp/assets/frpc"
"github.com/fatedier/frp/cmd/frpc/sub"
"github.com/fatedier/frp/pkg/util/system"
)
func main() {
system.EnableCompatibilityMode()
sub.Execute()
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/cmd/frpc/sub/admin.go | cmd/frpc/sub/admin.go | // Copyright 2023 The frp Authors
//
// 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 sub
import (
"context"
"fmt"
"os"
"strings"
"time"
"github.com/rodaine/table"
"github.com/spf13/cobra"
"github.com/fatedier/frp/pkg/config"
v1 "github.com/fatedier/frp/pkg/config/v1"
clientsdk "github.com/fatedier/frp/pkg/sdk/client"
)
var adminAPITimeout = 30 * time.Second
func init() {
commands := []struct {
name string
description string
handler func(*v1.ClientCommonConfig) error
}{
{"reload", "Hot-Reload frpc configuration", ReloadHandler},
{"status", "Overview of all proxies status", StatusHandler},
{"stop", "Stop the running frpc", StopHandler},
}
for _, cmdConfig := range commands {
cmd := NewAdminCommand(cmdConfig.name, cmdConfig.description, cmdConfig.handler)
cmd.Flags().DurationVar(&adminAPITimeout, "api-timeout", adminAPITimeout, "Timeout for admin API calls")
rootCmd.AddCommand(cmd)
}
}
func NewAdminCommand(name, short string, handler func(*v1.ClientCommonConfig) error) *cobra.Command {
return &cobra.Command{
Use: name,
Short: short,
Run: func(cmd *cobra.Command, args []string) {
cfg, _, _, _, err := config.LoadClientConfig(cfgFile, strictConfigMode)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
if cfg.WebServer.Port <= 0 {
fmt.Println("web server port should be set if you want to use this feature")
os.Exit(1)
}
if err := handler(cfg); err != nil {
fmt.Println(err)
os.Exit(1)
}
},
}
}
func ReloadHandler(clientCfg *v1.ClientCommonConfig) error {
client := clientsdk.New(clientCfg.WebServer.Addr, clientCfg.WebServer.Port)
client.SetAuth(clientCfg.WebServer.User, clientCfg.WebServer.Password)
ctx, cancel := context.WithTimeout(context.Background(), adminAPITimeout)
defer cancel()
if err := client.Reload(ctx, strictConfigMode); err != nil {
return err
}
fmt.Println("reload success")
return nil
}
func StatusHandler(clientCfg *v1.ClientCommonConfig) error {
client := clientsdk.New(clientCfg.WebServer.Addr, clientCfg.WebServer.Port)
client.SetAuth(clientCfg.WebServer.User, clientCfg.WebServer.Password)
ctx, cancel := context.WithTimeout(context.Background(), adminAPITimeout)
defer cancel()
res, err := client.GetAllProxyStatus(ctx)
if err != nil {
return err
}
fmt.Printf("Proxy Status...\n\n")
for _, typ := range proxyTypes {
arrs := res[string(typ)]
if len(arrs) == 0 {
continue
}
fmt.Println(strings.ToUpper(string(typ)))
tbl := table.New("Name", "Status", "LocalAddr", "Plugin", "RemoteAddr", "Error")
for _, ps := range arrs {
tbl.AddRow(ps.Name, ps.Status, ps.LocalAddr, ps.Plugin, ps.RemoteAddr, ps.Err)
}
tbl.Print()
fmt.Println("")
}
return nil
}
func StopHandler(clientCfg *v1.ClientCommonConfig) error {
client := clientsdk.New(clientCfg.WebServer.Addr, clientCfg.WebServer.Port)
client.SetAuth(clientCfg.WebServer.User, clientCfg.WebServer.Password)
ctx, cancel := context.WithTimeout(context.Background(), adminAPITimeout)
defer cancel()
if err := client.Stop(ctx); err != nil {
return err
}
fmt.Println("stop success")
return nil
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/cmd/frpc/sub/verify.go | cmd/frpc/sub/verify.go | // Copyright 2021 The frp Authors
//
// 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 sub
import (
"fmt"
"os"
"github.com/spf13/cobra"
"github.com/fatedier/frp/pkg/config"
"github.com/fatedier/frp/pkg/config/v1/validation"
"github.com/fatedier/frp/pkg/policy/security"
)
func init() {
rootCmd.AddCommand(verifyCmd)
}
var verifyCmd = &cobra.Command{
Use: "verify",
Short: "Verify that the configures is valid",
RunE: func(cmd *cobra.Command, args []string) error {
if cfgFile == "" {
fmt.Println("frpc: the configuration file is not specified")
return nil
}
cliCfg, proxyCfgs, visitorCfgs, _, err := config.LoadClientConfig(cfgFile, strictConfigMode)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
unsafeFeatures := security.NewUnsafeFeatures(allowUnsafe)
warning, err := validation.ValidateAllClientConfig(cliCfg, proxyCfgs, visitorCfgs, unsafeFeatures)
if warning != nil {
fmt.Printf("WARNING: %v\n", warning)
}
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Printf("frpc: the configuration file %s syntax is ok\n", cfgFile)
return nil
},
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/cmd/frpc/sub/root.go | cmd/frpc/sub/root.go | // Copyright 2018 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 sub
import (
"context"
"fmt"
"io/fs"
"os"
"os/signal"
"path/filepath"
"strings"
"sync"
"syscall"
"time"
"github.com/spf13/cobra"
"github.com/fatedier/frp/client"
"github.com/fatedier/frp/pkg/config"
v1 "github.com/fatedier/frp/pkg/config/v1"
"github.com/fatedier/frp/pkg/config/v1/validation"
"github.com/fatedier/frp/pkg/policy/featuregate"
"github.com/fatedier/frp/pkg/policy/security"
"github.com/fatedier/frp/pkg/util/log"
"github.com/fatedier/frp/pkg/util/version"
)
var (
cfgFile string
cfgDir string
showVersion bool
strictConfigMode bool
allowUnsafe []string
)
func init() {
rootCmd.PersistentFlags().StringVarP(&cfgFile, "config", "c", "./frpc.ini", "config file of frpc")
rootCmd.PersistentFlags().StringVarP(&cfgDir, "config_dir", "", "", "config directory, run one frpc service for each file in config directory")
rootCmd.PersistentFlags().BoolVarP(&showVersion, "version", "v", false, "version of frpc")
rootCmd.PersistentFlags().BoolVarP(&strictConfigMode, "strict_config", "", true, "strict config parsing mode, unknown fields will cause an errors")
rootCmd.PersistentFlags().StringSliceVarP(&allowUnsafe, "allow-unsafe", "", []string{},
fmt.Sprintf("allowed unsafe features, one or more of: %s", strings.Join(security.ClientUnsafeFeatures, ", ")))
}
var rootCmd = &cobra.Command{
Use: "frpc",
Short: "frpc is the client of frp (https://github.com/fatedier/frp)",
RunE: func(cmd *cobra.Command, args []string) error {
if showVersion {
fmt.Println(version.Full())
return nil
}
unsafeFeatures := security.NewUnsafeFeatures(allowUnsafe)
// If cfgDir is not empty, run multiple frpc service for each config file in cfgDir.
// Note that it's only designed for testing. It's not guaranteed to be stable.
if cfgDir != "" {
_ = runMultipleClients(cfgDir, unsafeFeatures)
return nil
}
// Do not show command usage here.
err := runClient(cfgFile, unsafeFeatures)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
return nil
},
}
func runMultipleClients(cfgDir string, unsafeFeatures *security.UnsafeFeatures) error {
var wg sync.WaitGroup
err := filepath.WalkDir(cfgDir, func(path string, d fs.DirEntry, err error) error {
if err != nil || d.IsDir() {
return nil
}
wg.Add(1)
time.Sleep(time.Millisecond)
go func() {
defer wg.Done()
err := runClient(path, unsafeFeatures)
if err != nil {
fmt.Printf("frpc service error for config file [%s]\n", path)
}
}()
return nil
})
wg.Wait()
return err
}
func Execute() {
rootCmd.SetGlobalNormalizationFunc(config.WordSepNormalizeFunc)
if err := rootCmd.Execute(); err != nil {
os.Exit(1)
}
}
func handleTermSignal(svr *client.Service) {
ch := make(chan os.Signal, 1)
signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
<-ch
svr.GracefulClose(500 * time.Millisecond)
}
func runClient(cfgFilePath string, unsafeFeatures *security.UnsafeFeatures) error {
cfg, proxyCfgs, visitorCfgs, isLegacyFormat, err := config.LoadClientConfig(cfgFilePath, strictConfigMode)
if err != nil {
return err
}
if isLegacyFormat {
fmt.Printf("WARNING: ini format is deprecated and the support will be removed in the future, " +
"please use yaml/json/toml format instead!\n")
}
if len(cfg.FeatureGates) > 0 {
if err := featuregate.SetFromMap(cfg.FeatureGates); err != nil {
return err
}
}
warning, err := validation.ValidateAllClientConfig(cfg, proxyCfgs, visitorCfgs, unsafeFeatures)
if warning != nil {
fmt.Printf("WARNING: %v\n", warning)
}
if err != nil {
return err
}
return startService(cfg, proxyCfgs, visitorCfgs, unsafeFeatures, cfgFilePath)
}
func startService(
cfg *v1.ClientCommonConfig,
proxyCfgs []v1.ProxyConfigurer,
visitorCfgs []v1.VisitorConfigurer,
unsafeFeatures *security.UnsafeFeatures,
cfgFile string,
) error {
log.InitLogger(cfg.Log.To, cfg.Log.Level, int(cfg.Log.MaxDays), cfg.Log.DisablePrintColor)
if cfgFile != "" {
log.Infof("start frpc service for config file [%s]", cfgFile)
defer log.Infof("frpc service for config file [%s] stopped", cfgFile)
}
svr, err := client.NewService(client.ServiceOptions{
Common: cfg,
ProxyCfgs: proxyCfgs,
VisitorCfgs: visitorCfgs,
UnsafeFeatures: unsafeFeatures,
ConfigFilePath: cfgFile,
})
if err != nil {
return err
}
shouldGracefulClose := cfg.Transport.Protocol == "kcp" || cfg.Transport.Protocol == "quic"
// Capture the exit signal if we use kcp or quic.
if shouldGracefulClose {
go handleTermSignal(svr)
}
return svr.Run(context.Background())
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/cmd/frpc/sub/proxy.go | cmd/frpc/sub/proxy.go | // Copyright 2023 The frp Authors
//
// 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 sub
import (
"fmt"
"os"
"slices"
"github.com/spf13/cobra"
"github.com/fatedier/frp/pkg/config"
v1 "github.com/fatedier/frp/pkg/config/v1"
"github.com/fatedier/frp/pkg/config/v1/validation"
"github.com/fatedier/frp/pkg/policy/security"
)
var proxyTypes = []v1.ProxyType{
v1.ProxyTypeTCP,
v1.ProxyTypeUDP,
v1.ProxyTypeTCPMUX,
v1.ProxyTypeHTTP,
v1.ProxyTypeHTTPS,
v1.ProxyTypeSTCP,
v1.ProxyTypeSUDP,
v1.ProxyTypeXTCP,
}
var visitorTypes = []v1.VisitorType{
v1.VisitorTypeSTCP,
v1.VisitorTypeSUDP,
v1.VisitorTypeXTCP,
}
func init() {
for _, typ := range proxyTypes {
c := v1.NewProxyConfigurerByType(typ)
if c == nil {
panic("proxy type: " + typ + " not support")
}
clientCfg := v1.ClientCommonConfig{}
cmd := NewProxyCommand(string(typ), c, &clientCfg)
config.RegisterClientCommonConfigFlags(cmd, &clientCfg)
config.RegisterProxyFlags(cmd, c)
// add sub command for visitor
if slices.Contains(visitorTypes, v1.VisitorType(typ)) {
vc := v1.NewVisitorConfigurerByType(v1.VisitorType(typ))
if vc == nil {
panic("visitor type: " + typ + " not support")
}
visitorCmd := NewVisitorCommand(string(typ), vc, &clientCfg)
config.RegisterVisitorFlags(visitorCmd, vc)
cmd.AddCommand(visitorCmd)
}
rootCmd.AddCommand(cmd)
}
}
func NewProxyCommand(name string, c v1.ProxyConfigurer, clientCfg *v1.ClientCommonConfig) *cobra.Command {
return &cobra.Command{
Use: name,
Short: fmt.Sprintf("Run frpc with a single %s proxy", name),
Run: func(cmd *cobra.Command, args []string) {
if err := clientCfg.Complete(); err != nil {
fmt.Println(err)
os.Exit(1)
}
unsafeFeatures := security.NewUnsafeFeatures(allowUnsafe)
validator := validation.NewConfigValidator(unsafeFeatures)
if _, err := validator.ValidateClientCommonConfig(clientCfg); err != nil {
fmt.Println(err)
os.Exit(1)
}
c.Complete(clientCfg.User)
c.GetBaseConfig().Type = name
if err := validation.ValidateProxyConfigurerForClient(c); err != nil {
fmt.Println(err)
os.Exit(1)
}
err := startService(clientCfg, []v1.ProxyConfigurer{c}, nil, unsafeFeatures, "")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
},
}
}
func NewVisitorCommand(name string, c v1.VisitorConfigurer, clientCfg *v1.ClientCommonConfig) *cobra.Command {
return &cobra.Command{
Use: "visitor",
Short: fmt.Sprintf("Run frpc with a single %s visitor", name),
Run: func(cmd *cobra.Command, args []string) {
if err := clientCfg.Complete(); err != nil {
fmt.Println(err)
os.Exit(1)
}
unsafeFeatures := security.NewUnsafeFeatures(allowUnsafe)
validator := validation.NewConfigValidator(unsafeFeatures)
if _, err := validator.ValidateClientCommonConfig(clientCfg); err != nil {
fmt.Println(err)
os.Exit(1)
}
c.Complete(clientCfg)
c.GetBaseConfig().Type = name
if err := validation.ValidateVisitorConfigurer(c); err != nil {
fmt.Println(err)
os.Exit(1)
}
err := startService(clientCfg, nil, []v1.VisitorConfigurer{c}, unsafeFeatures, "")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
},
}
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/cmd/frpc/sub/nathole.go | cmd/frpc/sub/nathole.go | // Copyright 2023 The frp Authors
//
// 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 sub
import (
"fmt"
"os"
"github.com/spf13/cobra"
"github.com/fatedier/frp/pkg/config"
v1 "github.com/fatedier/frp/pkg/config/v1"
"github.com/fatedier/frp/pkg/nathole"
)
var (
natHoleSTUNServer string
natHoleLocalAddr string
)
func init() {
rootCmd.AddCommand(natholeCmd)
natholeCmd.AddCommand(natholeDiscoveryCmd)
natholeCmd.PersistentFlags().StringVarP(&natHoleSTUNServer, "nat_hole_stun_server", "", "", "STUN server address for nathole")
natholeCmd.PersistentFlags().StringVarP(&natHoleLocalAddr, "nat_hole_local_addr", "l", "", "local address to connect STUN server")
}
var natholeCmd = &cobra.Command{
Use: "nathole",
Short: "Actions about nathole",
}
var natholeDiscoveryCmd = &cobra.Command{
Use: "discover",
Short: "Discover nathole information from stun server",
RunE: func(cmd *cobra.Command, args []string) error {
// ignore error here, because we can use command line pameters
cfg, _, _, _, err := config.LoadClientConfig(cfgFile, strictConfigMode)
if err != nil {
cfg = &v1.ClientCommonConfig{}
if err := cfg.Complete(); err != nil {
fmt.Printf("failed to complete config: %v\n", err)
os.Exit(1)
}
}
if natHoleSTUNServer != "" {
cfg.NatHoleSTUNServer = natHoleSTUNServer
}
if err := validateForNatHoleDiscovery(cfg); err != nil {
fmt.Println(err)
os.Exit(1)
}
addrs, localAddr, err := nathole.Discover([]string{cfg.NatHoleSTUNServer}, natHoleLocalAddr)
if err != nil {
fmt.Println("discover error:", err)
os.Exit(1)
}
if len(addrs) < 2 {
fmt.Printf("discover error: can not get enough addresses, need 2, got: %v\n", addrs)
os.Exit(1)
}
localIPs, _ := nathole.ListLocalIPsForNatHole(10)
natFeature, err := nathole.ClassifyNATFeature(addrs, localIPs)
if err != nil {
fmt.Println("classify nat feature error:", err)
os.Exit(1)
}
fmt.Println("STUN server:", cfg.NatHoleSTUNServer)
fmt.Println("Your NAT type is:", natFeature.NatType)
fmt.Println("Behavior is:", natFeature.Behavior)
fmt.Println("External address is:", addrs)
fmt.Println("Local address is:", localAddr.String())
fmt.Println("Public Network:", natFeature.PublicNetwork)
return nil
},
}
func validateForNatHoleDiscovery(cfg *v1.ClientCommonConfig) error {
if cfg.NatHoleSTUNServer == "" {
return fmt.Errorf("nat_hole_stun_server can not be empty")
}
return nil
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/e2e.go | test/e2e/e2e.go | package e2e
import (
"testing"
"github.com/onsi/ginkgo/v2"
"github.com/onsi/gomega"
"github.com/fatedier/frp/pkg/util/log"
"github.com/fatedier/frp/test/e2e/framework"
)
var _ = ginkgo.SynchronizedBeforeSuite(func() []byte {
setupSuite()
return nil
}, func(data []byte) {
// Run on all Ginkgo nodes
setupSuitePerGinkgoNode()
})
var _ = ginkgo.SynchronizedAfterSuite(func() {
CleanupSuite()
}, func() {
AfterSuiteActions()
})
// RunE2ETests checks configuration parameters (specified through flags) and then runs
// E2E tests using the Ginkgo runner.
// If a "report directory" is specified, one or more JUnit test reports will be
// generated in this directory, and cluster logs will also be saved.
// This function is called on each Ginkgo node in parallel mode.
func RunE2ETests(t *testing.T) {
gomega.RegisterFailHandler(framework.Fail)
suiteConfig, reporterConfig := ginkgo.GinkgoConfiguration()
// Turn on EmitSpecProgress to get spec progress (especially on interrupt)
suiteConfig.EmitSpecProgress = true
// Randomize specs as well as suites
suiteConfig.RandomizeAllSpecs = true
log.Infof("starting e2e run %q on Ginkgo node %d of total %d",
framework.RunID, suiteConfig.ParallelProcess, suiteConfig.ParallelTotal)
ginkgo.RunSpecs(t, "frp e2e suite", suiteConfig, reporterConfig)
}
// setupSuite is the boilerplate that can be used to setup ginkgo test suites, on the SynchronizedBeforeSuite step.
// There are certain operations we only want to run once per overall test invocation
// (such as deleting old namespaces, or verifying that all system pods are running.
// Because of the way Ginkgo runs tests in parallel, we must use SynchronizedBeforeSuite
// to ensure that these operations only run on the first parallel Ginkgo node.
//
// This function takes two parameters: one function which runs on only the first Ginkgo node,
// returning an opaque byte array, and then a second function which runs on all Ginkgo nodes,
// accepting the byte array.
func setupSuite() {
// Run only on Ginkgo node 1
}
// setupSuitePerGinkgoNode is the boilerplate that can be used to setup ginkgo test suites, on the SynchronizedBeforeSuite step.
// There are certain operations we only want to run once per overall test invocation on each Ginkgo node
// such as making some global variables accessible to all parallel executions
// Because of the way Ginkgo runs tests in parallel, we must use SynchronizedBeforeSuite
// Ref: https://onsi.github.io/ginkgo/#parallel-specs
func setupSuitePerGinkgoNode() {
// config.GinkgoConfig.ParallelNode
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/e2e_test.go | test/e2e/e2e_test.go | package e2e
import (
"flag"
"fmt"
"os"
"testing"
_ "github.com/onsi/ginkgo/v2"
"github.com/fatedier/frp/pkg/util/log"
// test source
"github.com/fatedier/frp/test/e2e/framework"
_ "github.com/fatedier/frp/test/e2e/legacy/basic"
_ "github.com/fatedier/frp/test/e2e/legacy/features"
_ "github.com/fatedier/frp/test/e2e/legacy/plugin"
_ "github.com/fatedier/frp/test/e2e/v1/basic"
_ "github.com/fatedier/frp/test/e2e/v1/features"
_ "github.com/fatedier/frp/test/e2e/v1/plugin"
)
// handleFlags sets up all flags and parses the command line.
func handleFlags() {
framework.RegisterCommonFlags(flag.CommandLine)
flag.Parse()
}
func TestMain(m *testing.M) {
// Register test flags, then parse flags.
handleFlags()
if err := framework.ValidateTestContext(&framework.TestContext); err != nil {
fmt.Println(err)
os.Exit(1)
}
log.InitLogger("console", framework.TestContext.LogLevel, 0, true)
os.Exit(m.Run())
}
func TestE2E(t *testing.T) {
RunE2ETests(t)
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/examples.go | test/e2e/examples.go | package e2e
import (
"fmt"
"github.com/onsi/ginkgo/v2"
"github.com/fatedier/frp/test/e2e/framework"
"github.com/fatedier/frp/test/e2e/framework/consts"
)
var _ = ginkgo.Describe("[Feature: Example]", func() {
f := framework.NewDefaultFramework()
ginkgo.Describe("TCP", func() {
ginkgo.It("Expose a TCP echo server", func() {
serverConf := consts.DefaultServerConfig
clientConf := consts.DefaultClientConfig
remotePort := f.AllocPort()
clientConf += fmt.Sprintf(`
[[proxies]]
name = "tcp"
type = "tcp"
localPort = {{ .%s }}
remotePort = %d
`, framework.TCPEchoServerPort, remotePort)
f.RunProcesses([]string{serverConf}, []string{clientConf})
framework.NewRequestExpect(f).Port(remotePort).Ensure()
})
})
})
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/suites.go | test/e2e/suites.go | package e2e
// CleanupSuite is the boilerplate that can be used after tests on ginkgo were run, on the SynchronizedAfterSuite step.
// Similar to SynchronizedBeforeSuite, we want to run some operations only once (such as collecting cluster logs).
// Here, the order of functions is reversed; first, the function which runs everywhere,
// and then the function that only runs on the first Ginkgo node.
func CleanupSuite() {
// Run on all Ginkgo nodes
}
// AfterSuiteActions are actions that are run on ginkgo's SynchronizedAfterSuite
func AfterSuiteActions() {
// Run only Ginkgo on node 1
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/pkg/process/process.go | test/e2e/pkg/process/process.go | package process
import (
"bytes"
"context"
"os/exec"
)
type Process struct {
cmd *exec.Cmd
cancel context.CancelFunc
errorOutput *bytes.Buffer
stdOutput *bytes.Buffer
beforeStopHandler func()
stopped bool
}
func New(path string, params []string) *Process {
return NewWithEnvs(path, params, nil)
}
func NewWithEnvs(path string, params []string, envs []string) *Process {
ctx, cancel := context.WithCancel(context.Background())
cmd := exec.CommandContext(ctx, path, params...)
cmd.Env = envs
p := &Process{
cmd: cmd,
cancel: cancel,
}
p.errorOutput = bytes.NewBufferString("")
p.stdOutput = bytes.NewBufferString("")
cmd.Stderr = p.errorOutput
cmd.Stdout = p.stdOutput
return p
}
func (p *Process) Start() error {
return p.cmd.Start()
}
func (p *Process) Stop() error {
if p.stopped {
return nil
}
defer func() {
p.stopped = true
}()
if p.beforeStopHandler != nil {
p.beforeStopHandler()
}
p.cancel()
return p.cmd.Wait()
}
func (p *Process) ErrorOutput() string {
return p.errorOutput.String()
}
func (p *Process) StdOutput() string {
return p.stdOutput.String()
}
func (p *Process) SetBeforeStopHandler(fn func()) {
p.beforeStopHandler = fn
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/pkg/plugin/plugin.go | test/e2e/pkg/plugin/plugin.go | package plugin
import (
"crypto/tls"
"encoding/json"
"io"
"net/http"
plugin "github.com/fatedier/frp/pkg/plugin/server"
"github.com/fatedier/frp/pkg/util/log"
"github.com/fatedier/frp/test/e2e/mock/server/httpserver"
)
type Handler func(req *plugin.Request) *plugin.Response
type NewPluginRequest func() *plugin.Request
func NewHTTPPluginServer(port int, newFunc NewPluginRequest, handler Handler, tlsConfig *tls.Config) *httpserver.Server {
return httpserver.New(
httpserver.WithBindPort(port),
httpserver.WithTLSConfig(tlsConfig),
httpserver.WithHandler(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
r := newFunc()
buf, err := io.ReadAll(req.Body)
if err != nil {
w.WriteHeader(500)
return
}
log.Tracef("plugin request: %s", string(buf))
err = json.Unmarshal(buf, &r)
if err != nil {
w.WriteHeader(500)
return
}
resp := handler(r)
buf, _ = json.Marshal(resp)
log.Tracef("plugin response: %s", string(buf))
_, _ = w.Write(buf)
})),
)
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/pkg/port/port.go | test/e2e/pkg/port/port.go | package port
import (
"fmt"
"net"
"strconv"
"sync"
"k8s.io/apimachinery/pkg/util/sets"
)
type Allocator struct {
reserved sets.Set[int]
used sets.Set[int]
mu sync.Mutex
}
// NewAllocator return a port allocator for testing.
// Example: from: 10, to: 20, mod 4, index 1
// Reserved ports: 13, 17
func NewAllocator(from int, to int, mod int, index int) *Allocator {
pa := &Allocator{
reserved: sets.New[int](),
used: sets.New[int](),
}
for i := from; i <= to; i++ {
if i%mod == index {
pa.reserved.Insert(i)
}
}
return pa
}
func (pa *Allocator) Get() int {
return pa.GetByName("")
}
func (pa *Allocator) GetByName(portName string) int {
var builder *nameBuilder
if portName == "" {
builder = &nameBuilder{}
} else {
var err error
builder, err = unmarshalFromName(portName)
if err != nil {
fmt.Println(err, portName)
return 0
}
}
pa.mu.Lock()
defer pa.mu.Unlock()
for i := 0; i < 20; i++ {
port := pa.getByRange(builder.rangePortFrom, builder.rangePortTo)
if port == 0 {
return 0
}
l, err := net.Listen("tcp", net.JoinHostPort("0.0.0.0", strconv.Itoa(port)))
if err != nil {
// Maybe not controlled by us, mark it used.
pa.used.Insert(port)
continue
}
l.Close()
udpAddr, err := net.ResolveUDPAddr("udp", net.JoinHostPort("0.0.0.0", strconv.Itoa(port)))
if err != nil {
continue
}
udpConn, err := net.ListenUDP("udp", udpAddr)
if err != nil {
// Maybe not controlled by us, mark it used.
pa.used.Insert(port)
continue
}
udpConn.Close()
pa.used.Insert(port)
pa.reserved.Delete(port)
return port
}
return 0
}
func (pa *Allocator) getByRange(from, to int) int {
if from <= 0 {
port, _ := pa.reserved.PopAny()
return port
}
// choose a random port between from - to
ports := pa.reserved.UnsortedList()
for _, port := range ports {
if port >= from && port <= to {
return port
}
}
return 0
}
func (pa *Allocator) Release(port int) {
if port <= 0 {
return
}
pa.mu.Lock()
defer pa.mu.Unlock()
if pa.used.Has(port) {
pa.used.Delete(port)
pa.reserved.Insert(port)
}
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/pkg/port/util.go | test/e2e/pkg/port/util.go | package port
import (
"fmt"
"strconv"
"strings"
)
const (
NameDelimiter = "_"
)
type NameOption func(*nameBuilder) *nameBuilder
type nameBuilder struct {
name string
rangePortFrom int
rangePortTo int
}
func unmarshalFromName(name string) (*nameBuilder, error) {
var builder nameBuilder
arrs := strings.Split(name, NameDelimiter)
switch len(arrs) {
case 2:
builder.name = arrs[1]
case 4:
builder.name = arrs[1]
fromPort, err := strconv.Atoi(arrs[2])
if err != nil {
return nil, fmt.Errorf("error range port from")
}
builder.rangePortFrom = fromPort
toPort, err := strconv.Atoi(arrs[3])
if err != nil {
return nil, fmt.Errorf("error range port to")
}
builder.rangePortTo = toPort
default:
return nil, fmt.Errorf("error port name format")
}
return &builder, nil
}
func (builder *nameBuilder) String() string {
name := fmt.Sprintf("Port%s%s", NameDelimiter, builder.name)
if builder.rangePortFrom > 0 && builder.rangePortTo > 0 && builder.rangePortTo > builder.rangePortFrom {
name += fmt.Sprintf("%s%d%s%d", NameDelimiter, builder.rangePortFrom, NameDelimiter, builder.rangePortTo)
}
return name
}
func WithRangePorts(from, to int) NameOption {
return func(builder *nameBuilder) *nameBuilder {
builder.rangePortFrom = from
builder.rangePortTo = to
return builder
}
}
func GenName(name string, options ...NameOption) string {
name = strings.ReplaceAll(name, "-", "")
name = strings.ReplaceAll(name, "_", "")
builder := &nameBuilder{name: name}
for _, option := range options {
builder = option(builder)
}
return builder.String()
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/pkg/cert/generator.go | test/e2e/pkg/cert/generator.go | package cert
import (
"crypto/tls"
"crypto/x509"
"encoding/pem"
"time"
)
// Artifacts hosts a private key, its corresponding serving certificate and
// the CA certificate that signs the serving certificate.
type Artifacts struct {
// PEM encoded private key
Key []byte
// PEM encoded serving certificate
Cert []byte
// PEM encoded CA private key
CAKey []byte
// PEM encoded CA certificate
CACert []byte
// Resource version of the certs
ResourceVersion string
}
// Generator is an interface to provision the serving certificate.
type Generator interface {
// Generate returns a Artifacts struct.
Generate(CommonName string) (*Artifacts, error)
// SetCA sets the PEM-encoded CA private key and CA cert for signing the generated serving cert.
SetCA(caKey, caCert []byte)
}
// ValidCACert think cert and key are valid if they meet the following requirements:
// - key and cert are valid pair
// - caCert is the root ca of cert
// - cert is for dnsName
// - cert won't expire before time
func ValidCACert(key, cert, caCert []byte, dnsName string, time time.Time) bool {
if len(key) == 0 || len(cert) == 0 || len(caCert) == 0 {
return false
}
// Verify key and cert are valid pair
_, err := tls.X509KeyPair(cert, key)
if err != nil {
return false
}
// Verify cert is valid for at least 1 year.
pool := x509.NewCertPool()
if !pool.AppendCertsFromPEM(caCert) {
return false
}
block, _ := pem.Decode(cert)
if block == nil {
return false
}
c, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return false
}
ops := x509.VerifyOptions{
DNSName: dnsName,
Roots: pool,
CurrentTime: time,
}
_, err = c.Verify(ops)
return err == nil
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/pkg/cert/selfsigned.go | test/e2e/pkg/cert/selfsigned.go | package cert
import (
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"errors"
"fmt"
"math"
"math/big"
"net"
"time"
"k8s.io/client-go/util/cert"
"k8s.io/client-go/util/keyutil"
)
type SelfSignedCertGenerator struct {
caKey []byte
caCert []byte
}
var _ Generator = &SelfSignedCertGenerator{}
// SetCA sets the PEM-encoded CA private key and CA cert for signing the generated serving cert.
func (cp *SelfSignedCertGenerator) SetCA(caKey, caCert []byte) {
cp.caKey = caKey
cp.caCert = caCert
}
// Generate creates and returns a CA certificate, certificate and
// key for the server or client. Key and Cert are used by the server or client
// to establish trust for others, CA certificate is used by the
// client or server to verify the other's authentication chain.
// The cert will be valid for 365 days.
func (cp *SelfSignedCertGenerator) Generate(commonName string) (*Artifacts, error) {
var signingKey *rsa.PrivateKey
var signingCert *x509.Certificate
var valid bool
var err error
valid, signingKey, signingCert = cp.validCACert()
if !valid {
signingKey, err = NewPrivateKey()
if err != nil {
return nil, fmt.Errorf("failed to create the CA private key: %v", err)
}
signingCert, err = cert.NewSelfSignedCACert(cert.Config{CommonName: commonName}, signingKey)
if err != nil {
return nil, fmt.Errorf("failed to create the CA cert: %v", err)
}
}
hostIP := net.ParseIP(commonName)
var altIPs []net.IP
DNSNames := []string{"localhost"}
if hostIP.To4() != nil {
altIPs = append(altIPs, hostIP.To4())
} else {
DNSNames = append(DNSNames, commonName)
}
key, err := NewPrivateKey()
if err != nil {
return nil, fmt.Errorf("failed to create the private key: %v", err)
}
signedCert, err := NewSignedCert(
cert.Config{
CommonName: commonName,
Usages: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth},
AltNames: cert.AltNames{IPs: altIPs, DNSNames: DNSNames},
},
key, signingCert, signingKey,
)
if err != nil {
return nil, fmt.Errorf("failed to create the cert: %v", err)
}
return &Artifacts{
Key: EncodePrivateKeyPEM(key),
Cert: EncodeCertPEM(signedCert),
CAKey: EncodePrivateKeyPEM(signingKey),
CACert: EncodeCertPEM(signingCert),
}, nil
}
func (cp *SelfSignedCertGenerator) validCACert() (bool, *rsa.PrivateKey, *x509.Certificate) {
if !ValidCACert(cp.caKey, cp.caCert, cp.caCert, "",
time.Now().AddDate(1, 0, 0)) {
return false, nil, nil
}
var ok bool
key, err := keyutil.ParsePrivateKeyPEM(cp.caKey)
if err != nil {
return false, nil, nil
}
privateKey, ok := key.(*rsa.PrivateKey)
if !ok {
return false, nil, nil
}
certs, err := cert.ParseCertsPEM(cp.caCert)
if err != nil {
return false, nil, nil
}
if len(certs) != 1 {
return false, nil, nil
}
return true, privateKey, certs[0]
}
// NewPrivateKey creates an RSA private key
func NewPrivateKey() (*rsa.PrivateKey, error) {
return rsa.GenerateKey(rand.Reader, 2048)
}
// NewSignedCert creates a signed certificate using the given CA certificate and key
func NewSignedCert(cfg cert.Config, key crypto.Signer, caCert *x509.Certificate, caKey crypto.Signer) (*x509.Certificate, error) {
serial, err := rand.Int(rand.Reader, new(big.Int).SetInt64(math.MaxInt64))
if err != nil {
return nil, err
}
if len(cfg.CommonName) == 0 {
return nil, errors.New("must specify a CommonName")
}
if len(cfg.Usages) == 0 {
return nil, errors.New("must specify at least one ExtKeyUsage")
}
certTmpl := x509.Certificate{
Subject: pkix.Name{
CommonName: cfg.CommonName,
Organization: cfg.Organization,
},
DNSNames: cfg.AltNames.DNSNames,
IPAddresses: cfg.AltNames.IPs,
SerialNumber: serial,
NotBefore: caCert.NotBefore,
NotAfter: time.Now().Add(time.Hour * 24 * 365 * 10).UTC(),
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: cfg.Usages,
}
certDERBytes, err := x509.CreateCertificate(rand.Reader, &certTmpl, caCert, key.Public(), caKey)
if err != nil {
return nil, err
}
return x509.ParseCertificate(certDERBytes)
}
// EncodePrivateKeyPEM returns PEM-encoded private key data
func EncodePrivateKeyPEM(key *rsa.PrivateKey) []byte {
block := pem.Block{
Type: keyutil.RSAPrivateKeyBlockType,
Bytes: x509.MarshalPKCS1PrivateKey(key),
}
return pem.EncodeToMemory(&block)
}
// EncodeCertPEM returns PEM-encoded certificate data
func EncodeCertPEM(ct *x509.Certificate) []byte {
block := pem.Block{
Type: cert.CertificateBlockType,
Bytes: ct.Raw,
}
return pem.EncodeToMemory(&block)
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/pkg/rpc/rpc.go | test/e2e/pkg/rpc/rpc.go | package rpc
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"io"
)
func WriteBytes(w io.Writer, buf []byte) (int, error) {
out := bytes.NewBuffer(nil)
if err := binary.Write(out, binary.BigEndian, int64(len(buf))); err != nil {
return 0, err
}
out.Write(buf)
return w.Write(out.Bytes())
}
func ReadBytes(r io.Reader) ([]byte, error) {
var length int64
if err := binary.Read(r, binary.BigEndian, &length); err != nil {
return nil, err
}
if length < 0 || length > 10*1024*1024 {
return nil, fmt.Errorf("invalid length")
}
buffer := make([]byte, length)
n, err := io.ReadFull(r, buffer)
if err != nil {
return nil, err
}
if int64(n) != length {
return nil, errors.New("invalid length")
}
return buffer, nil
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/pkg/ssh/client.go | test/e2e/pkg/ssh/client.go | package ssh
import (
"net"
libio "github.com/fatedier/golib/io"
"golang.org/x/crypto/ssh"
)
type TunnelClient struct {
localAddr string
sshServer string
commands string
sshConn *ssh.Client
ln net.Listener
}
func NewTunnelClient(localAddr string, sshServer string, commands string) *TunnelClient {
return &TunnelClient{
localAddr: localAddr,
sshServer: sshServer,
commands: commands,
}
}
func (c *TunnelClient) Start() error {
config := &ssh.ClientConfig{
User: "v0",
HostKeyCallback: func(string, net.Addr, ssh.PublicKey) error { return nil },
}
conn, err := ssh.Dial("tcp", c.sshServer, config)
if err != nil {
return err
}
c.sshConn = conn
l, err := conn.Listen("tcp", "0.0.0.0:80")
if err != nil {
return err
}
c.ln = l
ch, req, err := conn.OpenChannel("session", []byte(""))
if err != nil {
return err
}
defer ch.Close()
go ssh.DiscardRequests(req)
type command struct {
Cmd string
}
_, err = ch.SendRequest("exec", false, ssh.Marshal(command{Cmd: c.commands}))
if err != nil {
return err
}
go c.serveListener()
return nil
}
func (c *TunnelClient) Close() {
if c.sshConn != nil {
_ = c.sshConn.Close()
}
if c.ln != nil {
_ = c.ln.Close()
}
}
func (c *TunnelClient) serveListener() {
for {
conn, err := c.ln.Accept()
if err != nil {
return
}
go c.hanldeConn(conn)
}
}
func (c *TunnelClient) hanldeConn(conn net.Conn) {
defer conn.Close()
local, err := net.Dial("tcp", c.localAddr)
if err != nil {
return
}
_, _, _ = libio.Join(local, conn)
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/pkg/request/request.go | test/e2e/pkg/request/request.go | package request
import (
"bufio"
"bytes"
"crypto/tls"
"fmt"
"io"
"net"
"net/http"
"net/url"
"strconv"
"time"
libnet "github.com/fatedier/golib/net"
httppkg "github.com/fatedier/frp/pkg/util/http"
"github.com/fatedier/frp/test/e2e/pkg/rpc"
)
type Request struct {
protocol string
// for all protocol
addr string
port int
body []byte
timeout time.Duration
resolver *net.Resolver
// for http or https
method string
host string
path string
headers map[string]string
tlsConfig *tls.Config
authValue string
proxyURL string
}
func New() *Request {
return &Request{
protocol: "tcp",
addr: "127.0.0.1",
method: "GET",
path: "/",
headers: map[string]string{},
}
}
func (r *Request) Protocol(protocol string) *Request {
r.protocol = protocol
return r
}
func (r *Request) TCP() *Request {
r.protocol = "tcp"
return r
}
func (r *Request) UDP() *Request {
r.protocol = "udp"
return r
}
func (r *Request) HTTP() *Request {
r.protocol = "http"
return r
}
func (r *Request) HTTPS() *Request {
r.protocol = "https"
return r
}
func (r *Request) Proxy(url string) *Request {
r.proxyURL = url
return r
}
func (r *Request) Addr(addr string) *Request {
r.addr = addr
return r
}
func (r *Request) Port(port int) *Request {
r.port = port
return r
}
func (r *Request) HTTPParams(method, host, path string, headers map[string]string) *Request {
r.method = method
r.host = host
r.path = path
r.headers = headers
return r
}
func (r *Request) HTTPHost(host string) *Request {
r.host = host
return r
}
func (r *Request) HTTPPath(path string) *Request {
r.path = path
return r
}
func (r *Request) HTTPHeaders(headers map[string]string) *Request {
r.headers = headers
return r
}
func (r *Request) HTTPAuth(user, password string) *Request {
r.authValue = httppkg.BasicAuth(user, password)
return r
}
func (r *Request) TLSConfig(tlsConfig *tls.Config) *Request {
r.tlsConfig = tlsConfig
return r
}
func (r *Request) Timeout(timeout time.Duration) *Request {
r.timeout = timeout
return r
}
func (r *Request) Body(content []byte) *Request {
r.body = content
return r
}
func (r *Request) Resolver(resolver *net.Resolver) *Request {
r.resolver = resolver
return r
}
func (r *Request) Do() (*Response, error) {
var (
conn net.Conn
err error
)
addr := r.addr
if r.port > 0 {
addr = net.JoinHostPort(r.addr, strconv.Itoa(r.port))
}
// for protocol http and https
if r.protocol == "http" || r.protocol == "https" {
return r.sendHTTPRequest(r.method, fmt.Sprintf("%s://%s%s", r.protocol, addr, r.path),
r.host, r.headers, r.proxyURL, r.body, r.tlsConfig)
}
// for protocol tcp and udp
if len(r.proxyURL) > 0 {
if r.protocol != "tcp" {
return nil, fmt.Errorf("only tcp protocol is allowed for proxy")
}
proxyType, proxyAddress, auth, err := libnet.ParseProxyURL(r.proxyURL)
if err != nil {
return nil, fmt.Errorf("parse ProxyURL error: %v", err)
}
conn, err = libnet.Dial(addr, libnet.WithProxy(proxyType, proxyAddress), libnet.WithProxyAuth(auth))
if err != nil {
return nil, err
}
} else {
dialer := &net.Dialer{Resolver: r.resolver}
switch r.protocol {
case "tcp":
conn, err = dialer.Dial("tcp", addr)
case "udp":
conn, err = dialer.Dial("udp", addr)
default:
return nil, fmt.Errorf("invalid protocol")
}
if err != nil {
return nil, err
}
}
defer conn.Close()
if r.timeout > 0 {
_ = conn.SetDeadline(time.Now().Add(r.timeout))
}
buf, err := r.sendRequestByConn(conn, r.body)
if err != nil {
return nil, err
}
return &Response{Content: buf}, nil
}
type Response struct {
Code int
Header http.Header
Content []byte
}
func (r *Request) sendHTTPRequest(method, urlstr string, host string, headers map[string]string,
proxy string, body []byte, tlsConfig *tls.Config,
) (*Response, error) {
var inBody io.Reader
if len(body) != 0 {
inBody = bytes.NewReader(body)
}
req, err := http.NewRequest(method, urlstr, inBody)
if err != nil {
return nil, err
}
if host != "" {
req.Host = host
}
for k, v := range headers {
req.Header.Set(k, v)
}
if r.authValue != "" {
req.Header.Set("Authorization", r.authValue)
}
tr := &http.Transport{
DialContext: (&net.Dialer{
Timeout: time.Second,
KeepAlive: 30 * time.Second,
DualStack: true,
Resolver: r.resolver,
}).DialContext,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
TLSClientConfig: tlsConfig,
}
if len(proxy) != 0 {
tr.Proxy = func(req *http.Request) (*url.URL, error) {
return url.Parse(proxy)
}
}
client := http.Client{Transport: tr}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
ret := &Response{Code: resp.StatusCode, Header: resp.Header}
buf, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
ret.Content = buf
return ret, nil
}
func (r *Request) sendRequestByConn(c net.Conn, content []byte) ([]byte, error) {
_, err := rpc.WriteBytes(c, content)
if err != nil {
return nil, fmt.Errorf("write error: %v", err)
}
var reader io.Reader = c
if r.protocol == "udp" {
reader = bufio.NewReader(c)
}
buf, err := rpc.ReadBytes(reader)
if err != nil {
return nil, fmt.Errorf("read error: %v", err)
}
return buf, nil
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/mock/server/interface.go | test/e2e/mock/server/interface.go | package server
type Server interface {
Run() error
Close() error
BindAddr() string
BindPort() int
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/mock/server/streamserver/server.go | test/e2e/mock/server/streamserver/server.go | package streamserver
import (
"bufio"
"fmt"
"io"
"net"
"strconv"
libnet "github.com/fatedier/frp/pkg/util/net"
"github.com/fatedier/frp/test/e2e/pkg/rpc"
)
type Type string
const (
TCP Type = "tcp"
UDP Type = "udp"
Unix Type = "unix"
)
type Server struct {
netType Type
bindAddr string
bindPort int
respContent []byte
handler func(net.Conn)
l net.Listener
}
type Option func(*Server) *Server
func New(netType Type, options ...Option) *Server {
s := &Server{
netType: netType,
bindAddr: "127.0.0.1",
}
s.handler = s.handle
for _, option := range options {
s = option(s)
}
return s
}
func WithBindAddr(addr string) Option {
return func(s *Server) *Server {
s.bindAddr = addr
return s
}
}
func WithBindPort(port int) Option {
return func(s *Server) *Server {
s.bindPort = port
return s
}
}
func WithRespContent(content []byte) Option {
return func(s *Server) *Server {
s.respContent = content
return s
}
}
func WithCustomHandler(handler func(net.Conn)) Option {
return func(s *Server) *Server {
s.handler = handler
return s
}
}
func (s *Server) Run() error {
if err := s.initListener(); err != nil {
return err
}
go func() {
for {
c, err := s.l.Accept()
if err != nil {
return
}
go s.handler(c)
}
}()
return nil
}
func (s *Server) Close() error {
if s.l != nil {
return s.l.Close()
}
return nil
}
func (s *Server) initListener() (err error) {
switch s.netType {
case TCP:
s.l, err = net.Listen("tcp", net.JoinHostPort(s.bindAddr, strconv.Itoa(s.bindPort)))
case UDP:
s.l, err = libnet.ListenUDP(s.bindAddr, s.bindPort)
case Unix:
s.l, err = net.Listen("unix", s.bindAddr)
default:
return fmt.Errorf("unknown server type: %s", s.netType)
}
return err
}
func (s *Server) handle(c net.Conn) {
defer c.Close()
var reader io.Reader = c
if s.netType == UDP {
reader = bufio.NewReader(c)
}
for {
buf, err := rpc.ReadBytes(reader)
if err != nil {
return
}
if len(s.respContent) > 0 {
buf = s.respContent
}
_, _ = rpc.WriteBytes(c, buf)
}
}
func (s *Server) BindAddr() string {
return s.bindAddr
}
func (s *Server) BindPort() int {
return s.bindPort
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/mock/server/httpserver/server.go | test/e2e/mock/server/httpserver/server.go | package httpserver
import (
"crypto/tls"
"net"
"net/http"
"strconv"
"time"
)
type Server struct {
bindAddr string
bindPort int
handler http.Handler
l net.Listener
tlsConfig *tls.Config
hs *http.Server
}
type Option func(*Server) *Server
func New(options ...Option) *Server {
s := &Server{
bindAddr: "127.0.0.1",
}
for _, option := range options {
s = option(s)
}
return s
}
func WithBindAddr(addr string) Option {
return func(s *Server) *Server {
s.bindAddr = addr
return s
}
}
func WithBindPort(port int) Option {
return func(s *Server) *Server {
s.bindPort = port
return s
}
}
func WithTLSConfig(tlsConfig *tls.Config) Option {
return func(s *Server) *Server {
s.tlsConfig = tlsConfig
return s
}
}
func WithHandler(h http.Handler) Option {
return func(s *Server) *Server {
s.handler = h
return s
}
}
func WithResponse(resp []byte) Option {
return func(s *Server) *Server {
s.handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write(resp)
})
return s
}
}
func (s *Server) Run() error {
if err := s.initListener(); err != nil {
return err
}
addr := net.JoinHostPort(s.bindAddr, strconv.Itoa(s.bindPort))
hs := &http.Server{
Addr: addr,
Handler: s.handler,
TLSConfig: s.tlsConfig,
ReadHeaderTimeout: time.Minute,
}
s.hs = hs
if s.tlsConfig == nil {
go func() {
_ = hs.Serve(s.l)
}()
} else {
go func() {
_ = hs.ServeTLS(s.l, "", "")
}()
}
return nil
}
func (s *Server) Close() error {
if s.hs != nil {
return s.hs.Close()
}
return nil
}
func (s *Server) initListener() (err error) {
s.l, err = net.Listen("tcp", net.JoinHostPort(s.bindAddr, strconv.Itoa(s.bindPort)))
return
}
func (s *Server) BindAddr() string {
return s.bindAddr
}
func (s *Server) BindPort() int {
return s.bindPort
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/v1/plugin/client.go | test/e2e/v1/plugin/client.go | package plugin
import (
"crypto/tls"
"fmt"
"net/http"
"strconv"
"github.com/onsi/ginkgo/v2"
"github.com/fatedier/frp/pkg/transport"
"github.com/fatedier/frp/test/e2e/framework"
"github.com/fatedier/frp/test/e2e/framework/consts"
"github.com/fatedier/frp/test/e2e/mock/server/httpserver"
"github.com/fatedier/frp/test/e2e/pkg/cert"
"github.com/fatedier/frp/test/e2e/pkg/port"
"github.com/fatedier/frp/test/e2e/pkg/request"
)
var _ = ginkgo.Describe("[Feature: Client-Plugins]", func() {
f := framework.NewDefaultFramework()
ginkgo.Describe("UnixDomainSocket", func() {
ginkgo.It("Expose a unix domain socket echo server", func() {
serverConf := consts.DefaultServerConfig
clientConf := consts.DefaultClientConfig
getProxyConf := func(proxyName string, portName string, extra string) string {
return fmt.Sprintf(`
[[proxies]]
name = "%s"
type = "tcp"
remotePort = {{ .%s }}
`+extra, proxyName, portName) + fmt.Sprintf(`
[proxies.plugin]
type = "unix_domain_socket"
unixPath = "{{ .%s }}"
`, framework.UDSEchoServerAddr)
}
tests := []struct {
proxyName string
portName string
extraConfig string
}{
{
proxyName: "normal",
portName: port.GenName("Normal"),
},
{
proxyName: "with-encryption",
portName: port.GenName("WithEncryption"),
extraConfig: "transport.useEncryption = true",
},
{
proxyName: "with-compression",
portName: port.GenName("WithCompression"),
extraConfig: "transport.useCompression = true",
},
{
proxyName: "with-encryption-and-compression",
portName: port.GenName("WithEncryptionAndCompression"),
extraConfig: `
transport.useEncryption = true
transport.useCompression = true
`,
},
}
// build all client config
for _, test := range tests {
clientConf += getProxyConf(test.proxyName, test.portName, test.extraConfig) + "\n"
}
// run frps and frpc
f.RunProcesses([]string{serverConf}, []string{clientConf})
for _, test := range tests {
framework.NewRequestExpect(f).Port(f.PortByName(test.portName)).Ensure()
}
})
})
ginkgo.It("http_proxy", func() {
serverConf := consts.DefaultServerConfig
clientConf := consts.DefaultClientConfig
remotePort := f.AllocPort()
clientConf += fmt.Sprintf(`
[[proxies]]
name = "tcp"
type = "tcp"
remotePort = %d
[proxies.plugin]
type = "http_proxy"
httpUser = "abc"
httpPassword = "123"
`, remotePort)
f.RunProcesses([]string{serverConf}, []string{clientConf})
// http proxy, no auth info
framework.NewRequestExpect(f).PortName(framework.HTTPSimpleServerPort).RequestModify(func(r *request.Request) {
r.HTTP().Proxy("http://127.0.0.1:" + strconv.Itoa(remotePort))
}).Ensure(framework.ExpectResponseCode(407))
// http proxy, correct auth
framework.NewRequestExpect(f).PortName(framework.HTTPSimpleServerPort).RequestModify(func(r *request.Request) {
r.HTTP().Proxy("http://abc:123@127.0.0.1:" + strconv.Itoa(remotePort))
}).Ensure()
// connect TCP server by CONNECT method
framework.NewRequestExpect(f).PortName(framework.TCPEchoServerPort).RequestModify(func(r *request.Request) {
r.TCP().Proxy("http://abc:123@127.0.0.1:" + strconv.Itoa(remotePort))
})
})
ginkgo.It("socks5 proxy", func() {
serverConf := consts.DefaultServerConfig
clientConf := consts.DefaultClientConfig
remotePort := f.AllocPort()
clientConf += fmt.Sprintf(`
[[proxies]]
name = "tcp"
type = "tcp"
remotePort = %d
[proxies.plugin]
type = "socks5"
username = "abc"
password = "123"
`, remotePort)
f.RunProcesses([]string{serverConf}, []string{clientConf})
// http proxy, no auth info
framework.NewRequestExpect(f).PortName(framework.TCPEchoServerPort).RequestModify(func(r *request.Request) {
r.TCP().Proxy("socks5://127.0.0.1:" + strconv.Itoa(remotePort))
}).ExpectError(true).Ensure()
// http proxy, correct auth
framework.NewRequestExpect(f).PortName(framework.TCPEchoServerPort).RequestModify(func(r *request.Request) {
r.TCP().Proxy("socks5://abc:123@127.0.0.1:" + strconv.Itoa(remotePort))
}).Ensure()
})
ginkgo.It("static_file", func() {
vhostPort := f.AllocPort()
serverConf := consts.DefaultServerConfig + fmt.Sprintf(`
vhostHTTPPort = %d
`, vhostPort)
clientConf := consts.DefaultClientConfig
remotePort := f.AllocPort()
f.WriteTempFile("test_static_file", "foo")
clientConf += fmt.Sprintf(`
[[proxies]]
name = "tcp"
type = "tcp"
remotePort = %d
[proxies.plugin]
type = "static_file"
localPath = "%s"
[[proxies]]
name = "http"
type = "http"
customDomains = ["example.com"]
[proxies.plugin]
type = "static_file"
localPath = "%s"
[[proxies]]
name = "http-with-auth"
type = "http"
customDomains = ["other.example.com"]
[proxies.plugin]
type = "static_file"
localPath = "%s"
httpUser = "abc"
httpPassword = "123"
`, remotePort, f.TempDirectory, f.TempDirectory, f.TempDirectory)
f.RunProcesses([]string{serverConf}, []string{clientConf})
// from tcp proxy
framework.NewRequestExpect(f).Request(
framework.NewHTTPRequest().HTTPPath("/test_static_file").Port(remotePort),
).ExpectResp([]byte("foo")).Ensure()
// from http proxy without auth
framework.NewRequestExpect(f).Request(
framework.NewHTTPRequest().HTTPHost("example.com").HTTPPath("/test_static_file").Port(vhostPort),
).ExpectResp([]byte("foo")).Ensure()
// from http proxy with auth
framework.NewRequestExpect(f).Request(
framework.NewHTTPRequest().HTTPHost("other.example.com").HTTPPath("/test_static_file").Port(vhostPort).HTTPAuth("abc", "123"),
).ExpectResp([]byte("foo")).Ensure()
})
ginkgo.It("http2https", func() {
serverConf := consts.DefaultServerConfig
vhostHTTPPort := f.AllocPort()
serverConf += fmt.Sprintf(`
vhostHTTPPort = %d
`, vhostHTTPPort)
localPort := f.AllocPort()
clientConf := consts.DefaultClientConfig + fmt.Sprintf(`
[[proxies]]
name = "http2https"
type = "http"
customDomains = ["example.com"]
[proxies.plugin]
type = "http2https"
localAddr = "127.0.0.1:%d"
`, localPort)
f.RunProcesses([]string{serverConf}, []string{clientConf})
tlsConfig, err := transport.NewServerTLSConfig("", "", "")
framework.ExpectNoError(err)
localServer := httpserver.New(
httpserver.WithBindPort(localPort),
httpserver.WithTLSConfig(tlsConfig),
httpserver.WithResponse([]byte("test")),
)
f.RunServer("", localServer)
framework.NewRequestExpect(f).
Port(vhostHTTPPort).
RequestModify(func(r *request.Request) {
r.HTTP().HTTPHost("example.com")
}).
ExpectResp([]byte("test")).
Ensure()
})
ginkgo.It("https2http", func() {
generator := &cert.SelfSignedCertGenerator{}
artifacts, err := generator.Generate("example.com")
framework.ExpectNoError(err)
crtPath := f.WriteTempFile("server.crt", string(artifacts.Cert))
keyPath := f.WriteTempFile("server.key", string(artifacts.Key))
serverConf := consts.DefaultServerConfig
vhostHTTPSPort := f.AllocPort()
serverConf += fmt.Sprintf(`
vhostHTTPSPort = %d
`, vhostHTTPSPort)
localPort := f.AllocPort()
clientConf := consts.DefaultClientConfig + fmt.Sprintf(`
[[proxies]]
name = "https2http"
type = "https"
customDomains = ["example.com"]
[proxies.plugin]
type = "https2http"
localAddr = "127.0.0.1:%d"
crtPath = "%s"
keyPath = "%s"
`, localPort, crtPath, keyPath)
f.RunProcesses([]string{serverConf}, []string{clientConf})
localServer := httpserver.New(
httpserver.WithBindPort(localPort),
httpserver.WithResponse([]byte("test")),
)
f.RunServer("", localServer)
framework.NewRequestExpect(f).
Port(vhostHTTPSPort).
RequestModify(func(r *request.Request) {
r.HTTPS().HTTPHost("example.com").TLSConfig(&tls.Config{
ServerName: "example.com",
InsecureSkipVerify: true,
})
}).
ExpectResp([]byte("test")).
Ensure()
})
ginkgo.It("https2https", func() {
generator := &cert.SelfSignedCertGenerator{}
artifacts, err := generator.Generate("example.com")
framework.ExpectNoError(err)
crtPath := f.WriteTempFile("server.crt", string(artifacts.Cert))
keyPath := f.WriteTempFile("server.key", string(artifacts.Key))
serverConf := consts.DefaultServerConfig
vhostHTTPSPort := f.AllocPort()
serverConf += fmt.Sprintf(`
vhostHTTPSPort = %d
`, vhostHTTPSPort)
localPort := f.AllocPort()
clientConf := consts.DefaultClientConfig + fmt.Sprintf(`
[[proxies]]
name = "https2https"
type = "https"
customDomains = ["example.com"]
[proxies.plugin]
type = "https2https"
localAddr = "127.0.0.1:%d"
crtPath = "%s"
keyPath = "%s"
`, localPort, crtPath, keyPath)
f.RunProcesses([]string{serverConf}, []string{clientConf})
tlsConfig, err := transport.NewServerTLSConfig("", "", "")
framework.ExpectNoError(err)
localServer := httpserver.New(
httpserver.WithBindPort(localPort),
httpserver.WithResponse([]byte("test")),
httpserver.WithTLSConfig(tlsConfig),
)
f.RunServer("", localServer)
framework.NewRequestExpect(f).
Port(vhostHTTPSPort).
RequestModify(func(r *request.Request) {
r.HTTPS().HTTPHost("example.com").TLSConfig(&tls.Config{
ServerName: "example.com",
InsecureSkipVerify: true,
})
}).
ExpectResp([]byte("test")).
Ensure()
})
ginkgo.Describe("http2http", func() {
ginkgo.It("host header rewrite", func() {
serverConf := consts.DefaultServerConfig
localPort := f.AllocPort()
remotePort := f.AllocPort()
clientConf := consts.DefaultClientConfig + fmt.Sprintf(`
[[proxies]]
name = "http2http"
type = "tcp"
remotePort = %d
[proxies.plugin]
type = "http2http"
localAddr = "127.0.0.1:%d"
hostHeaderRewrite = "rewrite.test.com"
`, remotePort, localPort)
f.RunProcesses([]string{serverConf}, []string{clientConf})
localServer := httpserver.New(
httpserver.WithBindPort(localPort),
httpserver.WithHandler(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
_, _ = w.Write([]byte(req.Host))
})),
)
f.RunServer("", localServer)
framework.NewRequestExpect(f).
Port(remotePort).
RequestModify(func(r *request.Request) {
r.HTTP().HTTPHost("example.com")
}).
ExpectResp([]byte("rewrite.test.com")).
Ensure()
})
ginkgo.It("set request header", func() {
serverConf := consts.DefaultServerConfig
localPort := f.AllocPort()
remotePort := f.AllocPort()
clientConf := consts.DefaultClientConfig + fmt.Sprintf(`
[[proxies]]
name = "http2http"
type = "tcp"
remotePort = %d
[proxies.plugin]
type = "http2http"
localAddr = "127.0.0.1:%d"
requestHeaders.set.x-from-where = "frp"
`, remotePort, localPort)
f.RunProcesses([]string{serverConf}, []string{clientConf})
localServer := httpserver.New(
httpserver.WithBindPort(localPort),
httpserver.WithHandler(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
_, _ = w.Write([]byte(req.Header.Get("x-from-where")))
})),
)
f.RunServer("", localServer)
framework.NewRequestExpect(f).
Port(remotePort).
RequestModify(func(r *request.Request) {
r.HTTP().HTTPHost("example.com")
}).
ExpectResp([]byte("frp")).
Ensure()
})
})
ginkgo.It("tls2raw", func() {
generator := &cert.SelfSignedCertGenerator{}
artifacts, err := generator.Generate("example.com")
framework.ExpectNoError(err)
crtPath := f.WriteTempFile("tls2raw_server.crt", string(artifacts.Cert))
keyPath := f.WriteTempFile("tls2raw_server.key", string(artifacts.Key))
serverConf := consts.DefaultServerConfig
vhostHTTPSPort := f.AllocPort()
serverConf += fmt.Sprintf(`
vhostHTTPSPort = %d
`, vhostHTTPSPort)
localPort := f.AllocPort()
clientConf := consts.DefaultClientConfig + fmt.Sprintf(`
[[proxies]]
name = "tls2raw-test"
type = "https"
customDomains = ["example.com"]
[proxies.plugin]
type = "tls2raw"
localAddr = "127.0.0.1:%d"
crtPath = "%s"
keyPath = "%s"
`, localPort, crtPath, keyPath)
f.RunProcesses([]string{serverConf}, []string{clientConf})
localServer := httpserver.New(
httpserver.WithBindPort(localPort),
httpserver.WithResponse([]byte("test")),
)
f.RunServer("", localServer)
framework.NewRequestExpect(f).
Port(vhostHTTPSPort).
RequestModify(func(r *request.Request) {
r.HTTPS().HTTPHost("example.com").TLSConfig(&tls.Config{
ServerName: "example.com",
InsecureSkipVerify: true,
})
}).
ExpectResp([]byte("test")).
Ensure()
})
})
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/v1/plugin/server.go | test/e2e/v1/plugin/server.go | package plugin
import (
"fmt"
"time"
"github.com/onsi/ginkgo/v2"
plugin "github.com/fatedier/frp/pkg/plugin/server"
"github.com/fatedier/frp/pkg/transport"
"github.com/fatedier/frp/test/e2e/framework"
"github.com/fatedier/frp/test/e2e/framework/consts"
pluginpkg "github.com/fatedier/frp/test/e2e/pkg/plugin"
)
var _ = ginkgo.Describe("[Feature: Server-Plugins]", func() {
f := framework.NewDefaultFramework()
ginkgo.Describe("Login", func() {
newFunc := func() *plugin.Request {
var r plugin.Request
r.Content = &plugin.LoginContent{}
return &r
}
ginkgo.It("Auth for custom meta token", func() {
localPort := f.AllocPort()
clientAddressGot := false
handler := func(req *plugin.Request) *plugin.Response {
var ret plugin.Response
content := req.Content.(*plugin.LoginContent)
if content.ClientAddress != "" {
clientAddressGot = true
}
if content.Metas["token"] == "123" {
ret.Unchange = true
} else {
ret.Reject = true
ret.RejectReason = "invalid token"
}
return &ret
}
pluginServer := pluginpkg.NewHTTPPluginServer(localPort, newFunc, handler, nil)
f.RunServer("", pluginServer)
serverConf := consts.DefaultServerConfig + fmt.Sprintf(`
[[httpPlugins]]
name = "user-manager"
addr = "127.0.0.1:%d"
path = "/handler"
ops = ["Login"]
`, localPort)
clientConf := consts.DefaultClientConfig
remotePort := f.AllocPort()
clientConf += fmt.Sprintf(`
metadatas.token = "123"
[[proxies]]
name = "tcp"
type = "tcp"
localPort = {{ .%s }}
remotePort = %d
`, framework.TCPEchoServerPort, remotePort)
remotePort2 := f.AllocPort()
invalidTokenClientConf := consts.DefaultClientConfig + fmt.Sprintf(`
[[proxies]]
name = "tcp2"
type = "tcp"
localPort = {{ .%s }}
remotePort = %d
`, framework.TCPEchoServerPort, remotePort2)
f.RunProcesses([]string{serverConf}, []string{clientConf, invalidTokenClientConf})
framework.NewRequestExpect(f).Port(remotePort).Ensure()
framework.NewRequestExpect(f).Port(remotePort2).ExpectError(true).Ensure()
framework.ExpectTrue(clientAddressGot)
})
})
ginkgo.Describe("NewProxy", func() {
newFunc := func() *plugin.Request {
var r plugin.Request
r.Content = &plugin.NewProxyContent{}
return &r
}
ginkgo.It("Validate Info", func() {
localPort := f.AllocPort()
handler := func(req *plugin.Request) *plugin.Response {
var ret plugin.Response
content := req.Content.(*plugin.NewProxyContent)
if content.ProxyName == "tcp" {
ret.Unchange = true
} else {
ret.Reject = true
}
return &ret
}
pluginServer := pluginpkg.NewHTTPPluginServer(localPort, newFunc, handler, nil)
f.RunServer("", pluginServer)
serverConf := consts.DefaultServerConfig + fmt.Sprintf(`
[[httpPlugins]]
name = "test"
addr = "127.0.0.1:%d"
path = "/handler"
ops = ["NewProxy"]
`, localPort)
clientConf := consts.DefaultClientConfig
remotePort := f.AllocPort()
clientConf += fmt.Sprintf(`
[[proxies]]
name = "tcp"
type = "tcp"
localPort = {{ .%s }}
remotePort = %d
`, framework.TCPEchoServerPort, remotePort)
f.RunProcesses([]string{serverConf}, []string{clientConf})
framework.NewRequestExpect(f).Port(remotePort).Ensure()
})
ginkgo.It("Modify RemotePort", func() {
localPort := f.AllocPort()
remotePort := f.AllocPort()
handler := func(req *plugin.Request) *plugin.Response {
var ret plugin.Response
content := req.Content.(*plugin.NewProxyContent)
content.RemotePort = remotePort
ret.Content = content
return &ret
}
pluginServer := pluginpkg.NewHTTPPluginServer(localPort, newFunc, handler, nil)
f.RunServer("", pluginServer)
serverConf := consts.DefaultServerConfig + fmt.Sprintf(`
[[httpPlugins]]
name = "test"
addr = "127.0.0.1:%d"
path = "/handler"
ops = ["NewProxy"]
`, localPort)
clientConf := consts.DefaultClientConfig
clientConf += fmt.Sprintf(`
[[proxies]]
name = "tcp"
type = "tcp"
localPort = {{ .%s }}
remotePort = 0
`, framework.TCPEchoServerPort)
f.RunProcesses([]string{serverConf}, []string{clientConf})
framework.NewRequestExpect(f).Port(remotePort).Ensure()
})
})
ginkgo.Describe("CloseProxy", func() {
newFunc := func() *plugin.Request {
var r plugin.Request
r.Content = &plugin.CloseProxyContent{}
return &r
}
ginkgo.It("Validate Info", func() {
localPort := f.AllocPort()
var recordProxyName string
handler := func(req *plugin.Request) *plugin.Response {
var ret plugin.Response
content := req.Content.(*plugin.CloseProxyContent)
recordProxyName = content.ProxyName
return &ret
}
pluginServer := pluginpkg.NewHTTPPluginServer(localPort, newFunc, handler, nil)
f.RunServer("", pluginServer)
serverConf := consts.DefaultServerConfig + fmt.Sprintf(`
[[httpPlugins]]
name = "test"
addr = "127.0.0.1:%d"
path = "/handler"
ops = ["CloseProxy"]
`, localPort)
clientConf := consts.DefaultClientConfig
remotePort := f.AllocPort()
clientConf += fmt.Sprintf(`
[[proxies]]
name = "tcp"
type = "tcp"
localPort = {{ .%s }}
remotePort = %d
`, framework.TCPEchoServerPort, remotePort)
_, clients := f.RunProcesses([]string{serverConf}, []string{clientConf})
framework.NewRequestExpect(f).Port(remotePort).Ensure()
for _, c := range clients {
_ = c.Stop()
}
time.Sleep(1 * time.Second)
framework.ExpectEqual(recordProxyName, "tcp")
})
})
ginkgo.Describe("Ping", func() {
newFunc := func() *plugin.Request {
var r plugin.Request
r.Content = &plugin.PingContent{}
return &r
}
ginkgo.It("Validate Info", func() {
localPort := f.AllocPort()
var record string
handler := func(req *plugin.Request) *plugin.Response {
var ret plugin.Response
content := req.Content.(*plugin.PingContent)
record = content.PrivilegeKey
ret.Unchange = true
return &ret
}
pluginServer := pluginpkg.NewHTTPPluginServer(localPort, newFunc, handler, nil)
f.RunServer("", pluginServer)
serverConf := consts.DefaultServerConfig + fmt.Sprintf(`
[[httpPlugins]]
name = "test"
addr = "127.0.0.1:%d"
path = "/handler"
ops = ["Ping"]
`, localPort)
remotePort := f.AllocPort()
clientConf := consts.DefaultClientConfig
clientConf += fmt.Sprintf(`
transport.heartbeatInterval = 1
auth.additionalScopes = ["HeartBeats"]
[[proxies]]
name = "tcp"
type = "tcp"
localPort = {{ .%s }}
remotePort = %d
`, framework.TCPEchoServerPort, remotePort)
f.RunProcesses([]string{serverConf}, []string{clientConf})
framework.NewRequestExpect(f).Port(remotePort).Ensure()
time.Sleep(3 * time.Second)
framework.ExpectNotEqual("", record)
})
})
ginkgo.Describe("NewWorkConn", func() {
newFunc := func() *plugin.Request {
var r plugin.Request
r.Content = &plugin.NewWorkConnContent{}
return &r
}
ginkgo.It("Validate Info", func() {
localPort := f.AllocPort()
var record string
handler := func(req *plugin.Request) *plugin.Response {
var ret plugin.Response
content := req.Content.(*plugin.NewWorkConnContent)
record = content.RunID
ret.Unchange = true
return &ret
}
pluginServer := pluginpkg.NewHTTPPluginServer(localPort, newFunc, handler, nil)
f.RunServer("", pluginServer)
serverConf := consts.DefaultServerConfig + fmt.Sprintf(`
[[httpPlugins]]
name = "test"
addr = "127.0.0.1:%d"
path = "/handler"
ops = ["NewWorkConn"]
`, localPort)
remotePort := f.AllocPort()
clientConf := consts.DefaultClientConfig
clientConf += fmt.Sprintf(`
[[proxies]]
name = "tcp"
type = "tcp"
localPort = {{ .%s }}
remotePort = %d
`, framework.TCPEchoServerPort, remotePort)
f.RunProcesses([]string{serverConf}, []string{clientConf})
framework.NewRequestExpect(f).Port(remotePort).Ensure()
framework.ExpectNotEqual("", record)
})
})
ginkgo.Describe("NewUserConn", func() {
newFunc := func() *plugin.Request {
var r plugin.Request
r.Content = &plugin.NewUserConnContent{}
return &r
}
ginkgo.It("Validate Info", func() {
localPort := f.AllocPort()
var record string
handler := func(req *plugin.Request) *plugin.Response {
var ret plugin.Response
content := req.Content.(*plugin.NewUserConnContent)
record = content.RemoteAddr
ret.Unchange = true
return &ret
}
pluginServer := pluginpkg.NewHTTPPluginServer(localPort, newFunc, handler, nil)
f.RunServer("", pluginServer)
serverConf := consts.DefaultServerConfig + fmt.Sprintf(`
[[httpPlugins]]
name = "test"
addr = "127.0.0.1:%d"
path = "/handler"
ops = ["NewUserConn"]
`, localPort)
remotePort := f.AllocPort()
clientConf := consts.DefaultClientConfig
clientConf += fmt.Sprintf(`
[[proxies]]
name = "tcp"
type = "tcp"
localPort = {{ .%s }}
remotePort = %d
`, framework.TCPEchoServerPort, remotePort)
f.RunProcesses([]string{serverConf}, []string{clientConf})
framework.NewRequestExpect(f).Port(remotePort).Ensure()
framework.ExpectNotEqual("", record)
})
})
ginkgo.Describe("HTTPS Protocol", func() {
newFunc := func() *plugin.Request {
var r plugin.Request
r.Content = &plugin.NewUserConnContent{}
return &r
}
ginkgo.It("Validate Login Info, disable tls verify", func() {
localPort := f.AllocPort()
var record string
handler := func(req *plugin.Request) *plugin.Response {
var ret plugin.Response
content := req.Content.(*plugin.NewUserConnContent)
record = content.RemoteAddr
ret.Unchange = true
return &ret
}
tlsConfig, err := transport.NewServerTLSConfig("", "", "")
framework.ExpectNoError(err)
pluginServer := pluginpkg.NewHTTPPluginServer(localPort, newFunc, handler, tlsConfig)
f.RunServer("", pluginServer)
serverConf := consts.DefaultServerConfig + fmt.Sprintf(`
[[httpPlugins]]
name = "test"
addr = "https://127.0.0.1:%d"
path = "/handler"
ops = ["NewUserConn"]
`, localPort)
remotePort := f.AllocPort()
clientConf := consts.DefaultClientConfig
clientConf += fmt.Sprintf(`
[[proxies]]
name = "tcp"
type = "tcp"
localPort = {{ .%s }}
remotePort = %d
`, framework.TCPEchoServerPort, remotePort)
f.RunProcesses([]string{serverConf}, []string{clientConf})
framework.NewRequestExpect(f).Port(remotePort).Ensure()
framework.ExpectNotEqual("", record)
})
})
})
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/v1/basic/basic.go | test/e2e/v1/basic/basic.go | package basic
import (
"crypto/tls"
"fmt"
"strings"
"time"
"github.com/onsi/ginkgo/v2"
"github.com/fatedier/frp/pkg/transport"
"github.com/fatedier/frp/test/e2e/framework"
"github.com/fatedier/frp/test/e2e/framework/consts"
"github.com/fatedier/frp/test/e2e/mock/server/httpserver"
"github.com/fatedier/frp/test/e2e/mock/server/streamserver"
"github.com/fatedier/frp/test/e2e/pkg/port"
"github.com/fatedier/frp/test/e2e/pkg/request"
)
var _ = ginkgo.Describe("[Feature: Basic]", func() {
f := framework.NewDefaultFramework()
ginkgo.Describe("TCP && UDP", func() {
types := []string{"tcp", "udp"}
for _, t := range types {
proxyType := t
ginkgo.It(fmt.Sprintf("Expose a %s echo server", strings.ToUpper(proxyType)), func() {
serverConf := consts.DefaultServerConfig
clientConf := consts.DefaultClientConfig
localPortName := ""
protocol := "tcp"
switch proxyType {
case "tcp":
localPortName = framework.TCPEchoServerPort
protocol = "tcp"
case "udp":
localPortName = framework.UDPEchoServerPort
protocol = "udp"
}
getProxyConf := func(proxyName string, portName string, extra string) string {
return fmt.Sprintf(`
[[proxies]]
name = "%s"
type = "%s"
localPort = {{ .%s }}
remotePort = {{ .%s }}
`+extra, proxyName, proxyType, localPortName, portName)
}
tests := []struct {
proxyName string
portName string
extraConfig string
}{
{
proxyName: "normal",
portName: port.GenName("Normal"),
},
{
proxyName: "with-encryption",
portName: port.GenName("WithEncryption"),
extraConfig: "transport.useEncryption = true",
},
{
proxyName: "with-compression",
portName: port.GenName("WithCompression"),
extraConfig: "transport.useCompression = true",
},
{
proxyName: "with-encryption-and-compression",
portName: port.GenName("WithEncryptionAndCompression"),
extraConfig: `
transport.useEncryption = true
transport.useCompression = true
`,
},
}
// build all client config
for _, test := range tests {
clientConf += getProxyConf(test.proxyName, test.portName, test.extraConfig) + "\n"
}
// run frps and frpc
f.RunProcesses([]string{serverConf}, []string{clientConf})
for _, test := range tests {
framework.NewRequestExpect(f).
Protocol(protocol).
PortName(test.portName).
Explain(test.proxyName).
Ensure()
}
})
}
})
ginkgo.Describe("HTTP", func() {
ginkgo.It("proxy to HTTP server", func() {
serverConf := consts.DefaultServerConfig
vhostHTTPPort := f.AllocPort()
serverConf += fmt.Sprintf(`
vhostHTTPPort = %d
`, vhostHTTPPort)
clientConf := consts.DefaultClientConfig
getProxyConf := func(proxyName string, customDomains string, extra string) string {
return fmt.Sprintf(`
[[proxies]]
name = "%s"
type = "http"
localPort = {{ .%s }}
customDomains = %s
`+extra, proxyName, framework.HTTPSimpleServerPort, customDomains)
}
tests := []struct {
proxyName string
customDomains string
extraConfig string
}{
{
proxyName: "normal",
},
{
proxyName: "with-encryption",
extraConfig: "transport.useEncryption = true",
},
{
proxyName: "with-compression",
extraConfig: "transport.useCompression = true",
},
{
proxyName: "with-encryption-and-compression",
extraConfig: `
transport.useEncryption = true
transport.useCompression = true
`,
},
{
proxyName: "multiple-custom-domains",
customDomains: `["a.example.com", "b.example.com"]`,
},
}
// build all client config
for i, test := range tests {
if tests[i].customDomains == "" {
tests[i].customDomains = fmt.Sprintf(`["%s"]`, test.proxyName+".example.com")
}
clientConf += getProxyConf(test.proxyName, tests[i].customDomains, test.extraConfig) + "\n"
}
// run frps and frpc
f.RunProcesses([]string{serverConf}, []string{clientConf})
for _, test := range tests {
for _, domain := range strings.Split(test.customDomains, ",") {
domain = strings.TrimSpace(domain)
domain = strings.TrimLeft(domain, "[\"")
domain = strings.TrimRight(domain, "]\"")
framework.NewRequestExpect(f).
Explain(test.proxyName + "-" + domain).
Port(vhostHTTPPort).
RequestModify(func(r *request.Request) {
r.HTTP().HTTPHost(domain)
}).
Ensure()
}
}
// not exist host
framework.NewRequestExpect(f).
Explain("not exist host").
Port(vhostHTTPPort).
RequestModify(func(r *request.Request) {
r.HTTP().HTTPHost("not-exist.example.com")
}).
Ensure(framework.ExpectResponseCode(404))
})
})
ginkgo.Describe("HTTPS", func() {
ginkgo.It("proxy to HTTPS server", func() {
serverConf := consts.DefaultServerConfig
vhostHTTPSPort := f.AllocPort()
serverConf += fmt.Sprintf(`
vhostHTTPSPort = %d
`, vhostHTTPSPort)
localPort := f.AllocPort()
clientConf := consts.DefaultClientConfig
getProxyConf := func(proxyName string, customDomains string, extra string) string {
return fmt.Sprintf(`
[[proxies]]
name = "%s"
type = "https"
localPort = %d
customDomains = %s
`+extra, proxyName, localPort, customDomains)
}
tests := []struct {
proxyName string
customDomains string
extraConfig string
}{
{
proxyName: "normal",
},
{
proxyName: "with-encryption",
extraConfig: "transport.useEncryption = true",
},
{
proxyName: "with-compression",
extraConfig: "transport.useCompression = true",
},
{
proxyName: "with-encryption-and-compression",
extraConfig: `
transport.useEncryption = true
transport.useCompression = true
`,
},
{
proxyName: "multiple-custom-domains",
customDomains: `["a.example.com", "b.example.com"]`,
},
}
// build all client config
for i, test := range tests {
if tests[i].customDomains == "" {
tests[i].customDomains = fmt.Sprintf(`["%s"]`, test.proxyName+".example.com")
}
clientConf += getProxyConf(test.proxyName, tests[i].customDomains, test.extraConfig) + "\n"
}
// run frps and frpc
f.RunProcesses([]string{serverConf}, []string{clientConf})
tlsConfig, err := transport.NewServerTLSConfig("", "", "")
framework.ExpectNoError(err)
localServer := httpserver.New(
httpserver.WithBindPort(localPort),
httpserver.WithTLSConfig(tlsConfig),
httpserver.WithResponse([]byte("test")),
)
f.RunServer("", localServer)
for _, test := range tests {
for _, domain := range strings.Split(test.customDomains, ",") {
domain = strings.TrimSpace(domain)
domain = strings.TrimLeft(domain, "[\"")
domain = strings.TrimRight(domain, "]\"")
framework.NewRequestExpect(f).
Explain(test.proxyName + "-" + domain).
Port(vhostHTTPSPort).
RequestModify(func(r *request.Request) {
r.HTTPS().HTTPHost(domain).TLSConfig(&tls.Config{
ServerName: domain,
InsecureSkipVerify: true,
})
}).
ExpectResp([]byte("test")).
Ensure()
}
}
// not exist host
notExistDomain := "not-exist.example.com"
framework.NewRequestExpect(f).
Explain("not exist host").
Port(vhostHTTPSPort).
RequestModify(func(r *request.Request) {
r.HTTPS().HTTPHost(notExistDomain).TLSConfig(&tls.Config{
ServerName: notExistDomain,
InsecureSkipVerify: true,
})
}).
ExpectError(true).
Ensure()
})
})
ginkgo.Describe("STCP && SUDP && XTCP", func() {
types := []string{"stcp", "sudp", "xtcp"}
for _, t := range types {
proxyType := t
ginkgo.It(fmt.Sprintf("Expose echo server with %s", strings.ToUpper(proxyType)), func() {
serverConf := consts.DefaultServerConfig
clientServerConf := consts.DefaultClientConfig + "\nuser = \"user1\""
clientVisitorConf := consts.DefaultClientConfig + "\nuser = \"user1\""
clientUser2VisitorConf := consts.DefaultClientConfig + "\nuser = \"user2\""
localPortName := ""
protocol := "tcp"
switch proxyType {
case "stcp":
localPortName = framework.TCPEchoServerPort
protocol = "tcp"
case "sudp":
localPortName = framework.UDPEchoServerPort
protocol = "udp"
case "xtcp":
localPortName = framework.TCPEchoServerPort
protocol = "tcp"
ginkgo.Skip("stun server is not stable")
}
correctSK := "abc"
wrongSK := "123"
getProxyServerConf := func(proxyName string, extra string) string {
return fmt.Sprintf(`
[[proxies]]
name = "%s"
type = "%s"
secretKey = "%s"
localPort = {{ .%s }}
`+extra, proxyName, proxyType, correctSK, localPortName)
}
getProxyVisitorConf := func(proxyName string, portName, visitorSK, extra string) string {
return fmt.Sprintf(`
[[visitors]]
name = "%s"
type = "%s"
serverName = "%s"
secretKey = "%s"
bindPort = {{ .%s }}
`+extra, proxyName, proxyType, proxyName, visitorSK, portName)
}
tests := []struct {
proxyName string
bindPortName string
visitorSK string
commonExtraConfig string
proxyExtraConfig string
visitorExtraConfig string
expectError bool
deployUser2Client bool
// skipXTCP is used to skip xtcp test case
skipXTCP bool
}{
{
proxyName: "normal",
bindPortName: port.GenName("Normal"),
visitorSK: correctSK,
skipXTCP: true,
},
{
proxyName: "with-encryption",
bindPortName: port.GenName("WithEncryption"),
visitorSK: correctSK,
commonExtraConfig: "transport.useEncryption = true",
skipXTCP: true,
},
{
proxyName: "with-compression",
bindPortName: port.GenName("WithCompression"),
visitorSK: correctSK,
commonExtraConfig: "transport.useCompression = true",
skipXTCP: true,
},
{
proxyName: "with-encryption-and-compression",
bindPortName: port.GenName("WithEncryptionAndCompression"),
visitorSK: correctSK,
commonExtraConfig: `
transport.useEncryption = true
transport.useCompression = true
`,
skipXTCP: true,
},
{
proxyName: "with-error-sk",
bindPortName: port.GenName("WithErrorSK"),
visitorSK: wrongSK,
expectError: true,
},
{
proxyName: "allowed-user",
bindPortName: port.GenName("AllowedUser"),
visitorSK: correctSK,
proxyExtraConfig: `allowUsers = ["another", "user2"]`,
visitorExtraConfig: `serverUser = "user1"`,
deployUser2Client: true,
},
{
proxyName: "not-allowed-user",
bindPortName: port.GenName("NotAllowedUser"),
visitorSK: correctSK,
proxyExtraConfig: `allowUsers = ["invalid"]`,
visitorExtraConfig: `serverUser = "user1"`,
expectError: true,
},
{
proxyName: "allow-all",
bindPortName: port.GenName("AllowAll"),
visitorSK: correctSK,
proxyExtraConfig: `allowUsers = ["*"]`,
visitorExtraConfig: `serverUser = "user1"`,
deployUser2Client: true,
},
}
// build all client config
for _, test := range tests {
clientServerConf += getProxyServerConf(test.proxyName, test.commonExtraConfig+"\n"+test.proxyExtraConfig) + "\n"
}
for _, test := range tests {
config := getProxyVisitorConf(
test.proxyName, test.bindPortName, test.visitorSK, test.commonExtraConfig+"\n"+test.visitorExtraConfig,
) + "\n"
if test.deployUser2Client {
clientUser2VisitorConf += config
} else {
clientVisitorConf += config
}
}
// run frps and frpc
f.RunProcesses([]string{serverConf}, []string{clientServerConf, clientVisitorConf, clientUser2VisitorConf})
for _, test := range tests {
timeout := time.Second
if t == "xtcp" {
if test.skipXTCP {
continue
}
timeout = 10 * time.Second
}
framework.NewRequestExpect(f).
RequestModify(func(r *request.Request) {
r.Timeout(timeout)
}).
Protocol(protocol).
PortName(test.bindPortName).
Explain(test.proxyName).
ExpectError(test.expectError).
Ensure()
}
})
}
})
ginkgo.Describe("TCPMUX", func() {
ginkgo.It("Type tcpmux", func() {
serverConf := consts.DefaultServerConfig
clientConf := consts.DefaultClientConfig
tcpmuxHTTPConnectPortName := port.GenName("TCPMUX")
serverConf += fmt.Sprintf(`
tcpmuxHTTPConnectPort = {{ .%s }}
`, tcpmuxHTTPConnectPortName)
getProxyConf := func(proxyName string, extra string) string {
return fmt.Sprintf(`
[[proxies]]
name = "%s"
type = "tcpmux"
multiplexer = "httpconnect"
localPort = {{ .%s }}
customDomains = ["%s"]
`+extra, proxyName, port.GenName(proxyName), proxyName)
}
tests := []struct {
proxyName string
extraConfig string
}{
{
proxyName: "normal",
},
{
proxyName: "with-encryption",
extraConfig: "transport.useEncryption = true",
},
{
proxyName: "with-compression",
extraConfig: "transport.useCompression = true",
},
{
proxyName: "with-encryption-and-compression",
extraConfig: `
transport.useEncryption = true
transport.useCompression = true
`,
},
}
// build all client config
for _, test := range tests {
clientConf += getProxyConf(test.proxyName, test.extraConfig) + "\n"
localServer := streamserver.New(streamserver.TCP, streamserver.WithBindPort(f.AllocPort()), streamserver.WithRespContent([]byte(test.proxyName)))
f.RunServer(port.GenName(test.proxyName), localServer)
}
// run frps and frpc
f.RunProcesses([]string{serverConf}, []string{clientConf})
// Request without HTTP connect should get error
framework.NewRequestExpect(f).
PortName(tcpmuxHTTPConnectPortName).
ExpectError(true).
Explain("request without HTTP connect expect error").
Ensure()
proxyURL := fmt.Sprintf("http://127.0.0.1:%d", f.PortByName(tcpmuxHTTPConnectPortName))
// Request with incorrect connect hostname
framework.NewRequestExpect(f).RequestModify(func(r *request.Request) {
r.Addr("invalid").Proxy(proxyURL)
}).ExpectError(true).Explain("request without HTTP connect expect error").Ensure()
// Request with correct connect hostname
for _, test := range tests {
framework.NewRequestExpect(f).RequestModify(func(r *request.Request) {
r.Addr(test.proxyName).Proxy(proxyURL)
}).ExpectResp([]byte(test.proxyName)).Explain(test.proxyName).Ensure()
}
})
})
})
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/v1/basic/client.go | test/e2e/v1/basic/client.go | package basic
import (
"context"
"fmt"
"strconv"
"strings"
"time"
"github.com/onsi/ginkgo/v2"
"github.com/fatedier/frp/test/e2e/framework"
"github.com/fatedier/frp/test/e2e/framework/consts"
"github.com/fatedier/frp/test/e2e/pkg/request"
)
var _ = ginkgo.Describe("[Feature: ClientManage]", func() {
f := framework.NewDefaultFramework()
ginkgo.It("Update && Reload API", func() {
serverConf := consts.DefaultServerConfig
adminPort := f.AllocPort()
p1Port := f.AllocPort()
p2Port := f.AllocPort()
p3Port := f.AllocPort()
clientConf := consts.DefaultClientConfig + fmt.Sprintf(`
webServer.port = %d
[[proxies]]
name = "p1"
type = "tcp"
localPort = {{ .%s }}
remotePort = %d
[[proxies]]
name = "p2"
type = "tcp"
localPort = {{ .%s }}
remotePort = %d
[[proxies]]
name = "p3"
type = "tcp"
localPort = {{ .%s }}
remotePort = %d
`, adminPort,
framework.TCPEchoServerPort, p1Port,
framework.TCPEchoServerPort, p2Port,
framework.TCPEchoServerPort, p3Port)
f.RunProcesses([]string{serverConf}, []string{clientConf})
framework.NewRequestExpect(f).Port(p1Port).Ensure()
framework.NewRequestExpect(f).Port(p2Port).Ensure()
framework.NewRequestExpect(f).Port(p3Port).Ensure()
client := f.APIClientForFrpc(adminPort)
conf, err := client.GetConfig(context.Background())
framework.ExpectNoError(err)
newP2Port := f.AllocPort()
// change p2 port and remove p3 proxy
newClientConf := strings.ReplaceAll(conf, strconv.Itoa(p2Port), strconv.Itoa(newP2Port))
p3Index := strings.LastIndex(newClientConf, "[[proxies]]")
if p3Index >= 0 {
newClientConf = newClientConf[:p3Index]
}
err = client.UpdateConfig(context.Background(), newClientConf)
framework.ExpectNoError(err)
err = client.Reload(context.Background(), true)
framework.ExpectNoError(err)
time.Sleep(time.Second)
framework.NewRequestExpect(f).Port(p1Port).Explain("p1 port").Ensure()
framework.NewRequestExpect(f).Port(p2Port).Explain("original p2 port").ExpectError(true).Ensure()
framework.NewRequestExpect(f).Port(newP2Port).Explain("new p2 port").Ensure()
framework.NewRequestExpect(f).Port(p3Port).Explain("p3 port").ExpectError(true).Ensure()
})
ginkgo.It("healthz", func() {
serverConf := consts.DefaultServerConfig
dashboardPort := f.AllocPort()
clientConf := consts.DefaultClientConfig + fmt.Sprintf(`
webServer.addr = "0.0.0.0"
webServer.port = %d
webServer.user = "admin"
webServer.password = "admin"
`, dashboardPort)
f.RunProcesses([]string{serverConf}, []string{clientConf})
framework.NewRequestExpect(f).RequestModify(func(r *request.Request) {
r.HTTP().HTTPPath("/healthz")
}).Port(dashboardPort).ExpectResp([]byte("")).Ensure()
framework.NewRequestExpect(f).RequestModify(func(r *request.Request) {
r.HTTP().HTTPPath("/")
}).Port(dashboardPort).
Ensure(framework.ExpectResponseCode(401))
})
ginkgo.It("stop", func() {
serverConf := consts.DefaultServerConfig
adminPort := f.AllocPort()
testPort := f.AllocPort()
clientConf := consts.DefaultClientConfig + fmt.Sprintf(`
webServer.port = %d
[[proxies]]
name = "test"
type = "tcp"
localPort = {{ .%s }}
remotePort = %d
`, adminPort, framework.TCPEchoServerPort, testPort)
f.RunProcesses([]string{serverConf}, []string{clientConf})
framework.NewRequestExpect(f).Port(testPort).Ensure()
client := f.APIClientForFrpc(adminPort)
err := client.Stop(context.Background())
framework.ExpectNoError(err)
time.Sleep(3 * time.Second)
// frpc stopped so the port is not listened, expect error
framework.NewRequestExpect(f).Port(testPort).ExpectError(true).Ensure()
})
})
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/v1/basic/annotations.go | test/e2e/v1/basic/annotations.go | package basic
import (
"fmt"
"io"
"net/http"
"github.com/onsi/ginkgo/v2"
"github.com/tidwall/gjson"
"github.com/fatedier/frp/test/e2e/framework"
"github.com/fatedier/frp/test/e2e/framework/consts"
)
var _ = ginkgo.Describe("[Feature: Annotations]", func() {
f := framework.NewDefaultFramework()
ginkgo.It("Set Proxy Annotations", func() {
webPort := f.AllocPort()
serverConf := consts.DefaultServerConfig + fmt.Sprintf(`
webServer.port = %d
`, webPort)
p1Port := f.AllocPort()
clientConf := consts.DefaultClientConfig + fmt.Sprintf(`
[[proxies]]
name = "p1"
type = "tcp"
localPort = {{ .%s }}
remotePort = %d
[proxies.annotations]
"frp.e2e.test/foo" = "value1"
"frp.e2e.test/bar" = "value2"
`, framework.TCPEchoServerPort, p1Port)
f.RunProcesses([]string{serverConf}, []string{clientConf})
framework.NewRequestExpect(f).Port(p1Port).Ensure()
// check annotations in frps
resp, err := http.Get(fmt.Sprintf("http://127.0.0.1:%d/api/proxy/tcp/%s", webPort, "p1"))
framework.ExpectNoError(err)
framework.ExpectEqual(resp.StatusCode, 200)
defer resp.Body.Close()
content, err := io.ReadAll(resp.Body)
framework.ExpectNoError(err)
annotations := gjson.Get(string(content), "conf.annotations").Map()
framework.ExpectEqual("value1", annotations["frp.e2e.test/foo"].String())
framework.ExpectEqual("value2", annotations["frp.e2e.test/bar"].String())
})
})
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/v1/basic/xtcp.go | test/e2e/v1/basic/xtcp.go | package basic
import (
"fmt"
"time"
"github.com/onsi/ginkgo/v2"
"github.com/fatedier/frp/test/e2e/framework"
"github.com/fatedier/frp/test/e2e/framework/consts"
"github.com/fatedier/frp/test/e2e/pkg/port"
"github.com/fatedier/frp/test/e2e/pkg/request"
)
var _ = ginkgo.Describe("[Feature: XTCP]", func() {
f := framework.NewDefaultFramework()
ginkgo.It("Fallback To STCP", func() {
serverConf := consts.DefaultServerConfig
clientConf := consts.DefaultClientConfig
bindPortName := port.GenName("XTCP")
clientConf += fmt.Sprintf(`
[[proxies]]
name = "foo"
type = "stcp"
localPort = {{ .%s }}
[[visitors]]
name = "foo-visitor"
type = "stcp"
serverName = "foo"
bindPort = -1
[[visitors]]
name = "bar-visitor"
type = "xtcp"
serverName = "bar"
bindPort = {{ .%s }}
keepTunnelOpen = true
fallbackTo = "foo-visitor"
fallbackTimeoutMs = 200
`, framework.TCPEchoServerPort, bindPortName)
f.RunProcesses([]string{serverConf}, []string{clientConf})
framework.NewRequestExpect(f).
RequestModify(func(r *request.Request) {
r.Timeout(time.Second)
}).
PortName(bindPortName).
Ensure()
})
})
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/v1/basic/config.go | test/e2e/v1/basic/config.go | package basic
import (
"context"
"fmt"
"github.com/onsi/ginkgo/v2"
"github.com/fatedier/frp/test/e2e/framework"
"github.com/fatedier/frp/test/e2e/framework/consts"
"github.com/fatedier/frp/test/e2e/pkg/port"
)
var _ = ginkgo.Describe("[Feature: Config]", func() {
f := framework.NewDefaultFramework()
ginkgo.Describe("Template", func() {
ginkgo.It("render by env", func() {
serverConf := consts.DefaultServerConfig
clientConf := consts.DefaultClientConfig
portName := port.GenName("TCP")
serverConf += fmt.Sprintf(`
auth.token = "{{ %s{{ .Envs.FRP_TOKEN }}%s }}"
`, "`", "`")
clientConf += fmt.Sprintf(`
auth.token = "{{ %s{{ .Envs.FRP_TOKEN }}%s }}"
[[proxies]]
name = "tcp"
type = "tcp"
localPort = {{ .%s }}
remotePort = {{ .%s }}
`, "`", "`", framework.TCPEchoServerPort, portName)
f.SetEnvs([]string{"FRP_TOKEN=123"})
f.RunProcesses([]string{serverConf}, []string{clientConf})
framework.NewRequestExpect(f).PortName(portName).Ensure()
})
ginkgo.It("Range ports mapping", func() {
serverConf := consts.DefaultServerConfig
clientConf := consts.DefaultClientConfig
adminPort := f.AllocPort()
localPortsRange := "13010-13012,13014"
remotePortsRange := "23010-23012,23014"
escapeTemplate := func(s string) string {
return "{{ `" + s + "` }}"
}
clientConf += fmt.Sprintf(`
webServer.port = %d
%s
[[proxies]]
name = "tcp-%s"
type = "tcp"
localPort = %s
remotePort = %s
%s
`, adminPort,
escapeTemplate(fmt.Sprintf(`{{- range $_, $v := parseNumberRangePair "%s" "%s" }}`, localPortsRange, remotePortsRange)),
escapeTemplate("{{ $v.First }}"),
escapeTemplate("{{ $v.First }}"),
escapeTemplate("{{ $v.Second }}"),
escapeTemplate("{{- end }}"),
)
f.RunProcesses([]string{serverConf}, []string{clientConf})
client := f.APIClientForFrpc(adminPort)
checkProxyFn := func(name string, localPort, remotePort int) {
status, err := client.GetProxyStatus(context.Background(), name)
framework.ExpectNoError(err)
framework.ExpectContainSubstring(status.LocalAddr, fmt.Sprintf(":%d", localPort))
framework.ExpectContainSubstring(status.RemoteAddr, fmt.Sprintf(":%d", remotePort))
}
checkProxyFn("tcp-13010", 13010, 23010)
checkProxyFn("tcp-13011", 13011, 23011)
checkProxyFn("tcp-13012", 13012, 23012)
checkProxyFn("tcp-13014", 13014, 23014)
})
})
ginkgo.Describe("Includes", func() {
ginkgo.It("split tcp proxies into different files", func() {
serverPort := f.AllocPort()
serverConfigPath := f.GenerateConfigFile(fmt.Sprintf(`
bindAddr = "0.0.0.0"
bindPort = %d
`, serverPort))
remotePort := f.AllocPort()
proxyConfigPath := f.GenerateConfigFile(fmt.Sprintf(`
[[proxies]]
name = "tcp"
type = "tcp"
localPort = %d
remotePort = %d
`, f.PortByName(framework.TCPEchoServerPort), remotePort))
remotePort2 := f.AllocPort()
proxyConfigPath2 := f.GenerateConfigFile(fmt.Sprintf(`
[[proxies]]
name = "tcp2"
type = "tcp"
localPort = %d
remotePort = %d
`, f.PortByName(framework.TCPEchoServerPort), remotePort2))
clientConfigPath := f.GenerateConfigFile(fmt.Sprintf(`
serverPort = %d
includes = ["%s","%s"]
`, serverPort, proxyConfigPath, proxyConfigPath2))
_, _, err := f.RunFrps("-c", serverConfigPath)
framework.ExpectNoError(err)
_, _, err = f.RunFrpc("-c", clientConfigPath)
framework.ExpectNoError(err)
framework.NewRequestExpect(f).Port(remotePort).Ensure()
framework.NewRequestExpect(f).Port(remotePort2).Ensure()
})
})
ginkgo.Describe("Support Formats", func() {
ginkgo.It("YAML", func() {
serverConf := fmt.Sprintf(`
bindPort: {{ .%s }}
log:
level: trace
`, port.GenName("Server"))
remotePort := f.AllocPort()
clientConf := fmt.Sprintf(`
serverPort: {{ .%s }}
log:
level: trace
proxies:
- name: tcp
type: tcp
localPort: {{ .%s }}
remotePort: %d
`, port.GenName("Server"), framework.TCPEchoServerPort, remotePort)
f.RunProcesses([]string{serverConf}, []string{clientConf})
framework.NewRequestExpect(f).Port(remotePort).Ensure()
})
ginkgo.It("JSON", func() {
serverConf := fmt.Sprintf(`{"bindPort": {{ .%s }}, "log": {"level": "trace"}}`, port.GenName("Server"))
remotePort := f.AllocPort()
clientConf := fmt.Sprintf(`{"serverPort": {{ .%s }}, "log": {"level": "trace"},
"proxies": [{"name": "tcp", "type": "tcp", "localPort": {{ .%s }}, "remotePort": %d}]}`,
port.GenName("Server"), framework.TCPEchoServerPort, remotePort)
f.RunProcesses([]string{serverConf}, []string{clientConf})
framework.NewRequestExpect(f).Port(remotePort).Ensure()
})
})
})
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/v1/basic/token_source.go | test/e2e/v1/basic/token_source.go | // Copyright 2025 The frp Authors
//
// 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 basic
import (
"fmt"
"os"
"path/filepath"
"github.com/onsi/ginkgo/v2"
"github.com/fatedier/frp/test/e2e/framework"
"github.com/fatedier/frp/test/e2e/framework/consts"
"github.com/fatedier/frp/test/e2e/pkg/port"
)
var _ = ginkgo.Describe("[Feature: TokenSource]", func() {
f := framework.NewDefaultFramework()
createExecTokenScript := func(name string) string {
scriptPath := filepath.Join(f.TempDirectory, name)
scriptContent := `#!/bin/sh
printf '%s\n' "$1"
`
err := os.WriteFile(scriptPath, []byte(scriptContent), 0o600)
framework.ExpectNoError(err)
err = os.Chmod(scriptPath, 0o700)
framework.ExpectNoError(err)
return scriptPath
}
ginkgo.Describe("File-based token loading", func() {
ginkgo.It("should work with file tokenSource", func() {
// Create a temporary token file
tmpDir := f.TempDirectory
tokenFile := filepath.Join(tmpDir, "test_token")
tokenContent := "test-token-123"
err := os.WriteFile(tokenFile, []byte(tokenContent), 0o600)
framework.ExpectNoError(err)
serverConf := consts.DefaultServerConfig
clientConf := consts.DefaultClientConfig
portName := port.GenName("TCP")
// Server config with tokenSource
serverConf += fmt.Sprintf(`
auth.tokenSource.type = "file"
auth.tokenSource.file.path = "%s"
`, tokenFile)
// Client config with matching token
clientConf += fmt.Sprintf(`
auth.token = "%s"
[[proxies]]
name = "tcp"
type = "tcp"
localPort = {{ .%s }}
remotePort = {{ .%s }}
`, tokenContent, framework.TCPEchoServerPort, portName)
f.RunProcesses([]string{serverConf}, []string{clientConf})
framework.NewRequestExpect(f).PortName(portName).Ensure()
})
ginkgo.It("should work with client tokenSource", func() {
// Create a temporary token file
tmpDir := f.TempDirectory
tokenFile := filepath.Join(tmpDir, "client_token")
tokenContent := "client-token-456"
err := os.WriteFile(tokenFile, []byte(tokenContent), 0o600)
framework.ExpectNoError(err)
serverConf := consts.DefaultServerConfig
clientConf := consts.DefaultClientConfig
portName := port.GenName("TCP")
// Server config with matching token
serverConf += fmt.Sprintf(`
auth.token = "%s"
`, tokenContent)
// Client config with tokenSource
clientConf += fmt.Sprintf(`
auth.tokenSource.type = "file"
auth.tokenSource.file.path = "%s"
[[proxies]]
name = "tcp"
type = "tcp"
localPort = {{ .%s }}
remotePort = {{ .%s }}
`, tokenFile, framework.TCPEchoServerPort, portName)
f.RunProcesses([]string{serverConf}, []string{clientConf})
framework.NewRequestExpect(f).PortName(portName).Ensure()
})
ginkgo.It("should work with both server and client tokenSource", func() {
// Create temporary token files
tmpDir := f.TempDirectory
serverTokenFile := filepath.Join(tmpDir, "server_token")
clientTokenFile := filepath.Join(tmpDir, "client_token")
tokenContent := "shared-token-789"
err := os.WriteFile(serverTokenFile, []byte(tokenContent), 0o600)
framework.ExpectNoError(err)
err = os.WriteFile(clientTokenFile, []byte(tokenContent), 0o600)
framework.ExpectNoError(err)
serverConf := consts.DefaultServerConfig
clientConf := consts.DefaultClientConfig
portName := port.GenName("TCP")
// Server config with tokenSource
serverConf += fmt.Sprintf(`
auth.tokenSource.type = "file"
auth.tokenSource.file.path = "%s"
`, serverTokenFile)
// Client config with tokenSource
clientConf += fmt.Sprintf(`
auth.tokenSource.type = "file"
auth.tokenSource.file.path = "%s"
[[proxies]]
name = "tcp"
type = "tcp"
localPort = {{ .%s }}
remotePort = {{ .%s }}
`, clientTokenFile, framework.TCPEchoServerPort, portName)
f.RunProcesses([]string{serverConf}, []string{clientConf})
framework.NewRequestExpect(f).PortName(portName).Ensure()
})
ginkgo.It("should fail with mismatched tokens", func() {
// Create temporary token files with different content
tmpDir := f.TempDirectory
serverTokenFile := filepath.Join(tmpDir, "server_token")
clientTokenFile := filepath.Join(tmpDir, "client_token")
err := os.WriteFile(serverTokenFile, []byte("server-token"), 0o600)
framework.ExpectNoError(err)
err = os.WriteFile(clientTokenFile, []byte("client-token"), 0o600)
framework.ExpectNoError(err)
serverConf := consts.DefaultServerConfig
clientConf := consts.DefaultClientConfig
portName := port.GenName("TCP")
// Server config with tokenSource
serverConf += fmt.Sprintf(`
auth.tokenSource.type = "file"
auth.tokenSource.file.path = "%s"
`, serverTokenFile)
// Client config with different tokenSource
clientConf += fmt.Sprintf(`
auth.tokenSource.type = "file"
auth.tokenSource.file.path = "%s"
[[proxies]]
name = "tcp"
type = "tcp"
localPort = {{ .%s }}
remotePort = {{ .%s }}
`, clientTokenFile, framework.TCPEchoServerPort, portName)
f.RunProcesses([]string{serverConf}, []string{clientConf})
// This should fail due to token mismatch - the client should not be able to connect
// We expect the request to fail because the proxy tunnel is not established
framework.NewRequestExpect(f).PortName(portName).ExpectError(true).Ensure()
})
ginkgo.It("should fail with non-existent token file", func() {
// This test verifies that server fails to start when tokenSource points to non-existent file
// We'll verify this by checking that the configuration loading itself fails
// Create a config that references a non-existent file
tmpDir := f.TempDirectory
nonExistentFile := filepath.Join(tmpDir, "non_existent_token")
serverConf := consts.DefaultServerConfig
// Server config with non-existent tokenSource file
serverConf += fmt.Sprintf(`
auth.tokenSource.type = "file"
auth.tokenSource.file.path = "%s"
`, nonExistentFile)
// The test expectation is that this will fail during the RunProcesses call
// because the server cannot load the configuration due to missing token file
defer func() {
if r := recover(); r != nil {
// Expected: server should fail to start due to missing file
ginkgo.By(fmt.Sprintf("Server correctly failed to start: %v", r))
}
}()
// This should cause a panic or error during server startup
f.RunProcesses([]string{serverConf}, []string{})
})
})
ginkgo.Describe("Exec-based token loading", func() {
ginkgo.It("should work with server tokenSource", func() {
execValue := "exec-server-value"
scriptPath := createExecTokenScript("server_token_exec.sh")
serverPort := f.AllocPort()
remotePort := f.AllocPort()
serverConf := fmt.Sprintf(`
bindAddr = "0.0.0.0"
bindPort = %d
auth.tokenSource.type = "exec"
auth.tokenSource.exec.command = %q
auth.tokenSource.exec.args = [%q]
`, serverPort, scriptPath, execValue)
clientConf := fmt.Sprintf(`
serverAddr = "127.0.0.1"
serverPort = %d
loginFailExit = false
auth.token = %q
[[proxies]]
name = "tcp"
type = "tcp"
localPort = %d
remotePort = %d
`, serverPort, execValue, f.PortByName(framework.TCPEchoServerPort), remotePort)
serverConfigPath := f.GenerateConfigFile(serverConf)
clientConfigPath := f.GenerateConfigFile(clientConf)
_, _, err := f.RunFrps("-c", serverConfigPath, "--allow-unsafe=TokenSourceExec")
framework.ExpectNoError(err)
_, _, err = f.RunFrpc("-c", clientConfigPath, "--allow-unsafe=TokenSourceExec")
framework.ExpectNoError(err)
framework.NewRequestExpect(f).Port(remotePort).Ensure()
})
ginkgo.It("should work with client tokenSource", func() {
execValue := "exec-client-value"
scriptPath := createExecTokenScript("client_token_exec.sh")
serverPort := f.AllocPort()
remotePort := f.AllocPort()
serverConf := fmt.Sprintf(`
bindAddr = "0.0.0.0"
bindPort = %d
auth.token = %q
`, serverPort, execValue)
clientConf := fmt.Sprintf(`
serverAddr = "127.0.0.1"
serverPort = %d
loginFailExit = false
auth.tokenSource.type = "exec"
auth.tokenSource.exec.command = %q
auth.tokenSource.exec.args = [%q]
[[proxies]]
name = "tcp"
type = "tcp"
localPort = %d
remotePort = %d
`, serverPort, scriptPath, execValue, f.PortByName(framework.TCPEchoServerPort), remotePort)
serverConfigPath := f.GenerateConfigFile(serverConf)
clientConfigPath := f.GenerateConfigFile(clientConf)
_, _, err := f.RunFrps("-c", serverConfigPath, "--allow-unsafe=TokenSourceExec")
framework.ExpectNoError(err)
_, _, err = f.RunFrpc("-c", clientConfigPath, "--allow-unsafe=TokenSourceExec")
framework.ExpectNoError(err)
framework.NewRequestExpect(f).Port(remotePort).Ensure()
})
ginkgo.It("should work with both server and client tokenSource", func() {
execValue := "exec-shared-value"
scriptPath := createExecTokenScript("shared_token_exec.sh")
serverPort := f.AllocPort()
remotePort := f.AllocPort()
serverConf := fmt.Sprintf(`
bindAddr = "0.0.0.0"
bindPort = %d
auth.tokenSource.type = "exec"
auth.tokenSource.exec.command = %q
auth.tokenSource.exec.args = [%q]
`, serverPort, scriptPath, execValue)
clientConf := fmt.Sprintf(`
serverAddr = "127.0.0.1"
serverPort = %d
loginFailExit = false
auth.tokenSource.type = "exec"
auth.tokenSource.exec.command = %q
auth.tokenSource.exec.args = [%q]
[[proxies]]
name = "tcp"
type = "tcp"
localPort = %d
remotePort = %d
`, serverPort, scriptPath, execValue, f.PortByName(framework.TCPEchoServerPort), remotePort)
serverConfigPath := f.GenerateConfigFile(serverConf)
clientConfigPath := f.GenerateConfigFile(clientConf)
_, _, err := f.RunFrps("-c", serverConfigPath, "--allow-unsafe=TokenSourceExec")
framework.ExpectNoError(err)
_, _, err = f.RunFrpc("-c", clientConfigPath, "--allow-unsafe=TokenSourceExec")
framework.ExpectNoError(err)
framework.NewRequestExpect(f).Port(remotePort).Ensure()
})
ginkgo.It("should fail validation without allow-unsafe", func() {
execValue := "exec-unsafe-value"
scriptPath := createExecTokenScript("unsafe_token_exec.sh")
serverPort := f.AllocPort()
serverConf := fmt.Sprintf(`
bindAddr = "0.0.0.0"
bindPort = %d
auth.tokenSource.type = "exec"
auth.tokenSource.exec.command = %q
auth.tokenSource.exec.args = [%q]
`, serverPort, scriptPath, execValue)
serverConfigPath := f.GenerateConfigFile(serverConf)
_, output, err := f.RunFrps("verify", "-c", serverConfigPath)
framework.ExpectNoError(err)
framework.ExpectContainSubstring(output, "unsafe feature \"TokenSourceExec\" is not enabled")
})
})
})
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/v1/basic/cmd.go | test/e2e/v1/basic/cmd.go | package basic
import (
"strconv"
"strings"
"github.com/onsi/ginkgo/v2"
"github.com/fatedier/frp/test/e2e/framework"
"github.com/fatedier/frp/test/e2e/pkg/request"
)
const (
ConfigValidStr = "syntax is ok"
)
var _ = ginkgo.Describe("[Feature: Cmd]", func() {
f := framework.NewDefaultFramework()
ginkgo.Describe("Verify", func() {
ginkgo.It("frps valid", func() {
path := f.GenerateConfigFile(`
bindAddr = "0.0.0.0"
bindPort = 7000
`)
_, output, err := f.RunFrps("verify", "-c", path)
framework.ExpectNoError(err)
framework.ExpectTrue(strings.Contains(output, ConfigValidStr), "output: %s", output)
})
ginkgo.It("frps invalid", func() {
path := f.GenerateConfigFile(`
bindAddr = "0.0.0.0"
bindPort = 70000
`)
_, output, err := f.RunFrps("verify", "-c", path)
framework.ExpectNoError(err)
framework.ExpectTrue(!strings.Contains(output, ConfigValidStr), "output: %s", output)
})
ginkgo.It("frpc valid", func() {
path := f.GenerateConfigFile(`
serverAddr = "0.0.0.0"
serverPort = 7000
`)
_, output, err := f.RunFrpc("verify", "-c", path)
framework.ExpectNoError(err)
framework.ExpectTrue(strings.Contains(output, ConfigValidStr), "output: %s", output)
})
ginkgo.It("frpc invalid", func() {
path := f.GenerateConfigFile(`
serverAddr = "0.0.0.0"
serverPort = 7000
transport.protocol = "invalid"
`)
_, output, err := f.RunFrpc("verify", "-c", path)
framework.ExpectNoError(err)
framework.ExpectTrue(!strings.Contains(output, ConfigValidStr), "output: %s", output)
})
})
ginkgo.Describe("Single proxy", func() {
ginkgo.It("TCP", func() {
serverPort := f.AllocPort()
_, _, err := f.RunFrps("-t", "123", "-p", strconv.Itoa(serverPort))
framework.ExpectNoError(err)
localPort := f.PortByName(framework.TCPEchoServerPort)
remotePort := f.AllocPort()
_, _, err = f.RunFrpc("tcp", "-s", "127.0.0.1", "-P", strconv.Itoa(serverPort), "-t", "123", "-u", "test",
"-l", strconv.Itoa(localPort), "-r", strconv.Itoa(remotePort), "-n", "tcp_test")
framework.ExpectNoError(err)
framework.NewRequestExpect(f).Port(remotePort).Ensure()
})
ginkgo.It("UDP", func() {
serverPort := f.AllocPort()
_, _, err := f.RunFrps("-t", "123", "-p", strconv.Itoa(serverPort))
framework.ExpectNoError(err)
localPort := f.PortByName(framework.UDPEchoServerPort)
remotePort := f.AllocPort()
_, _, err = f.RunFrpc("udp", "-s", "127.0.0.1", "-P", strconv.Itoa(serverPort), "-t", "123", "-u", "test",
"-l", strconv.Itoa(localPort), "-r", strconv.Itoa(remotePort), "-n", "udp_test")
framework.ExpectNoError(err)
framework.NewRequestExpect(f).Protocol("udp").
Port(remotePort).Ensure()
})
ginkgo.It("HTTP", func() {
serverPort := f.AllocPort()
vhostHTTPPort := f.AllocPort()
_, _, err := f.RunFrps("-t", "123", "-p", strconv.Itoa(serverPort), "--vhost-http-port", strconv.Itoa(vhostHTTPPort))
framework.ExpectNoError(err)
_, _, err = f.RunFrpc("http", "-s", "127.0.0.1", "-P", strconv.Itoa(serverPort), "-t", "123", "-u", "test",
"-n", "udp_test", "-l", strconv.Itoa(f.PortByName(framework.HTTPSimpleServerPort)),
"--custom-domain", "test.example.com")
framework.ExpectNoError(err)
framework.NewRequestExpect(f).Port(vhostHTTPPort).
RequestModify(func(r *request.Request) {
r.HTTP().HTTPHost("test.example.com")
}).
Ensure()
})
})
})
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/v1/basic/server.go | test/e2e/v1/basic/server.go | package basic
import (
"context"
"fmt"
"net"
"strconv"
"github.com/onsi/ginkgo/v2"
"github.com/fatedier/frp/test/e2e/framework"
"github.com/fatedier/frp/test/e2e/framework/consts"
"github.com/fatedier/frp/test/e2e/pkg/port"
"github.com/fatedier/frp/test/e2e/pkg/request"
)
var _ = ginkgo.Describe("[Feature: Server Manager]", func() {
f := framework.NewDefaultFramework()
ginkgo.It("Ports Whitelist", func() {
serverConf := consts.DefaultServerConfig
clientConf := consts.DefaultClientConfig
serverConf += `
allowPorts = [
{ start = 10000, end = 11000 },
{ single = 11002 },
{ start = 12000, end = 13000 },
]
`
tcpPortName := port.GenName("TCP", port.WithRangePorts(10000, 11000))
udpPortName := port.GenName("UDP", port.WithRangePorts(12000, 13000))
clientConf += fmt.Sprintf(`
[[proxies]]
name = "tcp-allowded-in-range"
type = "tcp"
localPort = {{ .%s }}
remotePort = {{ .%s }}
`, framework.TCPEchoServerPort, tcpPortName)
clientConf += fmt.Sprintf(`
[[proxies]]
name = "tcp-port-not-allowed"
type = "tcp"
localPort = {{ .%s }}
remotePort = 11001
`, framework.TCPEchoServerPort)
clientConf += fmt.Sprintf(`
[[proxies]]
name = "tcp-port-unavailable"
type = "tcp"
localPort = {{ .%s }}
remotePort = {{ .%s }}
`, framework.TCPEchoServerPort, consts.PortServerName)
clientConf += fmt.Sprintf(`
[[proxies]]
name = "udp-allowed-in-range"
type = "udp"
localPort = {{ .%s }}
remotePort = {{ .%s }}
`, framework.UDPEchoServerPort, udpPortName)
clientConf += fmt.Sprintf(`
[[proxies]]
name = "udp-port-not-allowed"
type = "udp"
localPort = {{ .%s }}
remotePort = 11003
`, framework.UDPEchoServerPort)
f.RunProcesses([]string{serverConf}, []string{clientConf})
// TCP
// Allowed in range
framework.NewRequestExpect(f).PortName(tcpPortName).Ensure()
// Not Allowed
framework.NewRequestExpect(f).Port(11001).ExpectError(true).Ensure()
// Unavailable, already bind by frps
framework.NewRequestExpect(f).PortName(consts.PortServerName).ExpectError(true).Ensure()
// UDP
// Allowed in range
framework.NewRequestExpect(f).Protocol("udp").PortName(udpPortName).Ensure()
// Not Allowed
framework.NewRequestExpect(f).RequestModify(func(r *request.Request) {
r.UDP().Port(11003)
}).ExpectError(true).Ensure()
})
ginkgo.It("Alloc Random Port", func() {
serverConf := consts.DefaultServerConfig
clientConf := consts.DefaultClientConfig
adminPort := f.AllocPort()
clientConf += fmt.Sprintf(`
webServer.port = %d
[[proxies]]
name = "tcp"
type = "tcp"
localPort = {{ .%s }}
[[proxies]]
name = "udp"
type = "udp"
localPort = {{ .%s }}
`, adminPort, framework.TCPEchoServerPort, framework.UDPEchoServerPort)
f.RunProcesses([]string{serverConf}, []string{clientConf})
client := f.APIClientForFrpc(adminPort)
// tcp random port
status, err := client.GetProxyStatus(context.Background(), "tcp")
framework.ExpectNoError(err)
_, portStr, err := net.SplitHostPort(status.RemoteAddr)
framework.ExpectNoError(err)
port, err := strconv.Atoi(portStr)
framework.ExpectNoError(err)
framework.NewRequestExpect(f).Port(port).Ensure()
// udp random port
status, err = client.GetProxyStatus(context.Background(), "udp")
framework.ExpectNoError(err)
_, portStr, err = net.SplitHostPort(status.RemoteAddr)
framework.ExpectNoError(err)
port, err = strconv.Atoi(portStr)
framework.ExpectNoError(err)
framework.NewRequestExpect(f).Protocol("udp").Port(port).Ensure()
})
ginkgo.It("Port Reuse", func() {
serverConf := consts.DefaultServerConfig
// Use same port as PortServer
serverConf += fmt.Sprintf(`
vhostHTTPPort = {{ .%s }}
`, consts.PortServerName)
clientConf := consts.DefaultClientConfig + fmt.Sprintf(`
[[proxies]]
name = "http"
type = "http"
localPort = {{ .%s }}
customDomains = ["example.com"]
`, framework.HTTPSimpleServerPort)
f.RunProcesses([]string{serverConf}, []string{clientConf})
framework.NewRequestExpect(f).RequestModify(func(r *request.Request) {
r.HTTP().HTTPHost("example.com")
}).PortName(consts.PortServerName).Ensure()
})
ginkgo.It("healthz", func() {
serverConf := consts.DefaultServerConfig
dashboardPort := f.AllocPort()
// Use same port as PortServer
serverConf += fmt.Sprintf(`
vhostHTTPPort = {{ .%s }}
webServer.addr = "0.0.0.0"
webServer.port = %d
webServer.user = "admin"
webServer.password = "admin"
`, consts.PortServerName, dashboardPort)
clientConf := consts.DefaultClientConfig + fmt.Sprintf(`
[[proxies]]
name = "http"
type = "http"
localPort = {{ .%s }}
customDomains = ["example.com"]
`, framework.HTTPSimpleServerPort)
f.RunProcesses([]string{serverConf}, []string{clientConf})
framework.NewRequestExpect(f).RequestModify(func(r *request.Request) {
r.HTTP().HTTPPath("/healthz")
}).Port(dashboardPort).ExpectResp([]byte("")).Ensure()
framework.NewRequestExpect(f).RequestModify(func(r *request.Request) {
r.HTTP().HTTPPath("/")
}).Port(dashboardPort).
Ensure(framework.ExpectResponseCode(401))
})
})
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/v1/basic/http.go | test/e2e/v1/basic/http.go | package basic
import (
"fmt"
"net/http"
"net/url"
"strconv"
"time"
"github.com/gorilla/websocket"
"github.com/onsi/ginkgo/v2"
"github.com/fatedier/frp/test/e2e/framework"
"github.com/fatedier/frp/test/e2e/framework/consts"
"github.com/fatedier/frp/test/e2e/mock/server/httpserver"
"github.com/fatedier/frp/test/e2e/pkg/request"
)
var _ = ginkgo.Describe("[Feature: HTTP]", func() {
f := framework.NewDefaultFramework()
getDefaultServerConf := func(vhostHTTPPort int) string {
conf := consts.DefaultServerConfig + `
vhostHTTPPort = %d
`
return fmt.Sprintf(conf, vhostHTTPPort)
}
newHTTPServer := func(port int, respContent string) *httpserver.Server {
return httpserver.New(
httpserver.WithBindPort(port),
httpserver.WithHandler(framework.SpecifiedHTTPBodyHandler([]byte(respContent))),
)
}
ginkgo.It("HTTP route by locations", func() {
vhostHTTPPort := f.AllocPort()
serverConf := getDefaultServerConf(vhostHTTPPort)
fooPort := f.AllocPort()
f.RunServer("", newHTTPServer(fooPort, "foo"))
barPort := f.AllocPort()
f.RunServer("", newHTTPServer(barPort, "bar"))
clientConf := consts.DefaultClientConfig
clientConf += fmt.Sprintf(`
[[proxies]]
name = "foo"
type = "http"
localPort = %d
customDomains = ["normal.example.com"]
locations = ["/","/foo"]
[[proxies]]
name = "bar"
type = "http"
localPort = %d
customDomains = ["normal.example.com"]
locations = ["/bar"]
`, fooPort, barPort)
f.RunProcesses([]string{serverConf}, []string{clientConf})
tests := []struct {
path string
expectResp string
desc string
}{
{path: "/foo", expectResp: "foo", desc: "foo path"},
{path: "/bar", expectResp: "bar", desc: "bar path"},
{path: "/other", expectResp: "foo", desc: "other path"},
}
for _, test := range tests {
framework.NewRequestExpect(f).Explain(test.desc).Port(vhostHTTPPort).
RequestModify(func(r *request.Request) {
r.HTTP().HTTPHost("normal.example.com").HTTPPath(test.path)
}).
ExpectResp([]byte(test.expectResp)).
Ensure()
}
})
ginkgo.It("HTTP route by HTTP user", func() {
vhostHTTPPort := f.AllocPort()
serverConf := getDefaultServerConf(vhostHTTPPort)
fooPort := f.AllocPort()
f.RunServer("", newHTTPServer(fooPort, "foo"))
barPort := f.AllocPort()
f.RunServer("", newHTTPServer(barPort, "bar"))
otherPort := f.AllocPort()
f.RunServer("", newHTTPServer(otherPort, "other"))
clientConf := consts.DefaultClientConfig
clientConf += fmt.Sprintf(`
[[proxies]]
name = "foo"
type = "http"
localPort = %d
customDomains = ["normal.example.com"]
routeByHTTPUser = "user1"
[[proxies]]
name = "bar"
type = "http"
localPort = %d
customDomains = ["normal.example.com"]
routeByHTTPUser = "user2"
[[proxies]]
name = "catchAll"
type = "http"
localPort = %d
customDomains = ["normal.example.com"]
`, fooPort, barPort, otherPort)
f.RunProcesses([]string{serverConf}, []string{clientConf})
// user1
framework.NewRequestExpect(f).Explain("user1").Port(vhostHTTPPort).
RequestModify(func(r *request.Request) {
r.HTTP().HTTPHost("normal.example.com").HTTPAuth("user1", "")
}).
ExpectResp([]byte("foo")).
Ensure()
// user2
framework.NewRequestExpect(f).Explain("user2").Port(vhostHTTPPort).
RequestModify(func(r *request.Request) {
r.HTTP().HTTPHost("normal.example.com").HTTPAuth("user2", "")
}).
ExpectResp([]byte("bar")).
Ensure()
// other user
framework.NewRequestExpect(f).Explain("other user").Port(vhostHTTPPort).
RequestModify(func(r *request.Request) {
r.HTTP().HTTPHost("normal.example.com").HTTPAuth("user3", "")
}).
ExpectResp([]byte("other")).
Ensure()
})
ginkgo.It("HTTP Basic Auth", func() {
vhostHTTPPort := f.AllocPort()
serverConf := getDefaultServerConf(vhostHTTPPort)
clientConf := consts.DefaultClientConfig
clientConf += fmt.Sprintf(`
[[proxies]]
name = "test"
type = "http"
localPort = {{ .%s }}
customDomains = ["normal.example.com"]
httpUser = "test"
httpPassword = "test"
`, framework.HTTPSimpleServerPort)
f.RunProcesses([]string{serverConf}, []string{clientConf})
// not set auth header
framework.NewRequestExpect(f).Port(vhostHTTPPort).
RequestModify(func(r *request.Request) {
r.HTTP().HTTPHost("normal.example.com")
}).
Ensure(framework.ExpectResponseCode(401))
// set incorrect auth header
framework.NewRequestExpect(f).Port(vhostHTTPPort).
RequestModify(func(r *request.Request) {
r.HTTP().HTTPHost("normal.example.com").HTTPAuth("test", "invalid")
}).
Ensure(framework.ExpectResponseCode(401))
// set correct auth header
framework.NewRequestExpect(f).Port(vhostHTTPPort).
RequestModify(func(r *request.Request) {
r.HTTP().HTTPHost("normal.example.com").HTTPAuth("test", "test")
}).
Ensure()
})
ginkgo.It("Wildcard domain", func() {
vhostHTTPPort := f.AllocPort()
serverConf := getDefaultServerConf(vhostHTTPPort)
clientConf := consts.DefaultClientConfig
clientConf += fmt.Sprintf(`
[[proxies]]
name = "test"
type = "http"
localPort = {{ .%s }}
customDomains = ["*.example.com"]
`, framework.HTTPSimpleServerPort)
f.RunProcesses([]string{serverConf}, []string{clientConf})
// not match host
framework.NewRequestExpect(f).Port(vhostHTTPPort).
RequestModify(func(r *request.Request) {
r.HTTP().HTTPHost("not-match.test.com")
}).
Ensure(framework.ExpectResponseCode(404))
// test.example.com match *.example.com
framework.NewRequestExpect(f).Port(vhostHTTPPort).
RequestModify(func(r *request.Request) {
r.HTTP().HTTPHost("test.example.com")
}).
Ensure()
// sub.test.example.com match *.example.com
framework.NewRequestExpect(f).Port(vhostHTTPPort).
RequestModify(func(r *request.Request) {
r.HTTP().HTTPHost("sub.test.example.com")
}).
Ensure()
})
ginkgo.It("Subdomain", func() {
vhostHTTPPort := f.AllocPort()
serverConf := getDefaultServerConf(vhostHTTPPort)
serverConf += `
subdomainHost = "example.com"
`
fooPort := f.AllocPort()
f.RunServer("", newHTTPServer(fooPort, "foo"))
barPort := f.AllocPort()
f.RunServer("", newHTTPServer(barPort, "bar"))
clientConf := consts.DefaultClientConfig
clientConf += fmt.Sprintf(`
[[proxies]]
name = "foo"
type = "http"
localPort = %d
subdomain = "foo"
[[proxies]]
name = "bar"
type = "http"
localPort = %d
subdomain = "bar"
`, fooPort, barPort)
f.RunProcesses([]string{serverConf}, []string{clientConf})
// foo
framework.NewRequestExpect(f).Explain("foo subdomain").Port(vhostHTTPPort).
RequestModify(func(r *request.Request) {
r.HTTP().HTTPHost("foo.example.com")
}).
ExpectResp([]byte("foo")).
Ensure()
// bar
framework.NewRequestExpect(f).Explain("bar subdomain").Port(vhostHTTPPort).
RequestModify(func(r *request.Request) {
r.HTTP().HTTPHost("bar.example.com")
}).
ExpectResp([]byte("bar")).
Ensure()
})
ginkgo.It("Modify request headers", func() {
vhostHTTPPort := f.AllocPort()
serverConf := getDefaultServerConf(vhostHTTPPort)
localPort := f.AllocPort()
localServer := httpserver.New(
httpserver.WithBindPort(localPort),
httpserver.WithHandler(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
_, _ = w.Write([]byte(req.Header.Get("X-From-Where")))
})),
)
f.RunServer("", localServer)
clientConf := consts.DefaultClientConfig
clientConf += fmt.Sprintf(`
[[proxies]]
name = "test"
type = "http"
localPort = %d
customDomains = ["normal.example.com"]
requestHeaders.set.x-from-where = "frp"
`, localPort)
f.RunProcesses([]string{serverConf}, []string{clientConf})
framework.NewRequestExpect(f).Port(vhostHTTPPort).
RequestModify(func(r *request.Request) {
r.HTTP().HTTPHost("normal.example.com")
}).
ExpectResp([]byte("frp")). // local http server will write this X-From-Where header to response body
Ensure()
})
ginkgo.It("Modify response headers", func() {
vhostHTTPPort := f.AllocPort()
serverConf := getDefaultServerConf(vhostHTTPPort)
localPort := f.AllocPort()
localServer := httpserver.New(
httpserver.WithBindPort(localPort),
httpserver.WithHandler(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(200)
})),
)
f.RunServer("", localServer)
clientConf := consts.DefaultClientConfig
clientConf += fmt.Sprintf(`
[[proxies]]
name = "test"
type = "http"
localPort = %d
customDomains = ["normal.example.com"]
responseHeaders.set.x-from-where = "frp"
`, localPort)
f.RunProcesses([]string{serverConf}, []string{clientConf})
framework.NewRequestExpect(f).Port(vhostHTTPPort).
RequestModify(func(r *request.Request) {
r.HTTP().HTTPHost("normal.example.com")
}).
Ensure(func(res *request.Response) bool {
return res.Header.Get("X-From-Where") == "frp"
})
})
ginkgo.It("Host Header Rewrite", func() {
vhostHTTPPort := f.AllocPort()
serverConf := getDefaultServerConf(vhostHTTPPort)
localPort := f.AllocPort()
localServer := httpserver.New(
httpserver.WithBindPort(localPort),
httpserver.WithHandler(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
_, _ = w.Write([]byte(req.Host))
})),
)
f.RunServer("", localServer)
clientConf := consts.DefaultClientConfig
clientConf += fmt.Sprintf(`
[[proxies]]
name = "test"
type = "http"
localPort = %d
customDomains = ["normal.example.com"]
hostHeaderRewrite = "rewrite.example.com"
`, localPort)
f.RunProcesses([]string{serverConf}, []string{clientConf})
framework.NewRequestExpect(f).Port(vhostHTTPPort).
RequestModify(func(r *request.Request) {
r.HTTP().HTTPHost("normal.example.com")
}).
ExpectResp([]byte("rewrite.example.com")). // local http server will write host header to response body
Ensure()
})
ginkgo.It("Websocket protocol", func() {
vhostHTTPPort := f.AllocPort()
serverConf := getDefaultServerConf(vhostHTTPPort)
upgrader := websocket.Upgrader{}
localPort := f.AllocPort()
localServer := httpserver.New(
httpserver.WithBindPort(localPort),
httpserver.WithHandler(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
c, err := upgrader.Upgrade(w, req, nil)
if err != nil {
return
}
defer c.Close()
for {
mt, message, err := c.ReadMessage()
if err != nil {
break
}
err = c.WriteMessage(mt, message)
if err != nil {
break
}
}
})),
)
f.RunServer("", localServer)
clientConf := consts.DefaultClientConfig
clientConf += fmt.Sprintf(`
[[proxies]]
name = "test"
type = "http"
localPort = %d
customDomains = ["127.0.0.1"]
`, localPort)
f.RunProcesses([]string{serverConf}, []string{clientConf})
u := url.URL{Scheme: "ws", Host: "127.0.0.1:" + strconv.Itoa(vhostHTTPPort)}
c, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
framework.ExpectNoError(err)
err = c.WriteMessage(websocket.TextMessage, []byte(consts.TestString))
framework.ExpectNoError(err)
_, msg, err := c.ReadMessage()
framework.ExpectNoError(err)
framework.ExpectEqualValues(consts.TestString, string(msg))
})
ginkgo.It("vhostHTTPTimeout", func() {
vhostHTTPPort := f.AllocPort()
serverConf := getDefaultServerConf(vhostHTTPPort)
serverConf += `
vhostHTTPTimeout = 2
`
delayDuration := 0 * time.Second
localPort := f.AllocPort()
localServer := httpserver.New(
httpserver.WithBindPort(localPort),
httpserver.WithHandler(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
time.Sleep(delayDuration)
_, _ = w.Write([]byte(req.Host))
})),
)
f.RunServer("", localServer)
clientConf := consts.DefaultClientConfig
clientConf += fmt.Sprintf(`
[[proxies]]
name = "test"
type = "http"
localPort = %d
customDomains = ["normal.example.com"]
`, localPort)
f.RunProcesses([]string{serverConf}, []string{clientConf})
framework.NewRequestExpect(f).Port(vhostHTTPPort).
RequestModify(func(r *request.Request) {
r.HTTP().HTTPHost("normal.example.com").HTTP().Timeout(time.Second)
}).
ExpectResp([]byte("normal.example.com")).
Ensure()
delayDuration = 3 * time.Second
framework.NewRequestExpect(f).Port(vhostHTTPPort).
RequestModify(func(r *request.Request) {
r.HTTP().HTTPHost("normal.example.com").HTTP().Timeout(5 * time.Second)
}).
Ensure(framework.ExpectResponseCode(504))
})
})
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/v1/basic/client_server.go | test/e2e/v1/basic/client_server.go | package basic
import (
"fmt"
"strings"
"time"
"github.com/onsi/ginkgo/v2"
"github.com/fatedier/frp/test/e2e/framework"
"github.com/fatedier/frp/test/e2e/framework/consts"
"github.com/fatedier/frp/test/e2e/pkg/cert"
"github.com/fatedier/frp/test/e2e/pkg/port"
)
type generalTestConfigures struct {
server string
client string
clientPrefix string
client2 string
client2Prefix string
testDelay time.Duration
expectError bool
}
func renderBindPortConfig(protocol string) string {
switch protocol {
case "kcp":
return fmt.Sprintf(`kcpBindPort = {{ .%s }}`, consts.PortServerName)
case "quic":
return fmt.Sprintf(`quicBindPort = {{ .%s }}`, consts.PortServerName)
default:
return ""
}
}
func runClientServerTest(f *framework.Framework, configures *generalTestConfigures) {
serverConf := consts.DefaultServerConfig
clientConf := consts.DefaultClientConfig
if configures.clientPrefix != "" {
clientConf = configures.clientPrefix
}
serverConf += fmt.Sprintf(`
%s
`, configures.server)
tcpPortName := port.GenName("TCP")
udpPortName := port.GenName("UDP")
clientConf += fmt.Sprintf(`
%s
[[proxies]]
name = "tcp"
type = "tcp"
localPort = {{ .%s }}
remotePort = {{ .%s }}
[[proxies]]
name = "udp"
type = "udp"
localPort = {{ .%s }}
remotePort = {{ .%s }}
`, configures.client,
framework.TCPEchoServerPort, tcpPortName,
framework.UDPEchoServerPort, udpPortName,
)
clientConfs := []string{clientConf}
if configures.client2 != "" {
client2Conf := consts.DefaultClientConfig
if configures.client2Prefix != "" {
client2Conf = configures.client2Prefix
}
client2Conf += fmt.Sprintf(`
%s
`, configures.client2)
clientConfs = append(clientConfs, client2Conf)
}
f.RunProcesses([]string{serverConf}, clientConfs)
if configures.testDelay > 0 {
time.Sleep(configures.testDelay)
}
framework.NewRequestExpect(f).PortName(tcpPortName).ExpectError(configures.expectError).Explain("tcp proxy").Ensure()
framework.NewRequestExpect(f).Protocol("udp").
PortName(udpPortName).ExpectError(configures.expectError).Explain("udp proxy").Ensure()
}
// defineClientServerTest test a normal tcp and udp proxy with specified TestConfigures.
func defineClientServerTest(desc string, f *framework.Framework, configures *generalTestConfigures) {
ginkgo.It(desc, func() {
runClientServerTest(f, configures)
})
}
var _ = ginkgo.Describe("[Feature: Client-Server]", func() {
f := framework.NewDefaultFramework()
ginkgo.Describe("Protocol", func() {
supportProtocols := []string{"tcp", "kcp", "quic", "websocket"}
for _, protocol := range supportProtocols {
configures := &generalTestConfigures{
server: fmt.Sprintf(`
%s
`, renderBindPortConfig(protocol)),
client: fmt.Sprintf(`transport.protocol = "%s"`, protocol),
}
defineClientServerTest(protocol, f, configures)
}
})
// wss is special, it needs to be tested separately.
// frps only supports ws, so there should be a proxy to terminate TLS before frps.
ginkgo.Describe("Protocol wss", func() {
wssPort := f.AllocPort()
configures := &generalTestConfigures{
clientPrefix: fmt.Sprintf(`
serverAddr = "127.0.0.1"
serverPort = %d
loginFailExit = false
transport.protocol = "wss"
log.level = "trace"
`, wssPort),
// Due to the fact that frps cannot directly accept wss connections, we use the https2http plugin of another frpc to terminate TLS.
client2: fmt.Sprintf(`
[[proxies]]
name = "wss2ws"
type = "tcp"
remotePort = %d
[proxies.plugin]
type = "https2http"
localAddr = "127.0.0.1:{{ .%s }}"
`, wssPort, consts.PortServerName),
testDelay: 10 * time.Second,
}
defineClientServerTest("wss", f, configures)
})
ginkgo.Describe("Authentication", func() {
defineClientServerTest("Token Correct", f, &generalTestConfigures{
server: `auth.token = "123456"`,
client: `auth.token = "123456"`,
})
defineClientServerTest("Token Incorrect", f, &generalTestConfigures{
server: `auth.token = "123456"`,
client: `auth.token = "invalid"`,
expectError: true,
})
})
ginkgo.Describe("TLS", func() {
supportProtocols := []string{"tcp", "kcp", "quic", "websocket"}
for _, protocol := range supportProtocols {
tmp := protocol
// Since v0.50.0, the default value of tls_enable has been changed to true.
// Therefore, here it needs to be set as false to test the scenario of turning it off.
defineClientServerTest("Disable TLS over "+strings.ToUpper(tmp), f, &generalTestConfigures{
server: fmt.Sprintf(`
%s
`, renderBindPortConfig(protocol)),
client: fmt.Sprintf(`transport.tls.enable = false
transport.protocol = "%s"
`, protocol),
})
}
defineClientServerTest("enable tls force, client with TLS", f, &generalTestConfigures{
server: "transport.tls.force = true",
})
defineClientServerTest("enable tls force, client without TLS", f, &generalTestConfigures{
server: "transport.tls.force = true",
client: "transport.tls.enable = false",
expectError: true,
})
})
ginkgo.Describe("TLS with custom certificate", func() {
supportProtocols := []string{"tcp", "kcp", "quic", "websocket"}
var (
caCrtPath string
serverCrtPath, serverKeyPath string
clientCrtPath, clientKeyPath string
)
ginkgo.JustBeforeEach(func() {
generator := &cert.SelfSignedCertGenerator{}
artifacts, err := generator.Generate("127.0.0.1")
framework.ExpectNoError(err)
caCrtPath = f.WriteTempFile("ca.crt", string(artifacts.CACert))
serverCrtPath = f.WriteTempFile("server.crt", string(artifacts.Cert))
serverKeyPath = f.WriteTempFile("server.key", string(artifacts.Key))
generator.SetCA(artifacts.CACert, artifacts.CAKey)
_, err = generator.Generate("127.0.0.1")
framework.ExpectNoError(err)
clientCrtPath = f.WriteTempFile("client.crt", string(artifacts.Cert))
clientKeyPath = f.WriteTempFile("client.key", string(artifacts.Key))
})
for _, protocol := range supportProtocols {
tmp := protocol
ginkgo.It("one-way authentication: "+tmp, func() {
runClientServerTest(f, &generalTestConfigures{
server: fmt.Sprintf(`
%s
transport.tls.trustedCaFile = "%s"
`, renderBindPortConfig(tmp), caCrtPath),
client: fmt.Sprintf(`
transport.protocol = "%s"
transport.tls.certFile = "%s"
transport.tls.keyFile = "%s"
`, tmp, clientCrtPath, clientKeyPath),
})
})
ginkgo.It("mutual authentication: "+tmp, func() {
runClientServerTest(f, &generalTestConfigures{
server: fmt.Sprintf(`
%s
transport.tls.certFile = "%s"
transport.tls.keyFile = "%s"
transport.tls.trustedCaFile = "%s"
`, renderBindPortConfig(tmp), serverCrtPath, serverKeyPath, caCrtPath),
client: fmt.Sprintf(`
transport.protocol = "%s"
transport.tls.certFile = "%s"
transport.tls.keyFile = "%s"
transport.tls.trustedCaFile = "%s"
`, tmp, clientCrtPath, clientKeyPath, caCrtPath),
})
})
}
})
ginkgo.Describe("TLS with custom certificate and specified server name", func() {
var (
caCrtPath string
serverCrtPath, serverKeyPath string
clientCrtPath, clientKeyPath string
)
ginkgo.JustBeforeEach(func() {
generator := &cert.SelfSignedCertGenerator{}
artifacts, err := generator.Generate("example.com")
framework.ExpectNoError(err)
caCrtPath = f.WriteTempFile("ca.crt", string(artifacts.CACert))
serverCrtPath = f.WriteTempFile("server.crt", string(artifacts.Cert))
serverKeyPath = f.WriteTempFile("server.key", string(artifacts.Key))
generator.SetCA(artifacts.CACert, artifacts.CAKey)
_, err = generator.Generate("example.com")
framework.ExpectNoError(err)
clientCrtPath = f.WriteTempFile("client.crt", string(artifacts.Cert))
clientKeyPath = f.WriteTempFile("client.key", string(artifacts.Key))
})
ginkgo.It("mutual authentication", func() {
runClientServerTest(f, &generalTestConfigures{
server: fmt.Sprintf(`
transport.tls.certFile = "%s"
transport.tls.keyFile = "%s"
transport.tls.trustedCaFile = "%s"
`, serverCrtPath, serverKeyPath, caCrtPath),
client: fmt.Sprintf(`
transport.tls.serverName = "example.com"
transport.tls.certFile = "%s"
transport.tls.keyFile = "%s"
transport.tls.trustedCaFile = "%s"
`, clientCrtPath, clientKeyPath, caCrtPath),
})
})
ginkgo.It("mutual authentication with incorrect server name", func() {
runClientServerTest(f, &generalTestConfigures{
server: fmt.Sprintf(`
transport.tls.certFile = "%s"
transport.tls.keyFile = "%s"
transport.tls.trustedCaFile = "%s"
`, serverCrtPath, serverKeyPath, caCrtPath),
client: fmt.Sprintf(`
transport.tls.serverName = "invalid.com"
transport.tls.certFile = "%s"
transport.tls.keyFile = "%s"
transport.tls.trustedCaFile = "%s"
`, clientCrtPath, clientKeyPath, caCrtPath),
expectError: true,
})
})
})
ginkgo.Describe("TLS with disableCustomTLSFirstByte set to false", func() {
supportProtocols := []string{"tcp", "kcp", "quic", "websocket"}
for _, protocol := range supportProtocols {
tmp := protocol
defineClientServerTest("TLS over "+strings.ToUpper(tmp), f, &generalTestConfigures{
server: fmt.Sprintf(`
%s
`, renderBindPortConfig(protocol)),
client: fmt.Sprintf(`
transport.protocol = "%s"
transport.tls.disableCustomTLSFirstByte = false
`, protocol),
})
}
})
ginkgo.Describe("IPv6 bind address", func() {
supportProtocols := []string{"tcp", "kcp", "quic", "websocket"}
for _, protocol := range supportProtocols {
tmp := protocol
defineClientServerTest("IPv6 bind address: "+strings.ToUpper(tmp), f, &generalTestConfigures{
server: fmt.Sprintf(`
bindAddr = "::"
%s
`, renderBindPortConfig(protocol)),
client: fmt.Sprintf(`
transport.protocol = "%s"
`, protocol),
})
}
})
ginkgo.Describe("Use same port for bindPort and vhostHTTPSPort", func() {
supportProtocols := []string{"tcp", "kcp", "quic", "websocket"}
for _, protocol := range supportProtocols {
tmp := protocol
defineClientServerTest("Use same port for bindPort and vhostHTTPSPort: "+strings.ToUpper(tmp), f, &generalTestConfigures{
server: fmt.Sprintf(`
vhostHTTPSPort = {{ .%s }}
%s
`, consts.PortServerName, renderBindPortConfig(protocol)),
// transport.tls.disableCustomTLSFirstByte should set to false when vhostHTTPSPort is same as bindPort
client: fmt.Sprintf(`
transport.protocol = "%s"
transport.tls.disableCustomTLSFirstByte = false
`, protocol),
})
}
})
})
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/v1/basic/tcpmux.go | test/e2e/v1/basic/tcpmux.go | package basic
import (
"bufio"
"fmt"
"net"
"net/http"
"github.com/onsi/ginkgo/v2"
httppkg "github.com/fatedier/frp/pkg/util/http"
"github.com/fatedier/frp/test/e2e/framework"
"github.com/fatedier/frp/test/e2e/framework/consts"
"github.com/fatedier/frp/test/e2e/mock/server/streamserver"
"github.com/fatedier/frp/test/e2e/pkg/request"
"github.com/fatedier/frp/test/e2e/pkg/rpc"
)
var _ = ginkgo.Describe("[Feature: TCPMUX httpconnect]", func() {
f := framework.NewDefaultFramework()
getDefaultServerConf := func(httpconnectPort int) string {
conf := consts.DefaultServerConfig + `
tcpmuxHTTPConnectPort = %d
`
return fmt.Sprintf(conf, httpconnectPort)
}
newServer := func(port int, respContent string) *streamserver.Server {
return streamserver.New(
streamserver.TCP,
streamserver.WithBindPort(port),
streamserver.WithRespContent([]byte(respContent)),
)
}
proxyURLWithAuth := func(username, password string, port int) string {
if username == "" {
return fmt.Sprintf("http://127.0.0.1:%d", port)
}
return fmt.Sprintf("http://%s:%s@127.0.0.1:%d", username, password, port)
}
ginkgo.It("Route by HTTP user", func() {
vhostPort := f.AllocPort()
serverConf := getDefaultServerConf(vhostPort)
fooPort := f.AllocPort()
f.RunServer("", newServer(fooPort, "foo"))
barPort := f.AllocPort()
f.RunServer("", newServer(barPort, "bar"))
otherPort := f.AllocPort()
f.RunServer("", newServer(otherPort, "other"))
clientConf := consts.DefaultClientConfig
clientConf += fmt.Sprintf(`
[[proxies]]
name = "foo"
type = "tcpmux"
multiplexer = "httpconnect"
localPort = %d
customDomains = ["normal.example.com"]
routeByHTTPUser = "user1"
[[proxies]]
name = "bar"
type = "tcpmux"
multiplexer = "httpconnect"
localPort = %d
customDomains = ["normal.example.com"]
routeByHTTPUser = "user2"
[[proxies]]
name = "catchAll"
type = "tcpmux"
multiplexer = "httpconnect"
localPort = %d
customDomains = ["normal.example.com"]
`, fooPort, barPort, otherPort)
f.RunProcesses([]string{serverConf}, []string{clientConf})
// user1
framework.NewRequestExpect(f).Explain("user1").
RequestModify(func(r *request.Request) {
r.Addr("normal.example.com").Proxy(proxyURLWithAuth("user1", "", vhostPort))
}).
ExpectResp([]byte("foo")).
Ensure()
// user2
framework.NewRequestExpect(f).Explain("user2").
RequestModify(func(r *request.Request) {
r.Addr("normal.example.com").Proxy(proxyURLWithAuth("user2", "", vhostPort))
}).
ExpectResp([]byte("bar")).
Ensure()
// other user
framework.NewRequestExpect(f).Explain("other user").
RequestModify(func(r *request.Request) {
r.Addr("normal.example.com").Proxy(proxyURLWithAuth("user3", "", vhostPort))
}).
ExpectResp([]byte("other")).
Ensure()
})
ginkgo.It("Proxy auth", func() {
vhostPort := f.AllocPort()
serverConf := getDefaultServerConf(vhostPort)
fooPort := f.AllocPort()
f.RunServer("", newServer(fooPort, "foo"))
clientConf := consts.DefaultClientConfig
clientConf += fmt.Sprintf(`
[[proxies]]
name = "test"
type = "tcpmux"
multiplexer = "httpconnect"
localPort = %d
customDomains = ["normal.example.com"]
httpUser = "test"
httpPassword = "test"
`, fooPort)
f.RunProcesses([]string{serverConf}, []string{clientConf})
// not set auth header
framework.NewRequestExpect(f).Explain("no auth").
RequestModify(func(r *request.Request) {
r.Addr("normal.example.com").Proxy(proxyURLWithAuth("", "", vhostPort))
}).
ExpectError(true).
Ensure()
// set incorrect auth header
framework.NewRequestExpect(f).Explain("incorrect auth").
RequestModify(func(r *request.Request) {
r.Addr("normal.example.com").Proxy(proxyURLWithAuth("test", "invalid", vhostPort))
}).
ExpectError(true).
Ensure()
// set correct auth header
framework.NewRequestExpect(f).Explain("correct auth").
RequestModify(func(r *request.Request) {
r.Addr("normal.example.com").Proxy(proxyURLWithAuth("test", "test", vhostPort))
}).
ExpectResp([]byte("foo")).
Ensure()
})
ginkgo.It("TCPMux Passthrough", func() {
vhostPort := f.AllocPort()
serverConf := getDefaultServerConf(vhostPort)
serverConf += `
tcpmuxPassthrough = true
`
var (
respErr error
connectRequestHost string
)
newServer := func(port int) *streamserver.Server {
return streamserver.New(
streamserver.TCP,
streamserver.WithBindPort(port),
streamserver.WithCustomHandler(func(conn net.Conn) {
defer conn.Close()
// read HTTP CONNECT request
bufioReader := bufio.NewReader(conn)
req, err := http.ReadRequest(bufioReader)
if err != nil {
respErr = err
return
}
connectRequestHost = req.Host
// return ok response
res := httppkg.OkResponse()
if res.Body != nil {
defer res.Body.Close()
}
_ = res.Write(conn)
buf, err := rpc.ReadBytes(conn)
if err != nil {
respErr = err
return
}
_, _ = rpc.WriteBytes(conn, buf)
}),
)
}
localPort := f.AllocPort()
f.RunServer("", newServer(localPort))
clientConf := consts.DefaultClientConfig
clientConf += fmt.Sprintf(`
[[proxies]]
name = "test"
type = "tcpmux"
multiplexer = "httpconnect"
localPort = %d
customDomains = ["normal.example.com"]
`, localPort)
f.RunProcesses([]string{serverConf}, []string{clientConf})
framework.NewRequestExpect(f).
RequestModify(func(r *request.Request) {
r.Addr("normal.example.com").Proxy(proxyURLWithAuth("", "", vhostPort)).Body([]byte("frp"))
}).
ExpectResp([]byte("frp")).
Ensure()
framework.ExpectNoError(respErr)
framework.ExpectEqualValues(connectRequestHost, "normal.example.com")
})
})
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/v1/features/chaos.go | test/e2e/v1/features/chaos.go | package features
import (
"fmt"
"time"
"github.com/onsi/ginkgo/v2"
"github.com/fatedier/frp/test/e2e/framework"
)
var _ = ginkgo.Describe("[Feature: Chaos]", func() {
f := framework.NewDefaultFramework()
ginkgo.It("reconnect after frps restart", func() {
serverPort := f.AllocPort()
serverConfigPath := f.GenerateConfigFile(fmt.Sprintf(`
bindAddr = "0.0.0.0"
bindPort = %d
`, serverPort))
remotePort := f.AllocPort()
clientConfigPath := f.GenerateConfigFile(fmt.Sprintf(`
serverPort = %d
log.level = "trace"
[[proxies]]
name = "tcp"
type = "tcp"
localPort = %d
remotePort = %d
`, serverPort, f.PortByName(framework.TCPEchoServerPort), remotePort))
// 1. start frps and frpc, expect request success
ps, _, err := f.RunFrps("-c", serverConfigPath)
framework.ExpectNoError(err)
pc, _, err := f.RunFrpc("-c", clientConfigPath)
framework.ExpectNoError(err)
framework.NewRequestExpect(f).Port(remotePort).Ensure()
// 2. stop frps, expect request failed
_ = ps.Stop()
time.Sleep(200 * time.Millisecond)
framework.NewRequestExpect(f).Port(remotePort).ExpectError(true).Ensure()
// 3. restart frps, expect request success
_, _, err = f.RunFrps("-c", serverConfigPath)
framework.ExpectNoError(err)
time.Sleep(2 * time.Second)
framework.NewRequestExpect(f).Port(remotePort).Ensure()
// 4. stop frpc, expect request failed
_ = pc.Stop()
time.Sleep(200 * time.Millisecond)
framework.NewRequestExpect(f).Port(remotePort).ExpectError(true).Ensure()
// 5. restart frpc, expect request success
_, _, err = f.RunFrpc("-c", clientConfigPath)
framework.ExpectNoError(err)
time.Sleep(time.Second)
framework.NewRequestExpect(f).Port(remotePort).Ensure()
})
})
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/v1/features/ssh_tunnel.go | test/e2e/v1/features/ssh_tunnel.go | package features
import (
"crypto/tls"
"fmt"
"time"
"github.com/onsi/ginkgo/v2"
"github.com/fatedier/frp/pkg/transport"
"github.com/fatedier/frp/test/e2e/framework"
"github.com/fatedier/frp/test/e2e/framework/consts"
"github.com/fatedier/frp/test/e2e/mock/server/httpserver"
"github.com/fatedier/frp/test/e2e/mock/server/streamserver"
"github.com/fatedier/frp/test/e2e/pkg/request"
"github.com/fatedier/frp/test/e2e/pkg/ssh"
)
var _ = ginkgo.Describe("[Feature: SSH Tunnel]", func() {
f := framework.NewDefaultFramework()
ginkgo.It("tcp", func() {
sshPort := f.AllocPort()
serverConf := consts.DefaultServerConfig + fmt.Sprintf(`
sshTunnelGateway.bindPort = %d
`, sshPort)
f.RunProcesses([]string{serverConf}, nil)
localPort := f.PortByName(framework.TCPEchoServerPort)
remotePort := f.AllocPort()
tc := ssh.NewTunnelClient(
fmt.Sprintf("127.0.0.1:%d", localPort),
fmt.Sprintf("127.0.0.1:%d", sshPort),
fmt.Sprintf("tcp --remote-port %d", remotePort),
)
framework.ExpectNoError(tc.Start())
defer tc.Close()
time.Sleep(time.Second)
framework.NewRequestExpect(f).Port(remotePort).Ensure()
})
ginkgo.It("http", func() {
sshPort := f.AllocPort()
vhostPort := f.AllocPort()
serverConf := consts.DefaultServerConfig + fmt.Sprintf(`
vhostHTTPPort = %d
sshTunnelGateway.bindPort = %d
`, vhostPort, sshPort)
f.RunProcesses([]string{serverConf}, nil)
localPort := f.PortByName(framework.HTTPSimpleServerPort)
tc := ssh.NewTunnelClient(
fmt.Sprintf("127.0.0.1:%d", localPort),
fmt.Sprintf("127.0.0.1:%d", sshPort),
"http --custom-domain test.example.com",
)
framework.ExpectNoError(tc.Start())
defer tc.Close()
time.Sleep(time.Second)
framework.NewRequestExpect(f).Port(vhostPort).
RequestModify(func(r *request.Request) {
r.HTTP().HTTPHost("test.example.com")
}).
Ensure()
})
ginkgo.It("https", func() {
sshPort := f.AllocPort()
vhostPort := f.AllocPort()
serverConf := consts.DefaultServerConfig + fmt.Sprintf(`
vhostHTTPSPort = %d
sshTunnelGateway.bindPort = %d
`, vhostPort, sshPort)
f.RunProcesses([]string{serverConf}, nil)
localPort := f.AllocPort()
testDomain := "test.example.com"
tc := ssh.NewTunnelClient(
fmt.Sprintf("127.0.0.1:%d", localPort),
fmt.Sprintf("127.0.0.1:%d", sshPort),
fmt.Sprintf("https --custom-domain %s", testDomain),
)
framework.ExpectNoError(tc.Start())
defer tc.Close()
tlsConfig, err := transport.NewServerTLSConfig("", "", "")
framework.ExpectNoError(err)
localServer := httpserver.New(
httpserver.WithBindPort(localPort),
httpserver.WithTLSConfig(tlsConfig),
httpserver.WithResponse([]byte("test")),
)
f.RunServer("", localServer)
time.Sleep(time.Second)
framework.NewRequestExpect(f).
Port(vhostPort).
RequestModify(func(r *request.Request) {
r.HTTPS().HTTPHost(testDomain).TLSConfig(&tls.Config{
ServerName: testDomain,
InsecureSkipVerify: true,
})
}).
ExpectResp([]byte("test")).
Ensure()
})
ginkgo.It("tcpmux", func() {
sshPort := f.AllocPort()
tcpmuxPort := f.AllocPort()
serverConf := consts.DefaultServerConfig + fmt.Sprintf(`
tcpmuxHTTPConnectPort = %d
sshTunnelGateway.bindPort = %d
`, tcpmuxPort, sshPort)
f.RunProcesses([]string{serverConf}, nil)
localPort := f.AllocPort()
testDomain := "test.example.com"
tc := ssh.NewTunnelClient(
fmt.Sprintf("127.0.0.1:%d", localPort),
fmt.Sprintf("127.0.0.1:%d", sshPort),
fmt.Sprintf("tcpmux --mux=httpconnect --custom-domain %s", testDomain),
)
framework.ExpectNoError(tc.Start())
defer tc.Close()
localServer := streamserver.New(
streamserver.TCP,
streamserver.WithBindPort(localPort),
streamserver.WithRespContent([]byte("test")),
)
f.RunServer("", localServer)
time.Sleep(time.Second)
// Request without HTTP connect should get error
framework.NewRequestExpect(f).
Port(tcpmuxPort).
ExpectError(true).
Explain("request without HTTP connect expect error").
Ensure()
proxyURL := fmt.Sprintf("http://127.0.0.1:%d", tcpmuxPort)
// Request with incorrect connect hostname
framework.NewRequestExpect(f).RequestModify(func(r *request.Request) {
r.Addr("invalid").Proxy(proxyURL)
}).ExpectError(true).Explain("request without HTTP connect expect error").Ensure()
// Request with correct connect hostname
framework.NewRequestExpect(f).RequestModify(func(r *request.Request) {
r.Addr(testDomain).Proxy(proxyURL)
}).ExpectResp([]byte("test")).Ensure()
})
ginkgo.It("stcp", func() {
sshPort := f.AllocPort()
serverConf := consts.DefaultServerConfig + fmt.Sprintf(`
sshTunnelGateway.bindPort = %d
`, sshPort)
bindPort := f.AllocPort()
visitorConf := consts.DefaultClientConfig + fmt.Sprintf(`
[[visitors]]
name = "stcp-test-visitor"
type = "stcp"
serverName = "stcp-test"
secretKey = "abcdefg"
bindPort = %d
`, bindPort)
f.RunProcesses([]string{serverConf}, []string{visitorConf})
localPort := f.PortByName(framework.TCPEchoServerPort)
tc := ssh.NewTunnelClient(
fmt.Sprintf("127.0.0.1:%d", localPort),
fmt.Sprintf("127.0.0.1:%d", sshPort),
"stcp -n stcp-test --sk=abcdefg --allow-users=\"*\"",
)
framework.ExpectNoError(tc.Start())
defer tc.Close()
time.Sleep(time.Second)
framework.NewRequestExpect(f).
Port(bindPort).
Ensure()
})
})
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/v1/features/heartbeat.go | test/e2e/v1/features/heartbeat.go | package features
import (
"fmt"
"time"
"github.com/onsi/ginkgo/v2"
"github.com/fatedier/frp/test/e2e/framework"
)
var _ = ginkgo.Describe("[Feature: Heartbeat]", func() {
f := framework.NewDefaultFramework()
ginkgo.It("disable application layer heartbeat", func() {
serverPort := f.AllocPort()
serverConf := fmt.Sprintf(`
bindAddr = "0.0.0.0"
bindPort = %d
transport.heartbeatTimeout = -1
transport.tcpMuxKeepaliveInterval = 2
`, serverPort)
remotePort := f.AllocPort()
clientConf := fmt.Sprintf(`
serverPort = %d
log.level = "trace"
transport.heartbeatInterval = -1
transport.heartbeatTimeout = -1
transport.tcpMuxKeepaliveInterval = 2
[[proxies]]
name = "tcp"
type = "tcp"
localPort = %d
remotePort = %d
`, serverPort, f.PortByName(framework.TCPEchoServerPort), remotePort)
// run frps and frpc
f.RunProcesses([]string{serverConf}, []string{clientConf})
framework.NewRequestExpect(f).Protocol("tcp").Port(remotePort).Ensure()
time.Sleep(5 * time.Second)
framework.NewRequestExpect(f).Protocol("tcp").Port(remotePort).Ensure()
})
})
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/v1/features/bandwidth_limit.go | test/e2e/v1/features/bandwidth_limit.go | package features
import (
"fmt"
"strings"
"time"
"github.com/onsi/ginkgo/v2"
plugin "github.com/fatedier/frp/pkg/plugin/server"
"github.com/fatedier/frp/test/e2e/framework"
"github.com/fatedier/frp/test/e2e/framework/consts"
"github.com/fatedier/frp/test/e2e/mock/server/streamserver"
pluginpkg "github.com/fatedier/frp/test/e2e/pkg/plugin"
"github.com/fatedier/frp/test/e2e/pkg/request"
)
var _ = ginkgo.Describe("[Feature: Bandwidth Limit]", func() {
f := framework.NewDefaultFramework()
ginkgo.It("Proxy Bandwidth Limit by Client", func() {
serverConf := consts.DefaultServerConfig
clientConf := consts.DefaultClientConfig
localPort := f.AllocPort()
localServer := streamserver.New(streamserver.TCP, streamserver.WithBindPort(localPort))
f.RunServer("", localServer)
remotePort := f.AllocPort()
clientConf += fmt.Sprintf(`
[[proxies]]
name = "tcp"
type = "tcp"
localPort = %d
remotePort = %d
transport.bandwidthLimit = "10KB"
`, localPort, remotePort)
f.RunProcesses([]string{serverConf}, []string{clientConf})
content := strings.Repeat("a", 50*1024) // 5KB
start := time.Now()
framework.NewRequestExpect(f).Port(remotePort).RequestModify(func(r *request.Request) {
r.Body([]byte(content)).Timeout(30 * time.Second)
}).ExpectResp([]byte(content)).Ensure()
duration := time.Since(start)
framework.Logf("request duration: %s", duration.String())
framework.ExpectTrue(duration.Seconds() > 8, "100Kb with 10KB limit, want > 8 seconds, but got %s", duration.String())
})
ginkgo.It("Proxy Bandwidth Limit by Server", func() {
// new test plugin server
newFunc := func() *plugin.Request {
var r plugin.Request
r.Content = &plugin.NewProxyContent{}
return &r
}
pluginPort := f.AllocPort()
handler := func(req *plugin.Request) *plugin.Response {
var ret plugin.Response
content := req.Content.(*plugin.NewProxyContent)
content.BandwidthLimit = "10KB"
content.BandwidthLimitMode = "server"
ret.Content = content
return &ret
}
pluginServer := pluginpkg.NewHTTPPluginServer(pluginPort, newFunc, handler, nil)
f.RunServer("", pluginServer)
serverConf := consts.DefaultServerConfig + fmt.Sprintf(`
[[httpPlugins]]
name = "test"
addr = "127.0.0.1:%d"
path = "/handler"
ops = ["NewProxy"]
`, pluginPort)
clientConf := consts.DefaultClientConfig
localPort := f.AllocPort()
localServer := streamserver.New(streamserver.TCP, streamserver.WithBindPort(localPort))
f.RunServer("", localServer)
remotePort := f.AllocPort()
clientConf += fmt.Sprintf(`
[[proxies]]
name = "tcp"
type = "tcp"
localPort = %d
remotePort = %d
`, localPort, remotePort)
f.RunProcesses([]string{serverConf}, []string{clientConf})
content := strings.Repeat("a", 50*1024) // 5KB
start := time.Now()
framework.NewRequestExpect(f).Port(remotePort).RequestModify(func(r *request.Request) {
r.Body([]byte(content)).Timeout(30 * time.Second)
}).ExpectResp([]byte(content)).Ensure()
duration := time.Since(start)
framework.Logf("request duration: %s", duration.String())
framework.ExpectTrue(duration.Seconds() > 8, "100Kb with 10KB limit, want > 8 seconds, but got %s", duration.String())
})
})
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/v1/features/group.go | test/e2e/v1/features/group.go | package features
import (
"crypto/tls"
"fmt"
"strconv"
"sync"
"time"
"github.com/onsi/ginkgo/v2"
"github.com/fatedier/frp/pkg/transport"
"github.com/fatedier/frp/test/e2e/framework"
"github.com/fatedier/frp/test/e2e/framework/consts"
"github.com/fatedier/frp/test/e2e/mock/server/httpserver"
"github.com/fatedier/frp/test/e2e/mock/server/streamserver"
"github.com/fatedier/frp/test/e2e/pkg/request"
)
var _ = ginkgo.Describe("[Feature: Group]", func() {
f := framework.NewDefaultFramework()
newHTTPServer := func(port int, respContent string) *httpserver.Server {
return httpserver.New(
httpserver.WithBindPort(port),
httpserver.WithHandler(framework.SpecifiedHTTPBodyHandler([]byte(respContent))),
)
}
validateFooBarResponse := func(resp *request.Response) bool {
if string(resp.Content) == "foo" || string(resp.Content) == "bar" {
return true
}
return false
}
doFooBarHTTPRequest := func(vhostPort int, host string) []string {
results := []string{}
var wait sync.WaitGroup
var mu sync.Mutex
expectFn := func() {
framework.NewRequestExpect(f).Port(vhostPort).
RequestModify(func(r *request.Request) {
r.HTTP().HTTPHost(host)
}).
Ensure(validateFooBarResponse, func(resp *request.Response) bool {
mu.Lock()
defer mu.Unlock()
results = append(results, string(resp.Content))
return true
})
}
for i := 0; i < 10; i++ {
wait.Add(1)
go func() {
defer wait.Done()
expectFn()
}()
}
wait.Wait()
return results
}
ginkgo.Describe("Load Balancing", func() {
ginkgo.It("TCP", func() {
serverConf := consts.DefaultServerConfig
clientConf := consts.DefaultClientConfig
fooPort := f.AllocPort()
fooServer := streamserver.New(streamserver.TCP, streamserver.WithBindPort(fooPort), streamserver.WithRespContent([]byte("foo")))
f.RunServer("", fooServer)
barPort := f.AllocPort()
barServer := streamserver.New(streamserver.TCP, streamserver.WithBindPort(barPort), streamserver.WithRespContent([]byte("bar")))
f.RunServer("", barServer)
remotePort := f.AllocPort()
clientConf += fmt.Sprintf(`
[[proxies]]
name = "foo"
type = "tcp"
localPort = %d
remotePort = %d
loadBalancer.group = "test"
loadBalancer.groupKey = "123"
[[proxies]]
name = "bar"
type = "tcp"
localPort = %d
remotePort = %d
loadBalancer.group = "test"
loadBalancer.groupKey = "123"
`, fooPort, remotePort, barPort, remotePort)
f.RunProcesses([]string{serverConf}, []string{clientConf})
fooCount := 0
barCount := 0
for i := 0; i < 10; i++ {
framework.NewRequestExpect(f).Explain("times " + strconv.Itoa(i)).Port(remotePort).Ensure(func(resp *request.Response) bool {
switch string(resp.Content) {
case "foo":
fooCount++
case "bar":
barCount++
default:
return false
}
return true
})
}
framework.ExpectTrue(fooCount > 1 && barCount > 1, "fooCount: %d, barCount: %d", fooCount, barCount)
})
ginkgo.It("HTTPS", func() {
vhostHTTPSPort := f.AllocPort()
serverConf := consts.DefaultServerConfig + fmt.Sprintf(`
vhostHTTPSPort = %d
`, vhostHTTPSPort)
clientConf := consts.DefaultClientConfig
tlsConfig, err := transport.NewServerTLSConfig("", "", "")
framework.ExpectNoError(err)
fooPort := f.AllocPort()
fooServer := httpserver.New(
httpserver.WithBindPort(fooPort),
httpserver.WithHandler(framework.SpecifiedHTTPBodyHandler([]byte("foo"))),
httpserver.WithTLSConfig(tlsConfig),
)
f.RunServer("", fooServer)
barPort := f.AllocPort()
barServer := httpserver.New(
httpserver.WithBindPort(barPort),
httpserver.WithHandler(framework.SpecifiedHTTPBodyHandler([]byte("bar"))),
httpserver.WithTLSConfig(tlsConfig),
)
f.RunServer("", barServer)
clientConf += fmt.Sprintf(`
[[proxies]]
name = "foo"
type = "https"
localPort = %d
customDomains = ["example.com"]
loadBalancer.group = "test"
loadBalancer.groupKey = "123"
[[proxies]]
name = "bar"
type = "https"
localPort = %d
customDomains = ["example.com"]
loadBalancer.group = "test"
loadBalancer.groupKey = "123"
`, fooPort, barPort)
f.RunProcesses([]string{serverConf}, []string{clientConf})
fooCount := 0
barCount := 0
for i := 0; i < 10; i++ {
framework.NewRequestExpect(f).
Explain("times " + strconv.Itoa(i)).
Port(vhostHTTPSPort).
RequestModify(func(r *request.Request) {
r.HTTPS().HTTPHost("example.com").TLSConfig(&tls.Config{
ServerName: "example.com",
InsecureSkipVerify: true,
})
}).
Ensure(func(resp *request.Response) bool {
switch string(resp.Content) {
case "foo":
fooCount++
case "bar":
barCount++
default:
return false
}
return true
})
}
framework.ExpectTrue(fooCount > 1 && barCount > 1, "fooCount: %d, barCount: %d", fooCount, barCount)
})
})
ginkgo.Describe("Health Check", func() {
ginkgo.It("TCP", func() {
serverConf := consts.DefaultServerConfig
clientConf := consts.DefaultClientConfig
fooPort := f.AllocPort()
fooServer := streamserver.New(streamserver.TCP, streamserver.WithBindPort(fooPort), streamserver.WithRespContent([]byte("foo")))
f.RunServer("", fooServer)
barPort := f.AllocPort()
barServer := streamserver.New(streamserver.TCP, streamserver.WithBindPort(barPort), streamserver.WithRespContent([]byte("bar")))
f.RunServer("", barServer)
remotePort := f.AllocPort()
clientConf += fmt.Sprintf(`
[[proxies]]
name = "foo"
type = "tcp"
localPort = %d
remotePort = %d
loadBalancer.group = "test"
loadBalancer.groupKey = "123"
healthCheck.type = "tcp"
healthCheck.intervalSeconds = 1
[[proxies]]
name = "bar"
type = "tcp"
localPort = %d
remotePort = %d
loadBalancer.group = "test"
loadBalancer.groupKey = "123"
healthCheck.type = "tcp"
healthCheck.intervalSeconds = 1
`, fooPort, remotePort, barPort, remotePort)
f.RunProcesses([]string{serverConf}, []string{clientConf})
// check foo and bar is ok
results := []string{}
for i := 0; i < 10; i++ {
framework.NewRequestExpect(f).Port(remotePort).Ensure(validateFooBarResponse, func(resp *request.Response) bool {
results = append(results, string(resp.Content))
return true
})
}
framework.ExpectContainElements(results, []string{"foo", "bar"})
// close bar server, check foo is ok
barServer.Close()
time.Sleep(2 * time.Second)
for i := 0; i < 10; i++ {
framework.NewRequestExpect(f).Port(remotePort).ExpectResp([]byte("foo")).Ensure()
}
// resume bar server, check foo and bar is ok
f.RunServer("", barServer)
time.Sleep(2 * time.Second)
results = []string{}
for i := 0; i < 10; i++ {
framework.NewRequestExpect(f).Port(remotePort).Ensure(validateFooBarResponse, func(resp *request.Response) bool {
results = append(results, string(resp.Content))
return true
})
}
framework.ExpectContainElements(results, []string{"foo", "bar"})
})
ginkgo.It("HTTP", func() {
vhostPort := f.AllocPort()
serverConf := consts.DefaultServerConfig + fmt.Sprintf(`
vhostHTTPPort = %d
`, vhostPort)
clientConf := consts.DefaultClientConfig
fooPort := f.AllocPort()
fooServer := newHTTPServer(fooPort, "foo")
f.RunServer("", fooServer)
barPort := f.AllocPort()
barServer := newHTTPServer(barPort, "bar")
f.RunServer("", barServer)
clientConf += fmt.Sprintf(`
[[proxies]]
name = "foo"
type = "http"
localPort = %d
customDomains = ["example.com"]
loadBalancer.group = "test"
loadBalancer.groupKey = "123"
healthCheck.type = "http"
healthCheck.intervalSeconds = 1
healthCheck.path = "/healthz"
[[proxies]]
name = "bar"
type = "http"
localPort = %d
customDomains = ["example.com"]
loadBalancer.group = "test"
loadBalancer.groupKey = "123"
healthCheck.type = "http"
healthCheck.intervalSeconds = 1
healthCheck.path = "/healthz"
`, fooPort, barPort)
f.RunProcesses([]string{serverConf}, []string{clientConf})
// send first HTTP request
var contents []string
framework.NewRequestExpect(f).Port(vhostPort).
RequestModify(func(r *request.Request) {
r.HTTP().HTTPHost("example.com")
}).
Ensure(func(resp *request.Response) bool {
contents = append(contents, string(resp.Content))
return true
})
// send second HTTP request, should be forwarded to another service
framework.NewRequestExpect(f).Port(vhostPort).
RequestModify(func(r *request.Request) {
r.HTTP().HTTPHost("example.com")
}).
Ensure(func(resp *request.Response) bool {
contents = append(contents, string(resp.Content))
return true
})
framework.ExpectContainElements(contents, []string{"foo", "bar"})
// check foo and bar is ok
results := doFooBarHTTPRequest(vhostPort, "example.com")
framework.ExpectContainElements(results, []string{"foo", "bar"})
// close bar server, check foo is ok
barServer.Close()
time.Sleep(2 * time.Second)
results = doFooBarHTTPRequest(vhostPort, "example.com")
framework.ExpectContainElements(results, []string{"foo"})
framework.ExpectNotContainElements(results, []string{"bar"})
// resume bar server, check foo and bar is ok
f.RunServer("", barServer)
time.Sleep(2 * time.Second)
results = doFooBarHTTPRequest(vhostPort, "example.com")
framework.ExpectContainElements(results, []string{"foo", "bar"})
})
})
})
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/v1/features/real_ip.go | test/e2e/v1/features/real_ip.go | package features
import (
"bufio"
"crypto/tls"
"fmt"
"net"
"net/http"
"github.com/onsi/ginkgo/v2"
pp "github.com/pires/go-proxyproto"
"github.com/fatedier/frp/pkg/transport"
"github.com/fatedier/frp/pkg/util/log"
"github.com/fatedier/frp/test/e2e/framework"
"github.com/fatedier/frp/test/e2e/framework/consts"
"github.com/fatedier/frp/test/e2e/mock/server/httpserver"
"github.com/fatedier/frp/test/e2e/mock/server/streamserver"
"github.com/fatedier/frp/test/e2e/pkg/request"
"github.com/fatedier/frp/test/e2e/pkg/rpc"
)
var _ = ginkgo.Describe("[Feature: Real IP]", func() {
f := framework.NewDefaultFramework()
ginkgo.Describe("HTTP X-forwarded-For", func() {
ginkgo.It("Client Without Header", func() {
vhostHTTPPort := f.AllocPort()
serverConf := consts.DefaultServerConfig + fmt.Sprintf(`
vhostHTTPPort = %d
`, vhostHTTPPort)
localPort := f.AllocPort()
localServer := httpserver.New(
httpserver.WithBindPort(localPort),
httpserver.WithHandler(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
_, _ = w.Write([]byte(req.Header.Get("X-Forwarded-For")))
})),
)
f.RunServer("", localServer)
clientConf := consts.DefaultClientConfig
clientConf += fmt.Sprintf(`
[[proxies]]
name = "test"
type = "http"
localPort = %d
customDomains = ["normal.example.com"]
`, localPort)
f.RunProcesses([]string{serverConf}, []string{clientConf})
framework.NewRequestExpect(f).Port(vhostHTTPPort).
RequestModify(func(r *request.Request) {
r.HTTP().HTTPHost("normal.example.com")
}).
ExpectResp([]byte("127.0.0.1")).
Ensure()
})
ginkgo.It("Client With Header", func() {
vhostHTTPPort := f.AllocPort()
serverConf := consts.DefaultServerConfig + fmt.Sprintf(`
vhostHTTPPort = %d
`, vhostHTTPPort)
localPort := f.AllocPort()
localServer := httpserver.New(
httpserver.WithBindPort(localPort),
httpserver.WithHandler(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
_, _ = w.Write([]byte(req.Header.Get("X-Forwarded-For")))
})),
)
f.RunServer("", localServer)
clientConf := consts.DefaultClientConfig
clientConf += fmt.Sprintf(`
[[proxies]]
name = "test"
type = "http"
localPort = %d
customDomains = ["normal.example.com"]
`, localPort)
f.RunProcesses([]string{serverConf}, []string{clientConf})
framework.NewRequestExpect(f).Port(vhostHTTPPort).
RequestModify(func(r *request.Request) {
r.HTTP().HTTPHost("normal.example.com")
r.HTTP().HTTPHeaders(map[string]string{"x-forwarded-for": "2.2.2.2"})
}).
ExpectResp([]byte("2.2.2.2, 127.0.0.1")).
Ensure()
})
ginkgo.It("http2https plugin", func() {
vhostHTTPPort := f.AllocPort()
serverConf := consts.DefaultServerConfig + fmt.Sprintf(`
vhostHTTPPort = %d
`, vhostHTTPPort)
localPort := f.AllocPort()
clientConf := consts.DefaultClientConfig
clientConf += fmt.Sprintf(`
[[proxies]]
name = "test"
type = "http"
customDomains = ["normal.example.com"]
[proxies.plugin]
type = "http2https"
localAddr = "127.0.0.1:%d"
`, localPort)
f.RunProcesses([]string{serverConf}, []string{clientConf})
tlsConfig, err := transport.NewServerTLSConfig("", "", "")
framework.ExpectNoError(err)
localServer := httpserver.New(
httpserver.WithBindPort(localPort),
httpserver.WithHandler(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
_, _ = w.Write([]byte(req.Header.Get("X-Forwarded-For")))
})),
httpserver.WithTLSConfig(tlsConfig),
)
f.RunServer("", localServer)
framework.NewRequestExpect(f).Port(vhostHTTPPort).
RequestModify(func(r *request.Request) {
r.HTTP().HTTPHost("normal.example.com")
r.HTTP().HTTPHeaders(map[string]string{"x-forwarded-for": "2.2.2.2, 3.3.3.3"})
}).
ExpectResp([]byte("2.2.2.2, 3.3.3.3, 127.0.0.1")).
Ensure()
})
ginkgo.It("https2http plugin", func() {
vhostHTTPSPort := f.AllocPort()
serverConf := consts.DefaultServerConfig + fmt.Sprintf(`
vhostHTTPSPort = %d
`, vhostHTTPSPort)
localPort := f.AllocPort()
clientConf := consts.DefaultClientConfig
clientConf += fmt.Sprintf(`
[[proxies]]
name = "test"
type = "https"
customDomains = ["normal.example.com"]
[proxies.plugin]
type = "https2http"
localAddr = "127.0.0.1:%d"
`, localPort)
f.RunProcesses([]string{serverConf}, []string{clientConf})
localServer := httpserver.New(
httpserver.WithBindPort(localPort),
httpserver.WithHandler(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
_, _ = w.Write([]byte(req.Header.Get("X-Forwarded-For")))
})),
)
f.RunServer("", localServer)
framework.NewRequestExpect(f).Port(vhostHTTPSPort).
RequestModify(func(r *request.Request) {
r.HTTPS().HTTPHost("normal.example.com").
HTTPHeaders(map[string]string{"x-forwarded-for": "2.2.2.2"}).
TLSConfig(&tls.Config{ServerName: "normal.example.com", InsecureSkipVerify: true})
}).
ExpectResp([]byte("2.2.2.2, 127.0.0.1")).
Ensure()
})
})
ginkgo.Describe("Proxy Protocol", func() {
ginkgo.It("TCP", func() {
serverConf := consts.DefaultServerConfig
clientConf := consts.DefaultClientConfig
localPort := f.AllocPort()
localServer := streamserver.New(streamserver.TCP, streamserver.WithBindPort(localPort),
streamserver.WithCustomHandler(func(c net.Conn) {
defer c.Close()
rd := bufio.NewReader(c)
ppHeader, err := pp.Read(rd)
if err != nil {
log.Errorf("read proxy protocol error: %v", err)
return
}
for {
if _, err := rpc.ReadBytes(rd); err != nil {
return
}
buf := []byte(ppHeader.SourceAddr.String())
_, _ = rpc.WriteBytes(c, buf)
}
}))
f.RunServer("", localServer)
remotePort := f.AllocPort()
clientConf += fmt.Sprintf(`
[[proxies]]
name = "tcp"
type = "tcp"
localPort = %d
remotePort = %d
transport.proxyProtocolVersion = "v2"
`, localPort, remotePort)
f.RunProcesses([]string{serverConf}, []string{clientConf})
framework.NewRequestExpect(f).Port(remotePort).Ensure(func(resp *request.Response) bool {
log.Tracef("proxy protocol get SourceAddr: %s", string(resp.Content))
addr, err := net.ResolveTCPAddr("tcp", string(resp.Content))
if err != nil {
return false
}
if addr.IP.String() != "127.0.0.1" {
return false
}
return true
})
})
ginkgo.It("UDP", func() {
serverConf := consts.DefaultServerConfig
clientConf := consts.DefaultClientConfig
localPort := f.AllocPort()
localServer := streamserver.New(streamserver.UDP, streamserver.WithBindPort(localPort),
streamserver.WithCustomHandler(func(c net.Conn) {
defer c.Close()
rd := bufio.NewReader(c)
ppHeader, err := pp.Read(rd)
if err != nil {
log.Errorf("read proxy protocol error: %v", err)
return
}
// Read the actual UDP content after proxy protocol header
if _, err := rpc.ReadBytes(rd); err != nil {
return
}
buf := []byte(ppHeader.SourceAddr.String())
_, _ = rpc.WriteBytes(c, buf)
}))
f.RunServer("", localServer)
remotePort := f.AllocPort()
clientConf += fmt.Sprintf(`
[[proxies]]
name = "udp"
type = "udp"
localPort = %d
remotePort = %d
transport.proxyProtocolVersion = "v2"
`, localPort, remotePort)
f.RunProcesses([]string{serverConf}, []string{clientConf})
framework.NewRequestExpect(f).Protocol("udp").Port(remotePort).Ensure(func(resp *request.Response) bool {
log.Tracef("udp proxy protocol get SourceAddr: %s", string(resp.Content))
addr, err := net.ResolveUDPAddr("udp", string(resp.Content))
if err != nil {
return false
}
if addr.IP.String() != "127.0.0.1" {
return false
}
return true
})
})
ginkgo.It("HTTP", func() {
vhostHTTPPort := f.AllocPort()
serverConf := consts.DefaultServerConfig + fmt.Sprintf(`
vhostHTTPPort = %d
`, vhostHTTPPort)
clientConf := consts.DefaultClientConfig
localPort := f.AllocPort()
var srcAddrRecord string
localServer := streamserver.New(streamserver.TCP, streamserver.WithBindPort(localPort),
streamserver.WithCustomHandler(func(c net.Conn) {
defer c.Close()
rd := bufio.NewReader(c)
ppHeader, err := pp.Read(rd)
if err != nil {
log.Errorf("read proxy protocol error: %v", err)
return
}
srcAddrRecord = ppHeader.SourceAddr.String()
}))
f.RunServer("", localServer)
clientConf += fmt.Sprintf(`
[[proxies]]
name = "test"
type = "http"
localPort = %d
customDomains = ["normal.example.com"]
transport.proxyProtocolVersion = "v2"
`, localPort)
f.RunProcesses([]string{serverConf}, []string{clientConf})
framework.NewRequestExpect(f).Port(vhostHTTPPort).RequestModify(func(r *request.Request) {
r.HTTP().HTTPHost("normal.example.com")
}).Ensure(framework.ExpectResponseCode(404))
log.Tracef("proxy protocol get SourceAddr: %s", srcAddrRecord)
addr, err := net.ResolveTCPAddr("tcp", srcAddrRecord)
framework.ExpectNoError(err, srcAddrRecord)
framework.ExpectEqualValues("127.0.0.1", addr.IP.String())
})
})
})
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/v1/features/monitor.go | test/e2e/v1/features/monitor.go | package features
import (
"fmt"
"strings"
"time"
"github.com/onsi/ginkgo/v2"
"github.com/fatedier/frp/pkg/util/log"
"github.com/fatedier/frp/test/e2e/framework"
"github.com/fatedier/frp/test/e2e/framework/consts"
"github.com/fatedier/frp/test/e2e/pkg/request"
)
var _ = ginkgo.Describe("[Feature: Monitor]", func() {
f := framework.NewDefaultFramework()
ginkgo.It("Prometheus metrics", func() {
dashboardPort := f.AllocPort()
serverConf := consts.DefaultServerConfig + fmt.Sprintf(`
enablePrometheus = true
webServer.addr = "0.0.0.0"
webServer.port = %d
`, dashboardPort)
clientConf := consts.DefaultClientConfig
remotePort := f.AllocPort()
clientConf += fmt.Sprintf(`
[[proxies]]
name = "tcp"
type = "tcp"
localPort = {{ .%s }}
remotePort = %d
`, framework.TCPEchoServerPort, remotePort)
f.RunProcesses([]string{serverConf}, []string{clientConf})
framework.NewRequestExpect(f).Port(remotePort).Ensure()
time.Sleep(500 * time.Millisecond)
framework.NewRequestExpect(f).RequestModify(func(r *request.Request) {
r.HTTP().Port(dashboardPort).HTTPPath("/metrics")
}).Ensure(func(resp *request.Response) bool {
log.Tracef("prometheus metrics response: \n%s", resp.Content)
if resp.Code != 200 {
return false
}
if !strings.Contains(string(resp.Content), "traffic_in") {
return false
}
return true
})
})
})
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/framework/cleanup.go | test/e2e/framework/cleanup.go | package framework
import (
"sync"
)
// CleanupActionHandle is an integer pointer type for handling cleanup action
type CleanupActionHandle *int
type cleanupFuncHandle struct {
actionHandle CleanupActionHandle
actionHook func()
}
var (
cleanupActionsLock sync.Mutex
cleanupHookList = []cleanupFuncHandle{}
)
// AddCleanupAction installs a function that will be called in the event of the
// whole test being terminated. This allows arbitrary pieces of the overall
// test to hook into SynchronizedAfterSuite().
// The hooks are called in last-in-first-out order.
func AddCleanupAction(fn func()) CleanupActionHandle {
p := CleanupActionHandle(new(int))
cleanupActionsLock.Lock()
defer cleanupActionsLock.Unlock()
c := cleanupFuncHandle{actionHandle: p, actionHook: fn}
cleanupHookList = append([]cleanupFuncHandle{c}, cleanupHookList...)
return p
}
// RemoveCleanupAction removes a function that was installed by
// AddCleanupAction.
func RemoveCleanupAction(p CleanupActionHandle) {
cleanupActionsLock.Lock()
defer cleanupActionsLock.Unlock()
for i, item := range cleanupHookList {
if item.actionHandle == p {
cleanupHookList = append(cleanupHookList[:i], cleanupHookList[i+1:]...)
break
}
}
}
// RunCleanupActions runs all functions installed by AddCleanupAction. It does
// not remove them (see RemoveCleanupAction) but it does run unlocked, so they
// may remove themselves.
func RunCleanupActions() {
list := []func(){}
func() {
cleanupActionsLock.Lock()
defer cleanupActionsLock.Unlock()
for _, p := range cleanupHookList {
list = append(list, p.actionHook)
}
}()
// Run unlocked.
for _, fn := range list {
fn()
}
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/framework/request.go | test/e2e/framework/request.go | package framework
import (
"bytes"
"net/http"
flog "github.com/fatedier/frp/pkg/util/log"
"github.com/fatedier/frp/test/e2e/framework/consts"
"github.com/fatedier/frp/test/e2e/pkg/request"
)
func SpecifiedHTTPBodyHandler(body []byte) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
_, _ = w.Write(body)
}
}
func ExpectResponseCode(code int) EnsureFunc {
return func(resp *request.Response) bool {
if resp.Code == code {
return true
}
flog.Warnf("expect code %d, but got %d", code, resp.Code)
return false
}
}
// NewRequest return a default request with default timeout and content.
func NewRequest() *request.Request {
return request.New().
Timeout(consts.DefaultTimeout).
Body([]byte(consts.TestString))
}
func NewHTTPRequest() *request.Request {
return request.New().HTTP().HTTPParams("GET", "", "/", nil)
}
type RequestExpect struct {
req *request.Request
f *Framework
expectResp []byte
expectError bool
explain []any
}
func NewRequestExpect(f *Framework) *RequestExpect {
return &RequestExpect{
req: NewRequest(),
f: f,
expectResp: []byte(consts.TestString),
expectError: false,
explain: make([]any, 0),
}
}
func (e *RequestExpect) Request(req *request.Request) *RequestExpect {
e.req = req
return e
}
func (e *RequestExpect) RequestModify(f func(r *request.Request)) *RequestExpect {
f(e.req)
return e
}
func (e *RequestExpect) Protocol(protocol string) *RequestExpect {
e.req.Protocol(protocol)
return e
}
func (e *RequestExpect) PortName(name string) *RequestExpect {
if e.f != nil {
e.req.Port(e.f.PortByName(name))
}
return e
}
func (e *RequestExpect) Port(port int) *RequestExpect {
if e.f != nil {
e.req.Port(port)
}
return e
}
func (e *RequestExpect) ExpectResp(resp []byte) *RequestExpect {
e.expectResp = resp
return e
}
func (e *RequestExpect) ExpectError(expectErr bool) *RequestExpect {
e.expectError = expectErr
return e
}
func (e *RequestExpect) Explain(explain ...any) *RequestExpect {
e.explain = explain
return e
}
type EnsureFunc func(*request.Response) bool
func (e *RequestExpect) Ensure(fns ...EnsureFunc) {
ret, err := e.req.Do()
if e.expectError {
ExpectErrorWithOffset(1, err, e.explain...)
return
}
ExpectNoErrorWithOffset(1, err, e.explain...)
if len(fns) == 0 {
if !bytes.Equal(e.expectResp, ret.Content) {
flog.Tracef("response info: %+v", ret)
}
ExpectEqualValuesWithOffset(1, string(ret.Content), string(e.expectResp), e.explain...)
} else {
for _, fn := range fns {
ok := fn(ret)
if !ok {
flog.Tracef("response info: %+v", ret)
}
ExpectTrueWithOffset(1, ok, e.explain...)
}
}
}
func (e *RequestExpect) Do() (*request.Response, error) {
return e.req.Do()
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/framework/mockservers.go | test/e2e/framework/mockservers.go | package framework
import (
"fmt"
"net/http"
"os"
"github.com/fatedier/frp/test/e2e/framework/consts"
"github.com/fatedier/frp/test/e2e/mock/server"
"github.com/fatedier/frp/test/e2e/mock/server/httpserver"
"github.com/fatedier/frp/test/e2e/mock/server/streamserver"
"github.com/fatedier/frp/test/e2e/pkg/port"
)
const (
TCPEchoServerPort = "TCPEchoServerPort"
UDPEchoServerPort = "UDPEchoServerPort"
UDSEchoServerAddr = "UDSEchoServerAddr"
HTTPSimpleServerPort = "HTTPSimpleServerPort"
)
type MockServers struct {
tcpEchoServer server.Server
udpEchoServer server.Server
udsEchoServer server.Server
httpSimpleServer server.Server
}
func NewMockServers(portAllocator *port.Allocator) *MockServers {
s := &MockServers{}
tcpPort := portAllocator.Get()
udpPort := portAllocator.Get()
httpPort := portAllocator.Get()
s.tcpEchoServer = streamserver.New(streamserver.TCP, streamserver.WithBindPort(tcpPort))
s.udpEchoServer = streamserver.New(streamserver.UDP, streamserver.WithBindPort(udpPort))
s.httpSimpleServer = httpserver.New(httpserver.WithBindPort(httpPort),
httpserver.WithHandler(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
_, _ = w.Write([]byte(consts.TestString))
})),
)
udsIndex := portAllocator.Get()
udsAddr := fmt.Sprintf("%s/frp_echo_server_%d.sock", os.TempDir(), udsIndex)
os.Remove(udsAddr)
s.udsEchoServer = streamserver.New(streamserver.Unix, streamserver.WithBindAddr(udsAddr))
return s
}
func (m *MockServers) Run() error {
if err := m.tcpEchoServer.Run(); err != nil {
return err
}
if err := m.udpEchoServer.Run(); err != nil {
return err
}
if err := m.udsEchoServer.Run(); err != nil {
return err
}
return m.httpSimpleServer.Run()
}
func (m *MockServers) Close() {
m.tcpEchoServer.Close()
m.udpEchoServer.Close()
m.udsEchoServer.Close()
m.httpSimpleServer.Close()
os.Remove(m.udsEchoServer.BindAddr())
}
func (m *MockServers) GetTemplateParams() map[string]any {
ret := make(map[string]any)
ret[TCPEchoServerPort] = m.tcpEchoServer.BindPort()
ret[UDPEchoServerPort] = m.udpEchoServer.BindPort()
ret[UDSEchoServerAddr] = m.udsEchoServer.BindAddr()
ret[HTTPSimpleServerPort] = m.httpSimpleServer.BindPort()
return ret
}
func (m *MockServers) GetParam(key string) any {
params := m.GetTemplateParams()
if v, ok := params[key]; ok {
return v
}
return nil
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/framework/expect.go | test/e2e/framework/expect.go | package framework
import (
"github.com/onsi/gomega"
)
// ExpectEqual expects the specified two are the same, otherwise an exception raises
func ExpectEqual(actual any, extra any, explain ...any) {
gomega.ExpectWithOffset(1, actual).To(gomega.Equal(extra), explain...)
}
// ExpectEqualValues expects the specified two are the same, it not strict about type
func ExpectEqualValues(actual any, extra any, explain ...any) {
gomega.ExpectWithOffset(1, actual).To(gomega.BeEquivalentTo(extra), explain...)
}
func ExpectEqualValuesWithOffset(offset int, actual any, extra any, explain ...any) {
gomega.ExpectWithOffset(1+offset, actual).To(gomega.BeEquivalentTo(extra), explain...)
}
// ExpectNotEqual expects the specified two are not the same, otherwise an exception raises
func ExpectNotEqual(actual any, extra any, explain ...any) {
gomega.ExpectWithOffset(1, actual).NotTo(gomega.Equal(extra), explain...)
}
// ExpectError expects an error happens, otherwise an exception raises
func ExpectError(err error, explain ...any) {
gomega.ExpectWithOffset(1, err).To(gomega.HaveOccurred(), explain...)
}
func ExpectErrorWithOffset(offset int, err error, explain ...any) {
gomega.ExpectWithOffset(1+offset, err).To(gomega.HaveOccurred(), explain...)
}
// ExpectNoError checks if "err" is set, and if so, fails assertion while logging the error.
func ExpectNoError(err error, explain ...any) {
ExpectNoErrorWithOffset(1, err, explain...)
}
// ExpectNoErrorWithOffset checks if "err" is set, and if so, fails assertion while logging the error at "offset" levels above its caller
// (for example, for call chain f -> g -> ExpectNoErrorWithOffset(1, ...) error would be logged for "f").
func ExpectNoErrorWithOffset(offset int, err error, explain ...any) {
gomega.ExpectWithOffset(1+offset, err).NotTo(gomega.HaveOccurred(), explain...)
}
func ExpectContainSubstring(actual, substr string, explain ...any) {
gomega.ExpectWithOffset(1, actual).To(gomega.ContainSubstring(substr), explain...)
}
// ExpectConsistOf expects actual contains precisely the extra elements. The ordering of the elements does not matter.
func ExpectConsistOf(actual any, extra any, explain ...any) {
gomega.ExpectWithOffset(1, actual).To(gomega.ConsistOf(extra), explain...)
}
func ExpectContainElements(actual any, extra any, explain ...any) {
gomega.ExpectWithOffset(1, actual).To(gomega.ContainElements(extra), explain...)
}
func ExpectNotContainElements(actual any, extra any, explain ...any) {
gomega.ExpectWithOffset(1, actual).NotTo(gomega.ContainElements(extra), explain...)
}
// ExpectHaveKey expects the actual map has the key in the keyset
func ExpectHaveKey(actual any, key any, explain ...any) {
gomega.ExpectWithOffset(1, actual).To(gomega.HaveKey(key), explain...)
}
// ExpectEmpty expects actual is empty
func ExpectEmpty(actual any, explain ...any) {
gomega.ExpectWithOffset(1, actual).To(gomega.BeEmpty(), explain...)
}
func ExpectTrue(actual any, explain ...any) {
gomega.ExpectWithOffset(1, actual).Should(gomega.BeTrue(), explain...)
}
func ExpectTrueWithOffset(offset int, actual any, explain ...any) {
gomega.ExpectWithOffset(1+offset, actual).Should(gomega.BeTrue(), explain...)
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/framework/client.go | test/e2e/framework/client.go | package framework
import (
clientsdk "github.com/fatedier/frp/pkg/sdk/client"
)
func (f *Framework) APIClientForFrpc(port int) *clientsdk.Client {
return clientsdk.New("127.0.0.1", port)
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/framework/test_context.go | test/e2e/framework/test_context.go | package framework
import (
"flag"
"fmt"
"os"
)
type TestContextType struct {
FRPClientPath string
FRPServerPath string
LogLevel string
Debug bool
}
var TestContext TestContextType
// RegisterCommonFlags registers flags common to all e2e test suites.
// The flag set can be flag.CommandLine (if desired) or a custom
// flag set that then gets passed to viperconfig.ViperizeFlags.
//
// The other Register*Flags methods below can be used to add more
// test-specific flags. However, those settings then get added
// regardless whether the test is actually in the test suite.
func RegisterCommonFlags(flags *flag.FlagSet) {
flags.StringVar(&TestContext.FRPClientPath, "frpc-path", "../../bin/frpc", "The frp client binary to use.")
flags.StringVar(&TestContext.FRPServerPath, "frps-path", "../../bin/frps", "The frp server binary to use.")
flags.StringVar(&TestContext.LogLevel, "log-level", "debug", "Log level.")
flags.BoolVar(&TestContext.Debug, "debug", false, "Enable debug mode to print detail info.")
}
func ValidateTestContext(t *TestContextType) error {
if t.FRPClientPath == "" || t.FRPServerPath == "" {
return fmt.Errorf("frpc and frps binary path can't be empty")
}
if _, err := os.Stat(t.FRPClientPath); err != nil {
return fmt.Errorf("load frpc-path error: %v", err)
}
if _, err := os.Stat(t.FRPServerPath); err != nil {
return fmt.Errorf("load frps-path error: %v", err)
}
return nil
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/framework/util.go | test/e2e/framework/util.go | package framework
import (
"github.com/google/uuid"
)
// RunID is a unique identifier of the e2e run.
// Beware that this ID is not the same for all tests in the e2e run, because each Ginkgo node creates it separately.
var RunID string
func init() {
RunID = uuid.NewString()
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/framework/log.go | test/e2e/framework/log.go | package framework
import (
"fmt"
"time"
"github.com/onsi/ginkgo/v2"
)
func nowStamp() string {
return time.Now().Format(time.StampMilli)
}
func log(level string, format string, args ...any) {
fmt.Fprintf(ginkgo.GinkgoWriter, nowStamp()+": "+level+": "+format+"\n", args...)
}
// Logf logs the info.
func Logf(format string, args ...any) {
log("INFO", format, args...)
}
// Failf logs the fail info, including a stack trace starts with its direct caller
// (for example, for call chain f -> g -> Failf("foo", ...) error would be logged for "g").
func Failf(format string, args ...any) {
msg := fmt.Sprintf(format, args...)
skip := 1
ginkgo.Fail(msg, skip)
panic("unreachable")
}
// Fail is an alias for ginkgo.Fail.
var Fail = ginkgo.Fail
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/framework/process.go | test/e2e/framework/process.go | package framework
import (
"fmt"
"os"
"path/filepath"
"time"
flog "github.com/fatedier/frp/pkg/util/log"
"github.com/fatedier/frp/test/e2e/pkg/process"
)
// RunProcesses run multiple processes from templates.
// The first template should always be frps.
func (f *Framework) RunProcesses(serverTemplates []string, clientTemplates []string) ([]*process.Process, []*process.Process) {
templates := make([]string, 0, len(serverTemplates)+len(clientTemplates))
templates = append(templates, serverTemplates...)
templates = append(templates, clientTemplates...)
outs, ports, err := f.RenderTemplates(templates)
ExpectNoError(err)
ExpectTrue(len(templates) > 0)
for name, port := range ports {
f.usedPorts[name] = port
}
currentServerProcesses := make([]*process.Process, 0, len(serverTemplates))
for i := range serverTemplates {
path := filepath.Join(f.TempDirectory, fmt.Sprintf("frp-e2e-server-%d", i))
err = os.WriteFile(path, []byte(outs[i]), 0o600)
ExpectNoError(err)
if TestContext.Debug {
flog.Debugf("[%s] %s", path, outs[i])
}
p := process.NewWithEnvs(TestContext.FRPServerPath, []string{"-c", path}, f.osEnvs)
f.serverConfPaths = append(f.serverConfPaths, path)
f.serverProcesses = append(f.serverProcesses, p)
currentServerProcesses = append(currentServerProcesses, p)
err = p.Start()
ExpectNoError(err)
time.Sleep(500 * time.Millisecond)
}
time.Sleep(2 * time.Second)
currentClientProcesses := make([]*process.Process, 0, len(clientTemplates))
for i := range clientTemplates {
index := i + len(serverTemplates)
path := filepath.Join(f.TempDirectory, fmt.Sprintf("frp-e2e-client-%d", i))
err = os.WriteFile(path, []byte(outs[index]), 0o600)
ExpectNoError(err)
if TestContext.Debug {
flog.Debugf("[%s] %s", path, outs[index])
}
p := process.NewWithEnvs(TestContext.FRPClientPath, []string{"-c", path}, f.osEnvs)
f.clientConfPaths = append(f.clientConfPaths, path)
f.clientProcesses = append(f.clientProcesses, p)
currentClientProcesses = append(currentClientProcesses, p)
err = p.Start()
ExpectNoError(err)
time.Sleep(500 * time.Millisecond)
}
time.Sleep(3 * time.Second)
return currentServerProcesses, currentClientProcesses
}
func (f *Framework) RunFrps(args ...string) (*process.Process, string, error) {
p := process.NewWithEnvs(TestContext.FRPServerPath, args, f.osEnvs)
f.serverProcesses = append(f.serverProcesses, p)
err := p.Start()
if err != nil {
return p, p.StdOutput(), err
}
// Give frps extra time to finish binding ports before proceeding.
time.Sleep(4 * time.Second)
return p, p.StdOutput(), nil
}
func (f *Framework) RunFrpc(args ...string) (*process.Process, string, error) {
p := process.NewWithEnvs(TestContext.FRPClientPath, args, f.osEnvs)
f.clientProcesses = append(f.clientProcesses, p)
err := p.Start()
if err != nil {
return p, p.StdOutput(), err
}
time.Sleep(2 * time.Second)
return p, p.StdOutput(), nil
}
func (f *Framework) GenerateConfigFile(content string) string {
f.configFileIndex++
path := filepath.Join(f.TempDirectory, fmt.Sprintf("frp-e2e-config-%d", f.configFileIndex))
err := os.WriteFile(path, []byte(content), 0o600)
ExpectNoError(err)
return path
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/framework/framework.go | test/e2e/framework/framework.go | package framework
import (
"bytes"
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
"text/template"
"github.com/onsi/ginkgo/v2"
"github.com/fatedier/frp/test/e2e/mock/server"
"github.com/fatedier/frp/test/e2e/pkg/port"
"github.com/fatedier/frp/test/e2e/pkg/process"
)
type Options struct {
TotalParallelNode int
CurrentNodeIndex int
FromPortIndex int
ToPortIndex int
}
type Framework struct {
TempDirectory string
// ports used in this framework indexed by port name.
usedPorts map[string]int
// record ports allocated by this framework and release them after each test
allocatedPorts []int
// portAllocator to alloc port for this test case.
portAllocator *port.Allocator
// Multiple default mock servers used for e2e testing.
mockServers *MockServers
// To make sure that this framework cleans up after itself, no matter what,
// we install a Cleanup action before each test and clear it after. If we
// should abort, the AfterSuite hook should run all Cleanup actions.
cleanupHandle CleanupActionHandle
// beforeEachStarted indicates that BeforeEach has started
beforeEachStarted bool
serverConfPaths []string
serverProcesses []*process.Process
clientConfPaths []string
clientProcesses []*process.Process
// Manual registered mock servers.
servers []server.Server
// used to generate unique config file name.
configFileIndex int64
// envs used to start processes, the form is `key=value`.
osEnvs []string
}
func NewDefaultFramework() *Framework {
suiteConfig, _ := ginkgo.GinkgoConfiguration()
options := Options{
TotalParallelNode: suiteConfig.ParallelTotal,
CurrentNodeIndex: suiteConfig.ParallelProcess,
FromPortIndex: 10000,
ToPortIndex: 30000,
}
return NewFramework(options)
}
func NewFramework(opt Options) *Framework {
f := &Framework{
portAllocator: port.NewAllocator(opt.FromPortIndex, opt.ToPortIndex, opt.TotalParallelNode, opt.CurrentNodeIndex-1),
usedPorts: make(map[string]int),
}
ginkgo.BeforeEach(f.BeforeEach)
ginkgo.AfterEach(f.AfterEach)
return f
}
// BeforeEach create a temp directory.
func (f *Framework) BeforeEach() {
f.beforeEachStarted = true
f.cleanupHandle = AddCleanupAction(f.AfterEach)
dir, err := os.MkdirTemp(os.TempDir(), "frp-e2e-test-*")
ExpectNoError(err)
f.TempDirectory = dir
f.mockServers = NewMockServers(f.portAllocator)
if err := f.mockServers.Run(); err != nil {
Failf("%v", err)
}
params := f.mockServers.GetTemplateParams()
for k, v := range params {
switch t := v.(type) {
case int:
f.usedPorts[k] = t
default:
}
}
}
func (f *Framework) AfterEach() {
if !f.beforeEachStarted {
return
}
RemoveCleanupAction(f.cleanupHandle)
// stop processor
for _, p := range f.serverProcesses {
_ = p.Stop()
if TestContext.Debug || ginkgo.CurrentSpecReport().Failed() {
fmt.Println(p.ErrorOutput())
fmt.Println(p.StdOutput())
}
}
for _, p := range f.clientProcesses {
_ = p.Stop()
if TestContext.Debug || ginkgo.CurrentSpecReport().Failed() {
fmt.Println(p.ErrorOutput())
fmt.Println(p.StdOutput())
}
}
f.serverProcesses = nil
f.clientProcesses = nil
// close default mock servers
f.mockServers.Close()
// close manual registered mock servers
for _, s := range f.servers {
s.Close()
}
// clean directory
os.RemoveAll(f.TempDirectory)
f.TempDirectory = ""
f.serverConfPaths = []string{}
f.clientConfPaths = []string{}
// release used ports
for _, port := range f.usedPorts {
f.portAllocator.Release(port)
}
f.usedPorts = make(map[string]int)
// release allocated ports
for _, port := range f.allocatedPorts {
f.portAllocator.Release(port)
}
f.allocatedPorts = make([]int, 0)
// clear os envs
f.osEnvs = make([]string, 0)
}
var portRegex = regexp.MustCompile(`{{ \.Port.*? }}`)
// RenderPortsTemplate render templates with ports.
//
// Local: {{ .Port1 }}
// Target: {{ .Port2 }}
//
// return rendered content and all allocated ports.
func (f *Framework) genPortsFromTemplates(templates []string) (ports map[string]int, err error) {
ports = make(map[string]int)
for _, t := range templates {
arrs := portRegex.FindAllString(t, -1)
for _, str := range arrs {
str = strings.TrimPrefix(str, "{{ .")
str = strings.TrimSuffix(str, " }}")
str = strings.TrimSpace(str)
ports[str] = 0
}
}
defer func() {
if err != nil {
for _, port := range ports {
f.portAllocator.Release(port)
}
}
}()
for name := range ports {
port := f.portAllocator.GetByName(name)
if port <= 0 {
return nil, fmt.Errorf("can't allocate port")
}
ports[name] = port
}
return
}
// RenderTemplates alloc all ports for port names placeholder.
func (f *Framework) RenderTemplates(templates []string) (outs []string, ports map[string]int, err error) {
ports, err = f.genPortsFromTemplates(templates)
if err != nil {
return
}
params := f.mockServers.GetTemplateParams()
for name, port := range ports {
params[name] = port
}
for name, port := range f.usedPorts {
params[name] = port
}
for _, t := range templates {
tmpl, err := template.New("frp-e2e").Parse(t)
if err != nil {
return nil, nil, err
}
buffer := bytes.NewBuffer(nil)
if err = tmpl.Execute(buffer, params); err != nil {
return nil, nil, err
}
outs = append(outs, buffer.String())
}
return
}
func (f *Framework) PortByName(name string) int {
return f.usedPorts[name]
}
func (f *Framework) AllocPort() int {
port := f.portAllocator.Get()
ExpectTrue(port > 0, "alloc port failed")
f.allocatedPorts = append(f.allocatedPorts, port)
return port
}
func (f *Framework) ReleasePort(port int) {
f.portAllocator.Release(port)
}
func (f *Framework) RunServer(portName string, s server.Server) {
f.servers = append(f.servers, s)
if s.BindPort() > 0 && portName != "" {
f.usedPorts[portName] = s.BindPort()
}
err := s.Run()
ExpectNoError(err, "RunServer: with PortName %s", portName)
}
func (f *Framework) SetEnvs(envs []string) {
f.osEnvs = envs
}
func (f *Framework) WriteTempFile(name string, content string) string {
filePath := filepath.Join(f.TempDirectory, name)
err := os.WriteFile(filePath, []byte(content), 0o600)
ExpectNoError(err)
return filePath
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
fatedier/frp | https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/framework/consts/consts.go | test/e2e/framework/consts/consts.go | package consts
import (
"fmt"
"time"
"github.com/fatedier/frp/test/e2e/pkg/port"
)
const (
TestString = "frp is a fast reverse proxy to help you expose a local server behind a NAT or firewall to the internet."
DefaultTimeout = 2 * time.Second
)
var (
PortServerName string
PortClientAdmin string
DefaultServerConfig = `
bindPort = {{ .%s }}
log.level = "trace"
`
DefaultClientConfig = `
serverAddr = "127.0.0.1"
serverPort = {{ .%s }}
loginFailExit = false
log.level = "trace"
`
LegacyDefaultServerConfig = `
[common]
bind_port = {{ .%s }}
log_level = trace
`
LegacyDefaultClientConfig = `
[common]
server_addr = 127.0.0.1
server_port = {{ .%s }}
login_fail_exit = false
log_level = trace
`
)
func init() {
PortServerName = port.GenName("Server")
PortClientAdmin = port.GenName("ClientAdmin")
LegacyDefaultServerConfig = fmt.Sprintf(LegacyDefaultServerConfig, port.GenName("Server"))
LegacyDefaultClientConfig = fmt.Sprintf(LegacyDefaultClientConfig, port.GenName("Server"))
DefaultServerConfig = fmt.Sprintf(DefaultServerConfig, port.GenName("Server"))
DefaultClientConfig = fmt.Sprintf(DefaultClientConfig, port.GenName("Server"))
}
| go | Apache-2.0 | 33428ab538b7c55d46c70e2f04cc153f2400cd5b | 2026-01-07T08:35:43.420197Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.