forked from Mxmilu666/frp
Merge remote-tracking branch 'upstream/dev' into dev
This commit is contained in:
381
server/http/controller.go
Normal file
381
server/http/controller.go
Normal file
@@ -0,0 +1,381 @@
|
||||
// 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 http
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/fatedier/frp/pkg/config/types"
|
||||
v1 "github.com/fatedier/frp/pkg/config/v1"
|
||||
"github.com/fatedier/frp/pkg/metrics/mem"
|
||||
httppkg "github.com/fatedier/frp/pkg/util/http"
|
||||
"github.com/fatedier/frp/pkg/util/log"
|
||||
"github.com/fatedier/frp/pkg/util/version"
|
||||
"github.com/fatedier/frp/server/http/model"
|
||||
"github.com/fatedier/frp/server/proxy"
|
||||
"github.com/fatedier/frp/server/registry"
|
||||
)
|
||||
|
||||
type Controller struct {
|
||||
// dependencies
|
||||
serverCfg *v1.ServerConfig
|
||||
clientRegistry *registry.ClientRegistry
|
||||
pxyManager ProxyManager
|
||||
ctlManager ControlManager
|
||||
}
|
||||
|
||||
type ProxyManager interface {
|
||||
GetByName(name string) (proxy.Proxy, bool)
|
||||
}
|
||||
|
||||
type ControlManager interface {
|
||||
CloseAllProxyByName(proxyName string) error
|
||||
}
|
||||
|
||||
func NewController(
|
||||
serverCfg *v1.ServerConfig,
|
||||
clientRegistry *registry.ClientRegistry,
|
||||
pxyManager ProxyManager,
|
||||
ctlManager ControlManager,
|
||||
) *Controller {
|
||||
return &Controller{
|
||||
serverCfg: serverCfg,
|
||||
clientRegistry: clientRegistry,
|
||||
pxyManager: pxyManager,
|
||||
ctlManager: ctlManager,
|
||||
}
|
||||
}
|
||||
|
||||
// /api/serverinfo
|
||||
func (c *Controller) APIServerInfo(ctx *httppkg.Context) (any, error) {
|
||||
serverStats := mem.StatsCollector.GetServer()
|
||||
svrResp := model.ServerInfoResp{
|
||||
Version: version.Full(),
|
||||
BindPort: c.serverCfg.BindPort,
|
||||
VhostHTTPPort: c.serverCfg.VhostHTTPPort,
|
||||
VhostHTTPSPort: c.serverCfg.VhostHTTPSPort,
|
||||
TCPMuxHTTPConnectPort: c.serverCfg.TCPMuxHTTPConnectPort,
|
||||
KCPBindPort: c.serverCfg.KCPBindPort,
|
||||
QUICBindPort: c.serverCfg.QUICBindPort,
|
||||
SubdomainHost: c.serverCfg.SubDomainHost,
|
||||
MaxPoolCount: c.serverCfg.Transport.MaxPoolCount,
|
||||
MaxPortsPerClient: c.serverCfg.MaxPortsPerClient,
|
||||
HeartBeatTimeout: c.serverCfg.Transport.HeartbeatTimeout,
|
||||
AllowPortsStr: types.PortsRangeSlice(c.serverCfg.AllowPorts).String(),
|
||||
TLSForce: c.serverCfg.Transport.TLS.Force,
|
||||
|
||||
TotalTrafficIn: serverStats.TotalTrafficIn,
|
||||
TotalTrafficOut: serverStats.TotalTrafficOut,
|
||||
CurConns: serverStats.CurConns,
|
||||
ClientCounts: serverStats.ClientCounts,
|
||||
ProxyTypeCounts: serverStats.ProxyTypeCounts,
|
||||
}
|
||||
|
||||
return svrResp, nil
|
||||
}
|
||||
|
||||
// /api/clients
|
||||
func (c *Controller) APIClientList(ctx *httppkg.Context) (any, error) {
|
||||
if c.clientRegistry == nil {
|
||||
return nil, fmt.Errorf("client registry unavailable")
|
||||
}
|
||||
|
||||
userFilter := ctx.Query("user")
|
||||
clientIDFilter := ctx.Query("clientId")
|
||||
runIDFilter := ctx.Query("runId")
|
||||
statusFilter := strings.ToLower(ctx.Query("status"))
|
||||
|
||||
records := c.clientRegistry.List()
|
||||
items := make([]model.ClientInfoResp, 0, len(records))
|
||||
for _, info := range records {
|
||||
if userFilter != "" && info.User != userFilter {
|
||||
continue
|
||||
}
|
||||
if clientIDFilter != "" && info.ClientID() != clientIDFilter {
|
||||
continue
|
||||
}
|
||||
if runIDFilter != "" && info.RunID != runIDFilter {
|
||||
continue
|
||||
}
|
||||
if !matchStatusFilter(info.Online, statusFilter) {
|
||||
continue
|
||||
}
|
||||
items = append(items, buildClientInfoResp(info))
|
||||
}
|
||||
|
||||
slices.SortFunc(items, func(a, b model.ClientInfoResp) int {
|
||||
if v := cmp.Compare(a.User, b.User); v != 0 {
|
||||
return v
|
||||
}
|
||||
if v := cmp.Compare(a.ClientID, b.ClientID); v != 0 {
|
||||
return v
|
||||
}
|
||||
return cmp.Compare(a.Key, b.Key)
|
||||
})
|
||||
|
||||
return items, nil
|
||||
}
|
||||
|
||||
// /api/clients/{key}
|
||||
func (c *Controller) APIClientDetail(ctx *httppkg.Context) (any, error) {
|
||||
key := ctx.Param("key")
|
||||
if key == "" {
|
||||
return nil, fmt.Errorf("missing client key")
|
||||
}
|
||||
|
||||
if c.clientRegistry == nil {
|
||||
return nil, fmt.Errorf("client registry unavailable")
|
||||
}
|
||||
|
||||
info, ok := c.clientRegistry.GetByKey(key)
|
||||
if !ok {
|
||||
return nil, httppkg.NewError(http.StatusNotFound, fmt.Sprintf("client %s not found", key))
|
||||
}
|
||||
|
||||
return buildClientInfoResp(info), nil
|
||||
}
|
||||
|
||||
// /api/proxy/:type
|
||||
func (c *Controller) APIProxyByType(ctx *httppkg.Context) (any, error) {
|
||||
proxyType := ctx.Param("type")
|
||||
|
||||
proxyInfoResp := model.GetProxyInfoResp{}
|
||||
proxyInfoResp.Proxies = c.getProxyStatsByType(proxyType)
|
||||
slices.SortFunc(proxyInfoResp.Proxies, func(a, b *model.ProxyStatsInfo) int {
|
||||
return cmp.Compare(a.Name, b.Name)
|
||||
})
|
||||
|
||||
return proxyInfoResp, nil
|
||||
}
|
||||
|
||||
// /api/proxy/:type/:name
|
||||
func (c *Controller) APIProxyByTypeAndName(ctx *httppkg.Context) (any, error) {
|
||||
proxyType := ctx.Param("type")
|
||||
name := ctx.Param("name")
|
||||
|
||||
proxyStatsResp, code, msg := c.getProxyStatsByTypeAndName(proxyType, name)
|
||||
if code != 200 {
|
||||
return nil, httppkg.NewError(code, msg)
|
||||
}
|
||||
|
||||
return proxyStatsResp, nil
|
||||
}
|
||||
|
||||
// /api/traffic/:name
|
||||
func (c *Controller) APIProxyTraffic(ctx *httppkg.Context) (any, error) {
|
||||
name := ctx.Param("name")
|
||||
|
||||
trafficResp := model.GetProxyTrafficResp{}
|
||||
trafficResp.Name = name
|
||||
proxyTrafficInfo := mem.StatsCollector.GetProxyTraffic(name)
|
||||
|
||||
if proxyTrafficInfo == nil {
|
||||
return nil, httppkg.NewError(http.StatusNotFound, "no proxy info found")
|
||||
}
|
||||
trafficResp.TrafficIn = proxyTrafficInfo.TrafficIn
|
||||
trafficResp.TrafficOut = proxyTrafficInfo.TrafficOut
|
||||
|
||||
return trafficResp, nil
|
||||
}
|
||||
|
||||
// /api/proxies/:name
|
||||
func (c *Controller) APIProxyByName(ctx *httppkg.Context) (any, error) {
|
||||
name := ctx.Param("name")
|
||||
|
||||
ps := mem.StatsCollector.GetProxyByName(name)
|
||||
if ps == nil {
|
||||
return nil, httppkg.NewError(http.StatusNotFound, "no proxy info found")
|
||||
}
|
||||
|
||||
proxyInfo := model.GetProxyStatsResp{
|
||||
Name: ps.Name,
|
||||
User: ps.User,
|
||||
ClientID: ps.ClientID,
|
||||
TodayTrafficIn: ps.TodayTrafficIn,
|
||||
TodayTrafficOut: ps.TodayTrafficOut,
|
||||
CurConns: ps.CurConns,
|
||||
LastStartTime: ps.LastStartTime,
|
||||
LastCloseTime: ps.LastCloseTime,
|
||||
}
|
||||
|
||||
if pxy, ok := c.pxyManager.GetByName(name); ok {
|
||||
proxyInfo.Conf = getConfFromConfigurer(pxy.GetConfigurer())
|
||||
proxyInfo.Status = "online"
|
||||
} else {
|
||||
proxyInfo.Status = "offline"
|
||||
}
|
||||
|
||||
return proxyInfo, nil
|
||||
}
|
||||
|
||||
// POST /api/proxy/:name/close
|
||||
func (c *Controller) APICloseProxyByName(ctx *httppkg.Context) (any, error) {
|
||||
name := ctx.Param("name")
|
||||
if name == "" {
|
||||
return nil, httppkg.NewError(http.StatusBadRequest, "proxy name required")
|
||||
}
|
||||
|
||||
if c.ctlManager == nil {
|
||||
return nil, fmt.Errorf("control manager unavailable")
|
||||
}
|
||||
|
||||
if err := c.ctlManager.CloseAllProxyByName(name); err != nil {
|
||||
return nil, httppkg.NewError(http.StatusNotFound, err.Error())
|
||||
}
|
||||
|
||||
return httppkg.GeneralResponse{Code: 200, Msg: "ok"}, nil
|
||||
}
|
||||
|
||||
// DELETE /api/proxies?status=offline
|
||||
func (c *Controller) DeleteProxies(ctx *httppkg.Context) (any, error) {
|
||||
status := ctx.Query("status")
|
||||
if status != "offline" {
|
||||
return nil, httppkg.NewError(http.StatusBadRequest, "status only support offline")
|
||||
}
|
||||
cleared, total := mem.StatsCollector.ClearOfflineProxies()
|
||||
log.Infof("cleared [%d] offline proxies, total [%d] proxies", cleared, total)
|
||||
return httppkg.GeneralResponse{Code: 200, Msg: "success"}, nil
|
||||
}
|
||||
|
||||
func (c *Controller) getProxyStatsByType(proxyType string) (proxyInfos []*model.ProxyStatsInfo) {
|
||||
proxyStats := mem.StatsCollector.GetProxiesByType(proxyType)
|
||||
proxyInfos = make([]*model.ProxyStatsInfo, 0, len(proxyStats))
|
||||
for _, ps := range proxyStats {
|
||||
proxyInfo := &model.ProxyStatsInfo{
|
||||
User: ps.User,
|
||||
ClientID: ps.ClientID,
|
||||
}
|
||||
if pxy, ok := c.pxyManager.GetByName(ps.Name); ok {
|
||||
proxyInfo.Conf = getConfFromConfigurer(pxy.GetConfigurer())
|
||||
proxyInfo.Status = "online"
|
||||
} else {
|
||||
proxyInfo.Status = "offline"
|
||||
}
|
||||
proxyInfo.Name = ps.Name
|
||||
proxyInfo.TodayTrafficIn = ps.TodayTrafficIn
|
||||
proxyInfo.TodayTrafficOut = ps.TodayTrafficOut
|
||||
proxyInfo.CurConns = ps.CurConns
|
||||
proxyInfo.LastStartTime = ps.LastStartTime
|
||||
proxyInfo.LastCloseTime = ps.LastCloseTime
|
||||
proxyInfos = append(proxyInfos, proxyInfo)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (c *Controller) getProxyStatsByTypeAndName(proxyType string, proxyName string) (proxyInfo model.GetProxyStatsResp, code int, msg string) {
|
||||
proxyInfo.Name = proxyName
|
||||
ps := mem.StatsCollector.GetProxiesByTypeAndName(proxyType, proxyName)
|
||||
if ps == nil {
|
||||
code = 404
|
||||
msg = "no proxy info found"
|
||||
} else {
|
||||
proxyInfo.User = ps.User
|
||||
proxyInfo.ClientID = ps.ClientID
|
||||
if pxy, ok := c.pxyManager.GetByName(proxyName); ok {
|
||||
proxyInfo.Conf = getConfFromConfigurer(pxy.GetConfigurer())
|
||||
proxyInfo.Status = "online"
|
||||
} else {
|
||||
proxyInfo.Status = "offline"
|
||||
}
|
||||
proxyInfo.TodayTrafficIn = ps.TodayTrafficIn
|
||||
proxyInfo.TodayTrafficOut = ps.TodayTrafficOut
|
||||
proxyInfo.CurConns = ps.CurConns
|
||||
proxyInfo.LastStartTime = ps.LastStartTime
|
||||
proxyInfo.LastCloseTime = ps.LastCloseTime
|
||||
code = 200
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func buildClientInfoResp(info registry.ClientInfo) model.ClientInfoResp {
|
||||
resp := model.ClientInfoResp{
|
||||
Key: info.Key,
|
||||
User: info.User,
|
||||
ClientID: info.ClientID(),
|
||||
RunID: info.RunID,
|
||||
Version: info.Version,
|
||||
WireProtocol: info.WireProtocol,
|
||||
Hostname: info.Hostname,
|
||||
ClientIP: info.IP,
|
||||
FirstConnectedAt: toUnix(info.FirstConnectedAt),
|
||||
LastConnectedAt: toUnix(info.LastConnectedAt),
|
||||
Online: info.Online,
|
||||
}
|
||||
if !info.DisconnectedAt.IsZero() {
|
||||
resp.DisconnectedAt = info.DisconnectedAt.Unix()
|
||||
}
|
||||
return resp
|
||||
}
|
||||
|
||||
func toUnix(t time.Time) int64 {
|
||||
if t.IsZero() {
|
||||
return 0
|
||||
}
|
||||
return t.Unix()
|
||||
}
|
||||
|
||||
func matchStatusFilter(online bool, filter string) bool {
|
||||
switch strings.ToLower(filter) {
|
||||
case "", "all":
|
||||
return true
|
||||
case "online":
|
||||
return online
|
||||
case "offline":
|
||||
return !online
|
||||
default:
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
func getConfFromConfigurer(cfg v1.ProxyConfigurer) any {
|
||||
outBase := model.BaseOutConf{ProxyBaseConfig: *cfg.GetBaseConfig()}
|
||||
|
||||
switch c := cfg.(type) {
|
||||
case *v1.TCPProxyConfig:
|
||||
return &model.TCPOutConf{BaseOutConf: outBase, RemotePort: c.RemotePort}
|
||||
case *v1.UDPProxyConfig:
|
||||
return &model.UDPOutConf{BaseOutConf: outBase, RemotePort: c.RemotePort}
|
||||
case *v1.HTTPProxyConfig:
|
||||
return &model.HTTPOutConf{
|
||||
BaseOutConf: outBase,
|
||||
DomainConfig: c.DomainConfig,
|
||||
Locations: c.Locations,
|
||||
HostHeaderRewrite: c.HostHeaderRewrite,
|
||||
}
|
||||
case *v1.HTTPSProxyConfig:
|
||||
return &model.HTTPSOutConf{
|
||||
BaseOutConf: outBase,
|
||||
DomainConfig: c.DomainConfig,
|
||||
}
|
||||
case *v1.TCPMuxProxyConfig:
|
||||
return &model.TCPMuxOutConf{
|
||||
BaseOutConf: outBase,
|
||||
DomainConfig: c.DomainConfig,
|
||||
Multiplexer: c.Multiplexer,
|
||||
RouteByHTTPUser: c.RouteByHTTPUser,
|
||||
}
|
||||
case *v1.STCPProxyConfig:
|
||||
return &model.STCPOutConf{BaseOutConf: outBase}
|
||||
case *v1.XTCPProxyConfig:
|
||||
return &model.XTCPOutConf{BaseOutConf: outBase}
|
||||
}
|
||||
return outBase
|
||||
}
|
||||
95
server/http/controller_test.go
Normal file
95
server/http/controller_test.go
Normal file
@@ -0,0 +1,95 @@
|
||||
// Copyright 2026 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 http
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
v1 "github.com/fatedier/frp/pkg/config/v1"
|
||||
"github.com/fatedier/frp/pkg/proto/wire"
|
||||
"github.com/fatedier/frp/server/registry"
|
||||
)
|
||||
|
||||
func TestGetConfFromConfigurerKeepsPluginFields(t *testing.T) {
|
||||
cfg := &v1.TCPProxyConfig{
|
||||
ProxyBaseConfig: v1.ProxyBaseConfig{
|
||||
Name: "test-proxy",
|
||||
Type: string(v1.ProxyTypeTCP),
|
||||
ProxyBackend: v1.ProxyBackend{
|
||||
Plugin: v1.TypedClientPluginOptions{
|
||||
Type: v1.PluginHTTPProxy,
|
||||
ClientPluginOptions: &v1.HTTPProxyPluginOptions{
|
||||
Type: v1.PluginHTTPProxy,
|
||||
HTTPUser: "user",
|
||||
HTTPPassword: "password",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
RemotePort: 6000,
|
||||
}
|
||||
|
||||
content, err := json.Marshal(getConfFromConfigurer(cfg))
|
||||
if err != nil {
|
||||
t.Fatalf("marshal conf failed: %v", err)
|
||||
}
|
||||
|
||||
var out map[string]any
|
||||
if err := json.Unmarshal(content, &out); err != nil {
|
||||
t.Fatalf("unmarshal conf failed: %v", err)
|
||||
}
|
||||
|
||||
pluginValue, ok := out["plugin"]
|
||||
if !ok {
|
||||
t.Fatalf("plugin field missing in output: %v", out)
|
||||
}
|
||||
plugin, ok := pluginValue.(map[string]any)
|
||||
if !ok {
|
||||
t.Fatalf("plugin field should be object, got: %#v", pluginValue)
|
||||
}
|
||||
|
||||
if got := plugin["type"]; got != v1.PluginHTTPProxy {
|
||||
t.Fatalf("plugin type mismatch, want %q got %#v", v1.PluginHTTPProxy, got)
|
||||
}
|
||||
if got := plugin["httpUser"]; got != "user" {
|
||||
t.Fatalf("plugin httpUser mismatch, want %q got %#v", "user", got)
|
||||
}
|
||||
if got := plugin["httpPassword"]; got != "password" {
|
||||
t.Fatalf("plugin httpPassword mismatch, want %q got %#v", "password", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildClientInfoRespIncludesWireProtocol(t *testing.T) {
|
||||
info := registry.ClientInfo{
|
||||
Key: "user.client",
|
||||
User: "user",
|
||||
RawClientID: "client",
|
||||
RunID: "run-id",
|
||||
Version: "1.0.0",
|
||||
WireProtocol: wire.ProtocolV2,
|
||||
Hostname: "host",
|
||||
IP: "127.0.0.1",
|
||||
FirstConnectedAt: time.Unix(1, 0),
|
||||
LastConnectedAt: time.Unix(2, 0),
|
||||
Online: true,
|
||||
}
|
||||
|
||||
resp := buildClientInfoResp(info)
|
||||
if resp.WireProtocol != wire.ProtocolV2 {
|
||||
t.Fatalf("wire protocol mismatch, want %q got %q", wire.ProtocolV2, resp.WireProtocol)
|
||||
}
|
||||
}
|
||||
394
server/http/controller_v2.go
Normal file
394
server/http/controller_v2.go
Normal file
@@ -0,0 +1,394 @@
|
||||
// Copyright 2026 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 http
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"fmt"
|
||||
"math"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
v1 "github.com/fatedier/frp/pkg/config/v1"
|
||||
"github.com/fatedier/frp/pkg/metrics/mem"
|
||||
httppkg "github.com/fatedier/frp/pkg/util/http"
|
||||
"github.com/fatedier/frp/server/http/model"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultV2Page = 1
|
||||
defaultV2PageSize = 50
|
||||
maxV2PageSize = 200
|
||||
)
|
||||
|
||||
var apiV2ProxyTypes = []string{
|
||||
string(v1.ProxyTypeTCP),
|
||||
string(v1.ProxyTypeUDP),
|
||||
string(v1.ProxyTypeHTTP),
|
||||
string(v1.ProxyTypeHTTPS),
|
||||
string(v1.ProxyTypeTCPMUX),
|
||||
string(v1.ProxyTypeSTCP),
|
||||
string(v1.ProxyTypeXTCP),
|
||||
string(v1.ProxyTypeSUDP),
|
||||
}
|
||||
|
||||
// /api/v2/users
|
||||
func (c *Controller) APIV2UserList(ctx *httppkg.Context) (any, error) {
|
||||
page, pageSize, err := parseV2PageParams(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if c.clientRegistry == nil {
|
||||
return nil, fmt.Errorf("client registry unavailable")
|
||||
}
|
||||
|
||||
userStats := make(map[string]*model.V2UserResp)
|
||||
for _, info := range c.clientRegistry.List() {
|
||||
item := getOrCreateV2User(userStats, info.User)
|
||||
item.ClientCount++
|
||||
}
|
||||
for _, proxyInfo := range c.listV2ProxyStats("") {
|
||||
item := getOrCreateV2User(userStats, proxyInfo.User)
|
||||
item.ProxyCount++
|
||||
}
|
||||
|
||||
q := strings.ToLower(ctx.Query("q"))
|
||||
items := make([]model.V2UserResp, 0, len(userStats))
|
||||
for _, item := range userStats {
|
||||
if q != "" && !strings.Contains(strings.ToLower(item.User), q) {
|
||||
continue
|
||||
}
|
||||
items = append(items, *item)
|
||||
}
|
||||
slices.SortFunc(items, func(a, b model.V2UserResp) int {
|
||||
return cmp.Compare(a.User, b.User)
|
||||
})
|
||||
|
||||
return buildV2PageResp(items, page, pageSize), nil
|
||||
}
|
||||
|
||||
// /api/v2/clients
|
||||
func (c *Controller) APIV2ClientList(ctx *httppkg.Context) (any, error) {
|
||||
page, pageSize, err := parseV2PageParams(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if c.clientRegistry == nil {
|
||||
return nil, fmt.Errorf("client registry unavailable")
|
||||
}
|
||||
statusFilter, err := parseV2StatusFilter(ctx.Query("status"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
userFilter, filterByUser := queryValue(ctx, "user")
|
||||
clientIDFilter := ctx.Query("clientID")
|
||||
runIDFilter := ctx.Query("runID")
|
||||
q := strings.ToLower(ctx.Query("q"))
|
||||
|
||||
records := c.clientRegistry.List()
|
||||
items := make([]model.ClientInfoResp, 0, len(records))
|
||||
for _, info := range records {
|
||||
if filterByUser && info.User != userFilter {
|
||||
continue
|
||||
}
|
||||
if clientIDFilter != "" && info.ClientID() != clientIDFilter {
|
||||
continue
|
||||
}
|
||||
if runIDFilter != "" && info.RunID != runIDFilter {
|
||||
continue
|
||||
}
|
||||
if !matchV2StatusFilter(info.Online, statusFilter) {
|
||||
continue
|
||||
}
|
||||
resp := buildClientInfoResp(info)
|
||||
if q != "" && !matchV2ClientQuery(resp, q) {
|
||||
continue
|
||||
}
|
||||
items = append(items, resp)
|
||||
}
|
||||
|
||||
slices.SortFunc(items, func(a, b model.ClientInfoResp) int {
|
||||
if v := cmp.Compare(a.User, b.User); v != 0 {
|
||||
return v
|
||||
}
|
||||
if v := cmp.Compare(a.ClientID, b.ClientID); v != 0 {
|
||||
return v
|
||||
}
|
||||
return cmp.Compare(a.Key, b.Key)
|
||||
})
|
||||
|
||||
return buildV2PageResp(items, page, pageSize), nil
|
||||
}
|
||||
|
||||
// /api/v2/clients/{key}
|
||||
func (c *Controller) APIV2ClientDetail(ctx *httppkg.Context) (any, error) {
|
||||
return c.APIClientDetail(ctx)
|
||||
}
|
||||
|
||||
// /api/v2/proxies
|
||||
func (c *Controller) APIV2ProxyList(ctx *httppkg.Context) (any, error) {
|
||||
page, pageSize, err := parseV2PageParams(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
statusFilter, err := parseV2StatusFilter(ctx.Query("status"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
proxyType, err := parseV2ProxyTypeFilter(ctx.Query("type"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
userFilter, filterByUser := queryValue(ctx, "user")
|
||||
clientIDFilter := ctx.Query("clientID")
|
||||
q := strings.ToLower(ctx.Query("q"))
|
||||
|
||||
stats := c.listV2ProxyStats(proxyType)
|
||||
items := make([]model.V2ProxyResp, 0, len(stats))
|
||||
for _, ps := range stats {
|
||||
resp := c.buildV2ProxyResp(ps)
|
||||
if filterByUser && resp.User != userFilter {
|
||||
continue
|
||||
}
|
||||
if clientIDFilter != "" && resp.ClientID != clientIDFilter {
|
||||
continue
|
||||
}
|
||||
if !matchV2StatusFilter(resp.Status.State == "online", statusFilter) {
|
||||
continue
|
||||
}
|
||||
if q != "" && !matchV2ProxyQuery(resp, q) {
|
||||
continue
|
||||
}
|
||||
items = append(items, resp)
|
||||
}
|
||||
|
||||
slices.SortFunc(items, func(a, b model.V2ProxyResp) int {
|
||||
if v := cmp.Compare(a.Type, b.Type); v != 0 {
|
||||
return v
|
||||
}
|
||||
return cmp.Compare(a.Name, b.Name)
|
||||
})
|
||||
|
||||
return buildV2PageResp(items, page, pageSize), nil
|
||||
}
|
||||
|
||||
// /api/v2/proxies/{name}
|
||||
func (c *Controller) APIV2ProxyDetail(ctx *httppkg.Context) (any, error) {
|
||||
name := ctx.Param("name")
|
||||
if name == "" {
|
||||
return nil, fmt.Errorf("missing proxy name")
|
||||
}
|
||||
|
||||
ps := mem.StatsCollector.GetProxyByName(name)
|
||||
if ps == nil {
|
||||
return nil, httppkg.NewError(http.StatusNotFound, "no proxy info found")
|
||||
}
|
||||
return c.buildV2ProxyResp(ps), nil
|
||||
}
|
||||
|
||||
func getOrCreateV2User(items map[string]*model.V2UserResp, user string) *model.V2UserResp {
|
||||
item, ok := items[user]
|
||||
if !ok {
|
||||
item = &model.V2UserResp{User: user}
|
||||
items[user] = item
|
||||
}
|
||||
return item
|
||||
}
|
||||
|
||||
func parseV2PageParams(ctx *httppkg.Context) (int, int, error) {
|
||||
page, err := parseV2PositiveInt(ctx.Query("page"), defaultV2Page, "page")
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
pageSize, err := parseV2PositiveInt(ctx.Query("pageSize"), defaultV2PageSize, "pageSize")
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
if pageSize > maxV2PageSize {
|
||||
return 0, 0, httppkg.NewError(http.StatusBadRequest, fmt.Sprintf("pageSize must be between 1 and %d", maxV2PageSize))
|
||||
}
|
||||
if page > math.MaxInt/pageSize {
|
||||
return 0, 0, httppkg.NewError(http.StatusBadRequest, "page is too large")
|
||||
}
|
||||
return page, pageSize, nil
|
||||
}
|
||||
|
||||
func parseV2PositiveInt(raw string, defaultValue int, name string) (int, error) {
|
||||
if raw == "" {
|
||||
return defaultValue, nil
|
||||
}
|
||||
value, err := strconv.Atoi(raw)
|
||||
if err != nil || value < 1 {
|
||||
return 0, httppkg.NewError(http.StatusBadRequest, fmt.Sprintf("%s must be a positive integer", name))
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func parseV2StatusFilter(raw string) (string, error) {
|
||||
status := strings.ToLower(raw)
|
||||
switch status {
|
||||
case "", "all", "online", "offline":
|
||||
return status, nil
|
||||
default:
|
||||
return "", httppkg.NewError(http.StatusBadRequest, "status must be one of all, online, offline")
|
||||
}
|
||||
}
|
||||
|
||||
func parseV2ProxyTypeFilter(raw string) (string, error) {
|
||||
proxyType := strings.ToLower(raw)
|
||||
if proxyType == "" {
|
||||
return "", nil
|
||||
}
|
||||
if slices.Contains(apiV2ProxyTypes, proxyType) {
|
||||
return proxyType, nil
|
||||
}
|
||||
return "", httppkg.NewError(http.StatusBadRequest, "type must be one of tcp, udp, http, https, tcpmux, stcp, xtcp, sudp")
|
||||
}
|
||||
|
||||
func matchV2StatusFilter(online bool, filter string) bool {
|
||||
switch filter {
|
||||
case "", "all":
|
||||
return true
|
||||
case "online":
|
||||
return online
|
||||
case "offline":
|
||||
return !online
|
||||
default:
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
func buildV2PageResp[T any](items []T, page, pageSize int) model.V2PageResp[T] {
|
||||
total := len(items)
|
||||
return model.V2PageResp[T]{
|
||||
Total: total,
|
||||
Page: page,
|
||||
PageSize: pageSize,
|
||||
Items: paginateV2Items(items, page, pageSize),
|
||||
}
|
||||
}
|
||||
|
||||
func paginateV2Items[T any](items []T, page, pageSize int) []T {
|
||||
start := (page - 1) * pageSize
|
||||
if start >= len(items) {
|
||||
return []T{}
|
||||
}
|
||||
end := min(start+pageSize, len(items))
|
||||
return items[start:end]
|
||||
}
|
||||
|
||||
func queryValue(ctx *httppkg.Context, key string) (string, bool) {
|
||||
values, ok := ctx.Req.URL.Query()[key]
|
||||
if !ok {
|
||||
return "", false
|
||||
}
|
||||
if len(values) == 0 {
|
||||
return "", true
|
||||
}
|
||||
return values[0], true
|
||||
}
|
||||
|
||||
func matchV2ClientQuery(item model.ClientInfoResp, q string) bool {
|
||||
return containsV2Query(q,
|
||||
item.Key,
|
||||
item.User,
|
||||
item.ClientID,
|
||||
item.RunID,
|
||||
item.Version,
|
||||
item.WireProtocol,
|
||||
item.Hostname,
|
||||
item.ClientIP,
|
||||
)
|
||||
}
|
||||
|
||||
func matchV2ProxyQuery(item model.V2ProxyResp, q string) bool {
|
||||
values := []string{
|
||||
item.Name,
|
||||
item.Type,
|
||||
item.User,
|
||||
item.ClientID,
|
||||
item.Status.State,
|
||||
}
|
||||
|
||||
switch spec := item.Spec.(type) {
|
||||
case *model.TCPOutConf:
|
||||
values = append(values, strconv.Itoa(spec.RemotePort))
|
||||
case *model.UDPOutConf:
|
||||
values = append(values, strconv.Itoa(spec.RemotePort))
|
||||
case *model.HTTPOutConf:
|
||||
values = append(values, spec.CustomDomains...)
|
||||
values = append(values, spec.SubDomain)
|
||||
case *model.HTTPSOutConf:
|
||||
values = append(values, spec.CustomDomains...)
|
||||
values = append(values, spec.SubDomain)
|
||||
case *model.TCPMuxOutConf:
|
||||
values = append(values, spec.CustomDomains...)
|
||||
values = append(values, spec.SubDomain)
|
||||
}
|
||||
|
||||
return containsV2Query(q, values...)
|
||||
}
|
||||
|
||||
func containsV2Query(q string, values ...string) bool {
|
||||
for _, value := range values {
|
||||
if strings.Contains(strings.ToLower(value), q) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (c *Controller) listV2ProxyStats(proxyType string) []*mem.ProxyStats {
|
||||
if proxyType != "" {
|
||||
return mem.StatsCollector.GetProxiesByType(proxyType)
|
||||
}
|
||||
|
||||
items := make([]*mem.ProxyStats, 0)
|
||||
for _, t := range apiV2ProxyTypes {
|
||||
items = append(items, mem.StatsCollector.GetProxiesByType(t)...)
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
func (c *Controller) buildV2ProxyResp(ps *mem.ProxyStats) model.V2ProxyResp {
|
||||
state := "offline"
|
||||
var spec any
|
||||
if c.pxyManager != nil {
|
||||
if pxy, ok := c.pxyManager.GetByName(ps.Name); ok {
|
||||
state = "online"
|
||||
spec = getConfFromConfigurer(pxy.GetConfigurer())
|
||||
}
|
||||
}
|
||||
|
||||
return model.V2ProxyResp{
|
||||
Name: ps.Name,
|
||||
Type: ps.Type,
|
||||
User: ps.User,
|
||||
ClientID: ps.ClientID,
|
||||
Spec: spec,
|
||||
Status: model.V2ProxyStatusResp{
|
||||
State: state,
|
||||
TodayTrafficIn: ps.TodayTrafficIn,
|
||||
TodayTrafficOut: ps.TodayTrafficOut,
|
||||
CurConns: ps.CurConns,
|
||||
LastStartTime: ps.LastStartTime,
|
||||
LastCloseTime: ps.LastCloseTime,
|
||||
},
|
||||
}
|
||||
}
|
||||
374
server/http/controller_v2_test.go
Normal file
374
server/http/controller_v2_test.go
Normal file
@@ -0,0 +1,374 @@
|
||||
// Copyright 2026 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 http
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"math"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
|
||||
v1 "github.com/fatedier/frp/pkg/config/v1"
|
||||
"github.com/fatedier/frp/pkg/metrics/mem"
|
||||
httppkg "github.com/fatedier/frp/pkg/util/http"
|
||||
"github.com/fatedier/frp/server/http/model"
|
||||
serverproxy "github.com/fatedier/frp/server/proxy"
|
||||
"github.com/fatedier/frp/server/registry"
|
||||
)
|
||||
|
||||
type v2EnvelopeForTest[T any] struct {
|
||||
Code int `json:"code"`
|
||||
Msg string `json:"msg"`
|
||||
Data T `json:"data"`
|
||||
}
|
||||
|
||||
type fakeStatsCollector struct {
|
||||
proxies map[string]*mem.ProxyStats
|
||||
}
|
||||
|
||||
func (f *fakeStatsCollector) GetServer() *mem.ServerStats {
|
||||
return &mem.ServerStats{ProxyTypeCounts: map[string]int64{}}
|
||||
}
|
||||
|
||||
func (f *fakeStatsCollector) GetProxiesByType(proxyType string) []*mem.ProxyStats {
|
||||
items := make([]*mem.ProxyStats, 0)
|
||||
for _, ps := range f.proxies {
|
||||
if ps.Type == proxyType {
|
||||
items = append(items, ps)
|
||||
}
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
func (f *fakeStatsCollector) GetProxiesByTypeAndName(proxyType string, proxyName string) *mem.ProxyStats {
|
||||
ps := f.proxies[proxyName]
|
||||
if ps != nil && ps.Type == proxyType {
|
||||
return ps
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeStatsCollector) GetProxyByName(proxyName string) *mem.ProxyStats {
|
||||
return f.proxies[proxyName]
|
||||
}
|
||||
|
||||
func (f *fakeStatsCollector) GetProxyTraffic(name string) *mem.ProxyTrafficInfo {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeStatsCollector) ClearOfflineProxies() (int, int) {
|
||||
return 0, len(f.proxies)
|
||||
}
|
||||
|
||||
func TestAPIV2ClientListEnvelopePaginationAndFilters(t *testing.T) {
|
||||
controller := newV2TestController(t)
|
||||
router := newV2TestRouter(controller)
|
||||
|
||||
resp := performRequest(router, "/api/v2/clients?page=1&pageSize=1")
|
||||
if resp.Code != http.StatusOK {
|
||||
t.Fatalf("status mismatch, want %d got %d", http.StatusOK, resp.Code)
|
||||
}
|
||||
pageResp := decodeResponse[v2EnvelopeForTest[model.V2PageResp[model.ClientInfoResp]]](t, resp)
|
||||
if pageResp.Code != http.StatusOK || pageResp.Msg != "success" {
|
||||
t.Fatalf("envelope mismatch: %#v", pageResp)
|
||||
}
|
||||
if pageResp.Data.Total != 3 || pageResp.Data.Page != 1 || pageResp.Data.PageSize != 1 || len(pageResp.Data.Items) != 1 {
|
||||
t.Fatalf("page data mismatch: %#v", pageResp.Data)
|
||||
}
|
||||
if got := pageResp.Data.Items[0].User; got != "" {
|
||||
t.Fatalf("first sorted user mismatch, want empty got %q", got)
|
||||
}
|
||||
|
||||
resp = performRequest(router, "/api/v2/clients?user=&page=1&pageSize=50")
|
||||
emptyUserResp := decodeResponse[v2EnvelopeForTest[model.V2PageResp[model.ClientInfoResp]]](t, resp)
|
||||
if emptyUserResp.Data.Total != 1 || emptyUserResp.Data.Items[0].User != "" {
|
||||
t.Fatalf("empty user filter mismatch: %#v", emptyUserResp.Data)
|
||||
}
|
||||
|
||||
resp = performRequest(router, "/api/v2/clients?user=alice&status=online&q=alice-host")
|
||||
aliceResp := decodeResponse[v2EnvelopeForTest[model.V2PageResp[model.ClientInfoResp]]](t, resp)
|
||||
if aliceResp.Data.Total != 1 || aliceResp.Data.Items[0].User != "alice" {
|
||||
t.Fatalf("alice filter mismatch: %#v", aliceResp.Data)
|
||||
}
|
||||
|
||||
resp = performRequest(router, "/api/v2/clients?status=offline")
|
||||
offlineResp := decodeResponse[v2EnvelopeForTest[model.V2PageResp[model.ClientInfoResp]]](t, resp)
|
||||
if offlineResp.Data.Total != 1 || offlineResp.Data.Items[0].User != "bob" {
|
||||
t.Fatalf("offline filter mismatch: %#v", offlineResp.Data)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPIV2PageParamErrorsUseEnvelope(t *testing.T) {
|
||||
controller := newV2TestController(t)
|
||||
router := newV2TestRouter(controller)
|
||||
|
||||
resp := performRequest(router, "/api/v2/clients?page=0")
|
||||
if resp.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status mismatch, want %d got %d", http.StatusBadRequest, resp.Code)
|
||||
}
|
||||
errResp := decodeResponse[httppkg.V2Response](t, resp)
|
||||
if errResp.Code != http.StatusBadRequest || errResp.Data != nil {
|
||||
t.Fatalf("error envelope mismatch: %#v", errResp)
|
||||
}
|
||||
|
||||
resp = performRequest(router, "/api/v2/clients?pageSize=201")
|
||||
if resp.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status mismatch, want %d got %d", http.StatusBadRequest, resp.Code)
|
||||
}
|
||||
|
||||
resp = performRequest(router, fmt.Sprintf("/api/v2/clients?page=%d&pageSize=2", math.MaxInt))
|
||||
if resp.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status mismatch for overflowing page offset, want %d got %d", http.StatusBadRequest, resp.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPIV2ClientDetailEnvelope(t *testing.T) {
|
||||
controller := newV2TestController(t)
|
||||
router := newV2TestRouter(controller)
|
||||
|
||||
resp := performRequest(router, "/api/v2/clients/alice.client-a")
|
||||
if resp.Code != http.StatusOK {
|
||||
t.Fatalf("status mismatch, want %d got %d", http.StatusOK, resp.Code)
|
||||
}
|
||||
detailResp := decodeResponse[v2EnvelopeForTest[model.ClientInfoResp]](t, resp)
|
||||
if detailResp.Data.User != "alice" || detailResp.Data.ClientID != "client-a" {
|
||||
t.Fatalf("client detail mismatch: %#v", detailResp.Data)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPIV2ProxyListDetailAndUsers(t *testing.T) {
|
||||
controller := newV2TestController(t)
|
||||
router := newV2TestRouter(controller)
|
||||
|
||||
resp := performRequest(router, "/api/v2/proxies?type=invalid")
|
||||
if resp.Code != http.StatusBadRequest {
|
||||
t.Fatalf("invalid proxy type status mismatch, want %d got %d", http.StatusBadRequest, resp.Code)
|
||||
}
|
||||
errResp := decodeResponse[httppkg.V2Response](t, resp)
|
||||
if errResp.Code != http.StatusBadRequest || errResp.Data != nil {
|
||||
t.Fatalf("invalid proxy type error envelope mismatch: %#v", errResp)
|
||||
}
|
||||
|
||||
resp = performRequest(router, "/api/v2/proxies?type=tcp&user=&page=1&pageSize=50")
|
||||
proxyResp := decodeResponse[v2EnvelopeForTest[model.V2PageResp[model.V2ProxyResp]]](t, resp)
|
||||
if proxyResp.Data.Total != 1 {
|
||||
t.Fatalf("proxy filter total mismatch: %#v", proxyResp.Data)
|
||||
}
|
||||
proxyItem := proxyResp.Data.Items[0]
|
||||
if proxyItem.Name != "tcp-empty" || proxyItem.Type != "tcp" || proxyItem.User != "" || proxyItem.Status.State != "offline" {
|
||||
t.Fatalf("proxy item mismatch: %#v", proxyItem)
|
||||
}
|
||||
|
||||
resp = performRequest(router, "/api/v2/proxies/tcp-alice")
|
||||
proxyDetailResp := decodeResponse[v2EnvelopeForTest[model.V2ProxyResp]](t, resp)
|
||||
if proxyDetailResp.Data.Name != "tcp-alice" || proxyDetailResp.Data.User != "alice" {
|
||||
t.Fatalf("proxy detail mismatch: %#v", proxyDetailResp.Data)
|
||||
}
|
||||
|
||||
resp = performRequest(router, "/api/v2/users?page=1&pageSize=50")
|
||||
userResp := decodeResponse[v2EnvelopeForTest[model.V2PageResp[model.V2UserResp]]](t, resp)
|
||||
if userResp.Data.Total != 3 {
|
||||
t.Fatalf("user total mismatch: %#v", userResp.Data)
|
||||
}
|
||||
for _, item := range userResp.Data.Items {
|
||||
if item.ClientCount != 1 || item.ProxyCount != 1 {
|
||||
t.Fatalf("user counts mismatch: %#v", item)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMatchV2ProxyQueryMatchesSpecFields(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
item model.V2ProxyResp
|
||||
q string
|
||||
want bool
|
||||
}{
|
||||
{
|
||||
name: "tcp remote port",
|
||||
item: model.V2ProxyResp{Name: "tcp-proxy", Type: "tcp", Spec: &model.TCPOutConf{
|
||||
RemotePort: 6000,
|
||||
}},
|
||||
q: "6000",
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "udp remote port",
|
||||
item: model.V2ProxyResp{Name: "udp-proxy", Type: "udp", Spec: &model.UDPOutConf{
|
||||
RemotePort: 7000,
|
||||
}},
|
||||
q: "7000",
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "remote port does not match colon form",
|
||||
item: model.V2ProxyResp{Name: "tcp-proxy", Type: "tcp", Spec: &model.TCPOutConf{
|
||||
RemotePort: 6000,
|
||||
}},
|
||||
q: ":6000",
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "http custom domain",
|
||||
item: model.V2ProxyResp{Name: "http-proxy", Type: "http", Spec: &model.HTTPOutConf{
|
||||
DomainConfig: v1.DomainConfig{CustomDomains: []string{"app.example.com"}},
|
||||
}},
|
||||
q: "app.example.com",
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "https subdomain",
|
||||
item: model.V2ProxyResp{Name: "https-proxy", Type: "https", Spec: &model.HTTPSOutConf{
|
||||
DomainConfig: v1.DomainConfig{SubDomain: "portal"},
|
||||
}},
|
||||
q: "portal",
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "subdomain does not match expanded host",
|
||||
item: model.V2ProxyResp{Name: "https-proxy", Type: "https", Spec: &model.HTTPSOutConf{
|
||||
DomainConfig: v1.DomainConfig{SubDomain: "portal"},
|
||||
}},
|
||||
q: "portal.example.com",
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "tcpmux custom domain",
|
||||
item: model.V2ProxyResp{Name: "tcpmux-proxy", Type: "tcpmux", Spec: &model.TCPMuxOutConf{
|
||||
DomainConfig: v1.DomainConfig{CustomDomains: []string{"mux.example.com"}},
|
||||
}},
|
||||
q: "mux.example.com",
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "nil spec does not match spec fields",
|
||||
item: model.V2ProxyResp{Name: "offline-proxy", Type: "tcp", Spec: nil},
|
||||
q: "6000",
|
||||
want: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := matchV2ProxyQuery(tt.item, tt.q); got != tt.want {
|
||||
t.Fatalf("matchV2ProxyQuery() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLegacyAPIResponsesRemainBare(t *testing.T) {
|
||||
controller := newV2TestController(t)
|
||||
router := newV2TestRouter(controller)
|
||||
|
||||
resp := performRequest(router, "/api/clients")
|
||||
var clients []model.ClientInfoResp
|
||||
if err := json.Unmarshal(resp.Body.Bytes(), &clients); err != nil {
|
||||
t.Fatalf("legacy clients should be a bare array: %v, body: %s", err, resp.Body.String())
|
||||
}
|
||||
if len(clients) != 3 {
|
||||
t.Fatalf("legacy clients total mismatch, want 3 got %d", len(clients))
|
||||
}
|
||||
|
||||
resp = performRequest(router, "/api/proxy/tcp")
|
||||
var proxies model.GetProxyInfoResp
|
||||
if err := json.Unmarshal(resp.Body.Bytes(), &proxies); err != nil {
|
||||
t.Fatalf("legacy proxy response should be {proxies}: %v, body: %s", err, resp.Body.String())
|
||||
}
|
||||
if len(proxies.Proxies) != 2 {
|
||||
t.Fatalf("legacy tcp proxy total mismatch, want 2 got %d", len(proxies.Proxies))
|
||||
}
|
||||
var envelope httppkg.V2Response
|
||||
if err := json.Unmarshal(resp.Body.Bytes(), &envelope); err == nil && envelope.Code != 0 {
|
||||
t.Fatalf("legacy proxy response should not use v2 envelope: %#v", envelope)
|
||||
}
|
||||
}
|
||||
|
||||
func newV2TestController(t *testing.T) *Controller {
|
||||
t.Helper()
|
||||
|
||||
oldStatsCollector := mem.StatsCollector
|
||||
mem.StatsCollector = &fakeStatsCollector{
|
||||
proxies: map[string]*mem.ProxyStats{
|
||||
"tcp-empty": {
|
||||
Name: "tcp-empty",
|
||||
Type: "tcp",
|
||||
User: "",
|
||||
ClientID: "legacy-client",
|
||||
TodayTrafficIn: 10,
|
||||
TodayTrafficOut: 20,
|
||||
CurConns: 1,
|
||||
},
|
||||
"tcp-alice": {
|
||||
Name: "tcp-alice",
|
||||
Type: "tcp",
|
||||
User: "alice",
|
||||
ClientID: "client-a",
|
||||
TodayTrafficIn: 30,
|
||||
TodayTrafficOut: 40,
|
||||
},
|
||||
"udp-bob": {
|
||||
Name: "udp-bob",
|
||||
Type: "udp",
|
||||
User: "bob",
|
||||
ClientID: "client-b",
|
||||
},
|
||||
},
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
mem.StatsCollector = oldStatsCollector
|
||||
})
|
||||
|
||||
clientRegistry := registry.NewClientRegistry()
|
||||
clientRegistry.Register("", "legacy-client", "run-empty", "empty-host", "1.0.0", "127.0.0.1", "v1")
|
||||
clientRegistry.Register("alice", "client-a", "run-a", "alice-host", "1.0.0", "127.0.0.2", "v2")
|
||||
clientRegistry.Register("bob", "client-b", "run-b", "bob-host", "1.0.0", "127.0.0.3", "v1")
|
||||
clientRegistry.MarkOfflineByRunID("run-b")
|
||||
|
||||
return NewController(&v1.ServerConfig{}, clientRegistry, serverproxy.NewManager(), nil)
|
||||
}
|
||||
|
||||
func newV2TestRouter(controller *Controller) *mux.Router {
|
||||
router := mux.NewRouter()
|
||||
router.HandleFunc("/api/v2/users", httppkg.MakeHTTPHandlerFuncV2(controller.APIV2UserList)).Methods(http.MethodGet)
|
||||
router.HandleFunc("/api/v2/clients", httppkg.MakeHTTPHandlerFuncV2(controller.APIV2ClientList)).Methods(http.MethodGet)
|
||||
router.HandleFunc("/api/v2/clients/{key}", httppkg.MakeHTTPHandlerFuncV2(controller.APIV2ClientDetail)).Methods(http.MethodGet)
|
||||
router.HandleFunc("/api/v2/proxies", httppkg.MakeHTTPHandlerFuncV2(controller.APIV2ProxyList)).Methods(http.MethodGet)
|
||||
router.HandleFunc("/api/v2/proxies/{name}", httppkg.MakeHTTPHandlerFuncV2(controller.APIV2ProxyDetail)).Methods(http.MethodGet)
|
||||
router.HandleFunc("/api/clients", httppkg.MakeHTTPHandlerFunc(controller.APIClientList)).Methods(http.MethodGet)
|
||||
router.HandleFunc("/api/proxy/{type}", httppkg.MakeHTTPHandlerFunc(controller.APIProxyByType)).Methods(http.MethodGet)
|
||||
return router
|
||||
}
|
||||
|
||||
func performRequest(handler http.Handler, target string) *httptest.ResponseRecorder {
|
||||
req := httptest.NewRequest(http.MethodGet, target, nil)
|
||||
resp := httptest.NewRecorder()
|
||||
handler.ServeHTTP(resp, req)
|
||||
return resp
|
||||
}
|
||||
|
||||
func decodeResponse[T any](t *testing.T, resp *httptest.ResponseRecorder) T {
|
||||
t.Helper()
|
||||
|
||||
var out T
|
||||
if err := json.Unmarshal(resp.Body.Bytes(), &out); err != nil {
|
||||
t.Fatalf("unmarshal response failed: %v, body: %s", err, resp.Body.String())
|
||||
}
|
||||
return out
|
||||
}
|
||||
136
server/http/model/types.go
Normal file
136
server/http/model/types.go
Normal file
@@ -0,0 +1,136 @@
|
||||
// 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 model
|
||||
|
||||
import (
|
||||
v1 "github.com/fatedier/frp/pkg/config/v1"
|
||||
)
|
||||
|
||||
type ServerInfoResp struct {
|
||||
Version string `json:"version"`
|
||||
BindPort int `json:"bindPort"`
|
||||
VhostHTTPPort int `json:"vhostHTTPPort"`
|
||||
VhostHTTPSPort int `json:"vhostHTTPSPort"`
|
||||
TCPMuxHTTPConnectPort int `json:"tcpmuxHTTPConnectPort"`
|
||||
KCPBindPort int `json:"kcpBindPort"`
|
||||
QUICBindPort int `json:"quicBindPort"`
|
||||
SubdomainHost string `json:"subdomainHost"`
|
||||
MaxPoolCount int64 `json:"maxPoolCount"`
|
||||
MaxPortsPerClient int64 `json:"maxPortsPerClient"`
|
||||
HeartBeatTimeout int64 `json:"heartbeatTimeout"`
|
||||
AllowPortsStr string `json:"allowPortsStr,omitempty"`
|
||||
TLSForce bool `json:"tlsForce,omitempty"`
|
||||
|
||||
TotalTrafficIn int64 `json:"totalTrafficIn"`
|
||||
TotalTrafficOut int64 `json:"totalTrafficOut"`
|
||||
CurConns int64 `json:"curConns"`
|
||||
ClientCounts int64 `json:"clientCounts"`
|
||||
ProxyTypeCounts map[string]int64 `json:"proxyTypeCount"`
|
||||
}
|
||||
|
||||
type ClientInfoResp struct {
|
||||
Key string `json:"key"`
|
||||
User string `json:"user"`
|
||||
ClientID string `json:"clientID"`
|
||||
RunID string `json:"runID"`
|
||||
Version string `json:"version,omitempty"`
|
||||
WireProtocol string `json:"wireProtocol,omitempty"`
|
||||
Hostname string `json:"hostname"`
|
||||
ClientIP string `json:"clientIP,omitempty"`
|
||||
FirstConnectedAt int64 `json:"firstConnectedAt"`
|
||||
LastConnectedAt int64 `json:"lastConnectedAt"`
|
||||
DisconnectedAt int64 `json:"disconnectedAt,omitempty"`
|
||||
Online bool `json:"online"`
|
||||
}
|
||||
|
||||
type BaseOutConf struct {
|
||||
v1.ProxyBaseConfig
|
||||
}
|
||||
|
||||
type TCPOutConf struct {
|
||||
BaseOutConf
|
||||
RemotePort int `json:"remotePort"`
|
||||
}
|
||||
|
||||
type TCPMuxOutConf struct {
|
||||
BaseOutConf
|
||||
v1.DomainConfig
|
||||
Multiplexer string `json:"multiplexer"`
|
||||
RouteByHTTPUser string `json:"routeByHTTPUser"`
|
||||
}
|
||||
|
||||
type UDPOutConf struct {
|
||||
BaseOutConf
|
||||
RemotePort int `json:"remotePort"`
|
||||
}
|
||||
|
||||
type HTTPOutConf struct {
|
||||
BaseOutConf
|
||||
v1.DomainConfig
|
||||
Locations []string `json:"locations"`
|
||||
HostHeaderRewrite string `json:"hostHeaderRewrite"`
|
||||
}
|
||||
|
||||
type HTTPSOutConf struct {
|
||||
BaseOutConf
|
||||
v1.DomainConfig
|
||||
}
|
||||
|
||||
type STCPOutConf struct {
|
||||
BaseOutConf
|
||||
}
|
||||
|
||||
type XTCPOutConf struct {
|
||||
BaseOutConf
|
||||
}
|
||||
|
||||
// Get proxy info.
|
||||
type ProxyStatsInfo struct {
|
||||
Name string `json:"name"`
|
||||
Conf any `json:"conf"`
|
||||
User string `json:"user,omitempty"`
|
||||
ClientID string `json:"clientID,omitempty"`
|
||||
TodayTrafficIn int64 `json:"todayTrafficIn"`
|
||||
TodayTrafficOut int64 `json:"todayTrafficOut"`
|
||||
CurConns int64 `json:"curConns"`
|
||||
LastStartTime string `json:"lastStartTime"`
|
||||
LastCloseTime string `json:"lastCloseTime"`
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
type GetProxyInfoResp struct {
|
||||
Proxies []*ProxyStatsInfo `json:"proxies"`
|
||||
}
|
||||
|
||||
// Get proxy info by name.
|
||||
type GetProxyStatsResp struct {
|
||||
Name string `json:"name"`
|
||||
Conf any `json:"conf"`
|
||||
User string `json:"user,omitempty"`
|
||||
ClientID string `json:"clientID,omitempty"`
|
||||
TodayTrafficIn int64 `json:"todayTrafficIn"`
|
||||
TodayTrafficOut int64 `json:"todayTrafficOut"`
|
||||
CurConns int64 `json:"curConns"`
|
||||
LastStartTime string `json:"lastStartTime"`
|
||||
LastCloseTime string `json:"lastCloseTime"`
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
// /api/traffic/:name
|
||||
type GetProxyTrafficResp struct {
|
||||
Name string `json:"name"`
|
||||
TrafficIn []int64 `json:"trafficIn"`
|
||||
TrafficOut []int64 `json:"trafficOut"`
|
||||
}
|
||||
46
server/http/model/v2.go
Normal file
46
server/http/model/v2.go
Normal file
@@ -0,0 +1,46 @@
|
||||
// Copyright 2026 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 model
|
||||
|
||||
type V2PageResp[T any] struct {
|
||||
Total int `json:"total"`
|
||||
Page int `json:"page"`
|
||||
PageSize int `json:"pageSize"`
|
||||
Items []T `json:"items"`
|
||||
}
|
||||
|
||||
type V2UserResp struct {
|
||||
User string `json:"user"`
|
||||
ClientCount int `json:"clientCount"`
|
||||
ProxyCount int `json:"proxyCount"`
|
||||
}
|
||||
|
||||
type V2ProxyResp struct {
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
User string `json:"user"`
|
||||
ClientID string `json:"clientID"`
|
||||
Spec any `json:"spec"`
|
||||
Status V2ProxyStatusResp `json:"status"`
|
||||
}
|
||||
|
||||
type V2ProxyStatusResp struct {
|
||||
State string `json:"phase"`
|
||||
TodayTrafficIn int64 `json:"todayTrafficIn"`
|
||||
TodayTrafficOut int64 `json:"todayTrafficOut"`
|
||||
CurConns int64 `json:"curConns"`
|
||||
LastStartTime string `json:"lastStartTime"`
|
||||
LastCloseTime string `json:"lastCloseTime"`
|
||||
}
|
||||
Reference in New Issue
Block a user