controller.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. // Copyright 2025 The frp Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package api
  15. import (
  16. "cmp"
  17. "encoding/json"
  18. "fmt"
  19. "net/http"
  20. "slices"
  21. "strings"
  22. "time"
  23. "github.com/fatedier/frp/pkg/config/types"
  24. v1 "github.com/fatedier/frp/pkg/config/v1"
  25. "github.com/fatedier/frp/pkg/metrics/mem"
  26. httppkg "github.com/fatedier/frp/pkg/util/http"
  27. "github.com/fatedier/frp/pkg/util/log"
  28. "github.com/fatedier/frp/pkg/util/version"
  29. "github.com/fatedier/frp/server/proxy"
  30. "github.com/fatedier/frp/server/registry"
  31. )
  32. type Controller struct {
  33. // dependencies
  34. serverCfg *v1.ServerConfig
  35. clientRegistry *registry.ClientRegistry
  36. pxyManager ProxyManager
  37. }
  38. type ProxyManager interface {
  39. GetByName(name string) (proxy.Proxy, bool)
  40. }
  41. func NewController(
  42. serverCfg *v1.ServerConfig,
  43. clientRegistry *registry.ClientRegistry,
  44. pxyManager ProxyManager,
  45. ) *Controller {
  46. return &Controller{
  47. serverCfg: serverCfg,
  48. clientRegistry: clientRegistry,
  49. pxyManager: pxyManager,
  50. }
  51. }
  52. // /api/serverinfo
  53. func (c *Controller) APIServerInfo(ctx *httppkg.Context) (any, error) {
  54. serverStats := mem.StatsCollector.GetServer()
  55. svrResp := ServerInfoResp{
  56. Version: version.Full(),
  57. BindPort: c.serverCfg.BindPort,
  58. VhostHTTPPort: c.serverCfg.VhostHTTPPort,
  59. VhostHTTPSPort: c.serverCfg.VhostHTTPSPort,
  60. TCPMuxHTTPConnectPort: c.serverCfg.TCPMuxHTTPConnectPort,
  61. KCPBindPort: c.serverCfg.KCPBindPort,
  62. QUICBindPort: c.serverCfg.QUICBindPort,
  63. SubdomainHost: c.serverCfg.SubDomainHost,
  64. MaxPoolCount: c.serverCfg.Transport.MaxPoolCount,
  65. MaxPortsPerClient: c.serverCfg.MaxPortsPerClient,
  66. HeartBeatTimeout: c.serverCfg.Transport.HeartbeatTimeout,
  67. AllowPortsStr: types.PortsRangeSlice(c.serverCfg.AllowPorts).String(),
  68. TLSForce: c.serverCfg.Transport.TLS.Force,
  69. TotalTrafficIn: serverStats.TotalTrafficIn,
  70. TotalTrafficOut: serverStats.TotalTrafficOut,
  71. CurConns: serverStats.CurConns,
  72. ClientCounts: serverStats.ClientCounts,
  73. ProxyTypeCounts: serverStats.ProxyTypeCounts,
  74. }
  75. // For API that returns struct, we can just return it.
  76. // But current GeneralResponse.Msg in legacy code expects a JSON string.
  77. // Since MakeHTTPHandlerFunc handles struct by encoding to JSON, we can return svrResp directly?
  78. // The original code wraps it in GeneralResponse{Msg: string(json)}.
  79. // If we return svrResp, the response body will be the JSON of svrResp.
  80. // We should check if the frontend expects { "code": 200, "msg": "{...}" } or just {...}.
  81. // Looking at previous code:
  82. // res := GeneralResponse{Code: 200}
  83. // buf, _ := json.Marshal(&svrResp)
  84. // res.Msg = string(buf)
  85. // Response body: {"code": 200, "msg": "{\"version\":...}"}
  86. // Wait, is it double encoded JSON? Yes it seems so!
  87. // Let's check dashboard_api.go original code again.
  88. // Yes: res.Msg = string(buf).
  89. // So the frontend expects { "code": 200, "msg": "JSON_STRING" }.
  90. // This is kind of ugly, but we must preserve compatibility.
  91. return svrResp, nil
  92. }
  93. // /api/clients
  94. func (c *Controller) APIClientList(ctx *httppkg.Context) (any, error) {
  95. if c.clientRegistry == nil {
  96. return nil, fmt.Errorf("client registry unavailable")
  97. }
  98. userFilter := ctx.Query("user")
  99. clientIDFilter := ctx.Query("clientId")
  100. runIDFilter := ctx.Query("runId")
  101. statusFilter := strings.ToLower(ctx.Query("status"))
  102. records := c.clientRegistry.List()
  103. items := make([]ClientInfoResp, 0, len(records))
  104. for _, info := range records {
  105. if userFilter != "" && info.User != userFilter {
  106. continue
  107. }
  108. if clientIDFilter != "" && info.ClientID != clientIDFilter {
  109. continue
  110. }
  111. if runIDFilter != "" && info.RunID != runIDFilter {
  112. continue
  113. }
  114. if !matchStatusFilter(info.Online, statusFilter) {
  115. continue
  116. }
  117. items = append(items, buildClientInfoResp(info))
  118. }
  119. slices.SortFunc(items, func(a, b ClientInfoResp) int {
  120. if v := cmp.Compare(a.User, b.User); v != 0 {
  121. return v
  122. }
  123. if v := cmp.Compare(a.ClientID, b.ClientID); v != 0 {
  124. return v
  125. }
  126. return cmp.Compare(a.Key, b.Key)
  127. })
  128. return items, nil
  129. }
  130. // /api/clients/{key}
  131. func (c *Controller) APIClientDetail(ctx *httppkg.Context) (any, error) {
  132. key := ctx.Param("key")
  133. if key == "" {
  134. return nil, fmt.Errorf("missing client key")
  135. }
  136. if c.clientRegistry == nil {
  137. return nil, fmt.Errorf("client registry unavailable")
  138. }
  139. info, ok := c.clientRegistry.GetByKey(key)
  140. if !ok {
  141. return nil, httppkg.NewError(http.StatusNotFound, fmt.Sprintf("client %s not found", key))
  142. }
  143. return buildClientInfoResp(info), nil
  144. }
  145. // /api/proxy/:type
  146. func (c *Controller) APIProxyByType(ctx *httppkg.Context) (any, error) {
  147. proxyType := ctx.Param("type")
  148. proxyInfoResp := GetProxyInfoResp{}
  149. proxyInfoResp.Proxies = c.getProxyStatsByType(proxyType)
  150. slices.SortFunc(proxyInfoResp.Proxies, func(a, b *ProxyStatsInfo) int {
  151. return cmp.Compare(a.Name, b.Name)
  152. })
  153. return proxyInfoResp, nil
  154. }
  155. // /api/proxy/:type/:name
  156. func (c *Controller) APIProxyByTypeAndName(ctx *httppkg.Context) (any, error) {
  157. proxyType := ctx.Param("type")
  158. name := ctx.Param("name")
  159. proxyStatsResp, code, msg := c.getProxyStatsByTypeAndName(proxyType, name)
  160. if code != 200 {
  161. return nil, httppkg.NewError(code, msg)
  162. }
  163. return proxyStatsResp, nil
  164. }
  165. // /api/traffic/:name
  166. func (c *Controller) APIProxyTraffic(ctx *httppkg.Context) (any, error) {
  167. name := ctx.Param("name")
  168. trafficResp := GetProxyTrafficResp{}
  169. trafficResp.Name = name
  170. proxyTrafficInfo := mem.StatsCollector.GetProxyTraffic(name)
  171. if proxyTrafficInfo == nil {
  172. return nil, httppkg.NewError(http.StatusNotFound, "no proxy info found")
  173. }
  174. trafficResp.TrafficIn = proxyTrafficInfo.TrafficIn
  175. trafficResp.TrafficOut = proxyTrafficInfo.TrafficOut
  176. return trafficResp, nil
  177. }
  178. // DELETE /api/proxies?status=offline
  179. func (c *Controller) DeleteProxies(ctx *httppkg.Context) (any, error) {
  180. status := ctx.Query("status")
  181. if status != "offline" {
  182. return nil, httppkg.NewError(http.StatusBadRequest, "status only support offline")
  183. }
  184. cleared, total := mem.StatsCollector.ClearOfflineProxies()
  185. log.Infof("cleared [%d] offline proxies, total [%d] proxies", cleared, total)
  186. return nil, nil
  187. }
  188. func (c *Controller) getProxyStatsByType(proxyType string) (proxyInfos []*ProxyStatsInfo) {
  189. proxyStats := mem.StatsCollector.GetProxiesByType(proxyType)
  190. proxyInfos = make([]*ProxyStatsInfo, 0, len(proxyStats))
  191. for _, ps := range proxyStats {
  192. proxyInfo := &ProxyStatsInfo{}
  193. if pxy, ok := c.pxyManager.GetByName(ps.Name); ok {
  194. content, err := json.Marshal(pxy.GetConfigurer())
  195. if err != nil {
  196. log.Warnf("marshal proxy [%s] conf info error: %v", ps.Name, err)
  197. continue
  198. }
  199. proxyInfo.Conf = getConfByType(ps.Type)
  200. if err = json.Unmarshal(content, &proxyInfo.Conf); err != nil {
  201. log.Warnf("unmarshal proxy [%s] conf info error: %v", ps.Name, err)
  202. continue
  203. }
  204. proxyInfo.Status = "online"
  205. if pxy.GetLoginMsg() != nil {
  206. proxyInfo.ClientVersion = pxy.GetLoginMsg().Version
  207. }
  208. } else {
  209. proxyInfo.Status = "offline"
  210. }
  211. proxyInfo.Name = ps.Name
  212. proxyInfo.TodayTrafficIn = ps.TodayTrafficIn
  213. proxyInfo.TodayTrafficOut = ps.TodayTrafficOut
  214. proxyInfo.CurConns = ps.CurConns
  215. proxyInfo.LastStartTime = ps.LastStartTime
  216. proxyInfo.LastCloseTime = ps.LastCloseTime
  217. proxyInfos = append(proxyInfos, proxyInfo)
  218. }
  219. return
  220. }
  221. func (c *Controller) getProxyStatsByTypeAndName(proxyType string, proxyName string) (proxyInfo GetProxyStatsResp, code int, msg string) {
  222. proxyInfo.Name = proxyName
  223. ps := mem.StatsCollector.GetProxiesByTypeAndName(proxyType, proxyName)
  224. if ps == nil {
  225. code = 404
  226. msg = "no proxy info found"
  227. } else {
  228. if pxy, ok := c.pxyManager.GetByName(proxyName); ok {
  229. content, err := json.Marshal(pxy.GetConfigurer())
  230. if err != nil {
  231. log.Warnf("marshal proxy [%s] conf info error: %v", ps.Name, err)
  232. code = 400
  233. msg = "parse conf error"
  234. return
  235. }
  236. proxyInfo.Conf = getConfByType(ps.Type)
  237. if err = json.Unmarshal(content, &proxyInfo.Conf); err != nil {
  238. log.Warnf("unmarshal proxy [%s] conf info error: %v", ps.Name, err)
  239. code = 400
  240. msg = "parse conf error"
  241. return
  242. }
  243. proxyInfo.Status = "online"
  244. } else {
  245. proxyInfo.Status = "offline"
  246. }
  247. proxyInfo.TodayTrafficIn = ps.TodayTrafficIn
  248. proxyInfo.TodayTrafficOut = ps.TodayTrafficOut
  249. proxyInfo.CurConns = ps.CurConns
  250. proxyInfo.LastStartTime = ps.LastStartTime
  251. proxyInfo.LastCloseTime = ps.LastCloseTime
  252. code = 200
  253. }
  254. return
  255. }
  256. func buildClientInfoResp(info registry.ClientInfo) ClientInfoResp {
  257. resp := ClientInfoResp{
  258. Key: info.Key,
  259. User: info.User,
  260. ClientID: info.ClientID,
  261. RunID: info.RunID,
  262. Hostname: info.Hostname,
  263. ClientIP: info.IP,
  264. FirstConnectedAt: toUnix(info.FirstConnectedAt),
  265. LastConnectedAt: toUnix(info.LastConnectedAt),
  266. Online: info.Online,
  267. }
  268. if !info.DisconnectedAt.IsZero() {
  269. resp.DisconnectedAt = info.DisconnectedAt.Unix()
  270. }
  271. return resp
  272. }
  273. func toUnix(t time.Time) int64 {
  274. if t.IsZero() {
  275. return 0
  276. }
  277. return t.Unix()
  278. }
  279. func matchStatusFilter(online bool, filter string) bool {
  280. switch strings.ToLower(filter) {
  281. case "", "all":
  282. return true
  283. case "online":
  284. return online
  285. case "offline":
  286. return !online
  287. default:
  288. return true
  289. }
  290. }
  291. func getConfByType(proxyType string) any {
  292. switch v1.ProxyType(proxyType) {
  293. case v1.ProxyTypeTCP:
  294. return &TCPOutConf{}
  295. case v1.ProxyTypeTCPMUX:
  296. return &TCPMuxOutConf{}
  297. case v1.ProxyTypeUDP:
  298. return &UDPOutConf{}
  299. case v1.ProxyTypeHTTP:
  300. return &HTTPOutConf{}
  301. case v1.ProxyTypeHTTPS:
  302. return &HTTPSOutConf{}
  303. case v1.ProxyTypeSTCP:
  304. return &STCPOutConf{}
  305. case v1.ProxyTypeXTCP:
  306. return &XTCPOutConf{}
  307. default:
  308. return nil
  309. }
  310. }