node.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906
  1. package service
  2. import (
  3. "context"
  4. "crypto/sha256"
  5. "crypto/tls"
  6. "encoding/base64"
  7. "encoding/json"
  8. "errors"
  9. "fmt"
  10. "net"
  11. "net/http"
  12. "net/url"
  13. "slices"
  14. "strconv"
  15. "strings"
  16. "time"
  17. "github.com/mhsanaei/3x-ui/v3/internal/database"
  18. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  19. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  20. "github.com/mhsanaei/3x-ui/v3/internal/util/common"
  21. "github.com/mhsanaei/3x-ui/v3/internal/util/json_util"
  22. "github.com/mhsanaei/3x-ui/v3/internal/util/netsafe"
  23. "github.com/mhsanaei/3x-ui/v3/internal/web/runtime"
  24. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  25. )
  26. type HeartbeatPatch struct {
  27. Status string
  28. LastHeartbeat int64
  29. LatencyMs int
  30. XrayVersion string
  31. PanelVersion string
  32. Guid string
  33. CpuPct float64
  34. MemPct float64
  35. UptimeSecs uint64
  36. // NetUp/NetDown are the node's current interface throughput (bytes/sec),
  37. // summed over non-virtual interfaces, read from its status response.
  38. NetUp uint64
  39. NetDown uint64
  40. LastError string
  41. // XrayState and XrayError come from the remote /panel/api/server/status when the
  42. // panel API is reachable. They allow distinguishing panel connectivity from
  43. // Xray core health on the node.
  44. XrayState string
  45. XrayError string
  46. }
  47. type NodeService struct{}
  48. // FetchCertFingerprint connects to the node over HTTPS without verifying the
  49. // certificate and returns the leaf certificate's SHA-256 as base64, so the UI
  50. // can offer a "fetch and pin current certificate" action.
  51. func (s *NodeService) FetchCertFingerprint(ctx context.Context, n *model.Node) (string, error) {
  52. addr, err := netsafe.NormalizeHost(n.Address)
  53. if err != nil {
  54. return "", err
  55. }
  56. scheme := n.Scheme
  57. if scheme != "http" && scheme != "https" {
  58. scheme = "https"
  59. }
  60. if scheme != "https" {
  61. return "", common.NewError("certificate pinning is only available for https nodes")
  62. }
  63. if n.Port <= 0 || n.Port > 65535 {
  64. return "", common.NewError("node port must be 1-65535")
  65. }
  66. probeURL := &url.URL{
  67. Scheme: scheme,
  68. Host: net.JoinHostPort(addr, strconv.Itoa(n.Port)),
  69. Path: normalizeBasePath(n.BasePath) + "panel/api/server/status",
  70. }
  71. req, err := http.NewRequestWithContext(
  72. netsafe.ContextWithAllowPrivate(ctx, n.AllowPrivateAddress),
  73. http.MethodGet, probeURL.String(), nil)
  74. if err != nil {
  75. return "", err
  76. }
  77. client := &http.Client{
  78. Transport: &http.Transport{
  79. DialContext: netsafe.SSRFGuardedDialContext,
  80. TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // lgtm[go/disabled-certificate-check]
  81. },
  82. }
  83. resp, err := client.Do(req)
  84. if err != nil {
  85. return "", err
  86. }
  87. defer resp.Body.Close()
  88. if resp.TLS == nil || len(resp.TLS.PeerCertificates) == 0 {
  89. return "", common.NewError("node did not present a TLS certificate")
  90. }
  91. sum := sha256.Sum256(resp.TLS.PeerCertificates[0].Raw)
  92. return base64.StdEncoding.EncodeToString(sum[:]), nil
  93. }
  94. func (s *NodeService) GetAll() ([]*model.Node, error) {
  95. db := database.GetDB()
  96. var nodes []*model.Node
  97. err := db.Model(model.Node{}).Order("id asc").Find(&nodes).Error
  98. if err != nil || len(nodes) == 0 {
  99. return nodes, err
  100. }
  101. type inboundRow struct {
  102. Id int
  103. NodeID int `gorm:"column:node_id"`
  104. }
  105. var inboundRows []inboundRow
  106. if err := db.Table("inbounds").
  107. Select("id, node_id").
  108. Where("node_id IS NOT NULL").
  109. Scan(&inboundRows).Error; err != nil {
  110. return nodes, nil
  111. }
  112. if len(inboundRows) == 0 {
  113. return nodes, nil
  114. }
  115. inboundsByNode := make(map[int][]int, len(nodes))
  116. nodeByInbound := make(map[int]int, len(inboundRows))
  117. for _, row := range inboundRows {
  118. inboundsByNode[row.NodeID] = append(inboundsByNode[row.NodeID], row.Id)
  119. nodeByInbound[row.Id] = row.NodeID
  120. }
  121. type clientCountRow struct {
  122. NodeID int `gorm:"column:node_id"`
  123. Count int `gorm:"column:count"`
  124. }
  125. var clientCounts []clientCountRow
  126. if err := db.Raw(`
  127. SELECT inbounds.node_id AS node_id, COUNT(DISTINCT client_inbounds.client_id) AS count
  128. FROM inbounds
  129. JOIN client_inbounds ON client_inbounds.inbound_id = inbounds.id
  130. WHERE inbounds.node_id IS NOT NULL
  131. GROUP BY inbounds.node_id
  132. `).Scan(&clientCounts).Error; err == nil {
  133. for _, row := range clientCounts {
  134. for _, n := range nodes {
  135. if n.Id == row.NodeID {
  136. n.ClientCount = row.Count
  137. break
  138. }
  139. }
  140. }
  141. }
  142. now := time.Now().UnixMilli()
  143. type trafficRow struct {
  144. InboundID int `gorm:"column:inbound_id"`
  145. Email string
  146. Enable bool
  147. Total int64
  148. Up int64
  149. Down int64
  150. ExpiryTime int64 `gorm:"column:expiry_time"`
  151. }
  152. var trafficRows []trafficRow
  153. inboundIDs := make([]int, 0, len(nodeByInbound))
  154. for id := range nodeByInbound {
  155. inboundIDs = append(inboundIDs, id)
  156. }
  157. // Chunk the IN clause to avoid "too many SQL variables" on SQLite
  158. // when there are many node-owned inbounds (common with many nodes).
  159. // sqliteMaxVars is defined in this package (inbound.go).
  160. for _, batch := range chunkInts(inboundIDs, sqliteMaxVars) {
  161. var page []trafficRow
  162. if err := db.Table("client_traffics").
  163. Select("inbound_id, email, enable, total, up, down, expiry_time").
  164. Where("inbound_id IN ?", batch).
  165. Scan(&page).Error; err == nil {
  166. trafficRows = append(trafficRows, page...)
  167. }
  168. }
  169. depletedByNode := make(map[int]int)
  170. if len(trafficRows) > 0 {
  171. for _, row := range trafficRows {
  172. nodeID, ok := nodeByInbound[row.InboundID]
  173. if !ok {
  174. continue
  175. }
  176. expired := row.ExpiryTime > 0 && row.ExpiryTime <= now
  177. exhausted := row.Total > 0 && row.Up+row.Down >= row.Total
  178. if expired || exhausted || !row.Enable {
  179. depletedByNode[nodeID]++
  180. }
  181. }
  182. }
  183. onlineByGuid := s.onlineEmailsByGuid()
  184. for _, n := range nodes {
  185. n.InboundCount = len(inboundsByNode[n.Id])
  186. n.DepletedCount = depletedByNode[n.Id]
  187. // Online is attributed to the node that physically hosts the client
  188. // (by GUID): a client on a sub-node counts under the sub-node, not
  189. // the intermediate node it syncs through (#4983).
  190. n.OnlineCount = len(onlineByGuid[effectiveNodeGuid(n)])
  191. }
  192. return nodes, nil
  193. }
  194. func (s *NodeService) onlineEmailsByGuid() map[string]map[string]struct{} {
  195. svc := InboundService{}
  196. byGuid := svc.GetOnlineClientsByGuid()
  197. out := make(map[string]map[string]struct{}, len(byGuid))
  198. for guid, emails := range byGuid {
  199. set := make(map[string]struct{}, len(emails))
  200. for _, email := range emails {
  201. set[email] = struct{}{}
  202. }
  203. out[guid] = set
  204. }
  205. return out
  206. }
  207. // effectiveNodeGuid is a node's stable online-attribution key: its reported
  208. // panelGuid, or a master-local synthetic id when the node is an old build that
  209. // hasn't reported one yet (#4983).
  210. func effectiveNodeGuid(n *model.Node) string {
  211. if n.Guid != "" {
  212. return n.Guid
  213. }
  214. return synthNodeGuid(n.Id)
  215. }
  216. func (s *NodeService) GetById(id int) (*model.Node, error) {
  217. db := database.GetDB()
  218. n := &model.Node{}
  219. if err := db.Model(model.Node{}).Where("id = ?", id).First(n).Error; err != nil {
  220. return nil, err
  221. }
  222. return n, nil
  223. }
  224. // NodeExists reports whether a node with the given id exists on this panel.
  225. // Used to drop stale, cross-panel node references on inbound import. A Count
  226. // query distinguishes "no such node" (count 0, no error) from a real DB error.
  227. func (s *NodeService) NodeExists(id int) (bool, error) {
  228. if id <= 0 {
  229. return false, nil
  230. }
  231. var count int64
  232. if err := database.GetDB().Model(model.Node{}).Where("id = ?", id).Count(&count).Error; err != nil {
  233. return false, err
  234. }
  235. return count > 0, nil
  236. }
  237. func normalizeBasePath(p string) string {
  238. p = strings.TrimSpace(p)
  239. if p == "" {
  240. return "/"
  241. }
  242. if !strings.HasPrefix(p, "/") {
  243. p = "/" + p
  244. }
  245. if !strings.HasSuffix(p, "/") {
  246. p = p + "/"
  247. }
  248. return p
  249. }
  250. func (s *NodeService) normalize(n *model.Node) error {
  251. n.Name = strings.TrimSpace(n.Name)
  252. n.ApiToken = strings.TrimSpace(n.ApiToken)
  253. if n.Name == "" {
  254. return common.NewError("node name is required")
  255. }
  256. addr, err := netsafe.NormalizeHost(n.Address)
  257. if err != nil {
  258. return common.NewError(err.Error())
  259. }
  260. n.Address = addr
  261. if n.Port <= 0 || n.Port > 65535 {
  262. return common.NewError("node port must be 1-65535")
  263. }
  264. if n.Scheme != "http" && n.Scheme != "https" {
  265. n.Scheme = "https"
  266. }
  267. if n.TlsVerifyMode != "skip" && n.TlsVerifyMode != "pin" && n.TlsVerifyMode != "mtls" {
  268. n.TlsVerifyMode = "verify"
  269. }
  270. if n.TlsVerifyMode == "mtls" && n.Scheme != "https" {
  271. return common.NewError("mtls requires the node scheme to be https")
  272. }
  273. n.PinnedCertSha256 = strings.TrimSpace(n.PinnedCertSha256)
  274. if n.InboundSyncMode != "selected" {
  275. n.InboundSyncMode = "all"
  276. n.InboundTags = nil
  277. } else {
  278. seen := make(map[string]struct{}, len(n.InboundTags))
  279. tags := make([]string, 0, len(n.InboundTags))
  280. for _, tag := range n.InboundTags {
  281. tag = strings.TrimSpace(tag)
  282. if tag == "" {
  283. continue
  284. }
  285. if _, ok := seen[tag]; ok {
  286. continue
  287. }
  288. seen[tag] = struct{}{}
  289. tags = append(tags, tag)
  290. }
  291. n.InboundTags = tags
  292. }
  293. if n.TlsVerifyMode == "pin" {
  294. if _, err := runtime.DecodeCertPin(n.PinnedCertSha256); err != nil {
  295. return common.NewError(err.Error())
  296. }
  297. }
  298. n.BasePath = normalizeBasePath(n.BasePath)
  299. return nil
  300. }
  301. func (s *NodeService) Create(n *model.Node) error {
  302. if err := s.normalize(n); err != nil {
  303. return err
  304. }
  305. db := database.GetDB()
  306. return db.Create(n).Error
  307. }
  308. func (s *NodeService) Update(id int, in *model.Node) error {
  309. if err := s.normalize(in); err != nil {
  310. return err
  311. }
  312. inboundTagsJSON, err := json.Marshal(in.InboundTags)
  313. if err != nil {
  314. return err
  315. }
  316. db := database.GetDB()
  317. existing := &model.Node{}
  318. if err := db.Where("id = ?", id).First(existing).Error; err != nil {
  319. return err
  320. }
  321. updates := map[string]any{
  322. "name": in.Name,
  323. "remark": in.Remark,
  324. "scheme": in.Scheme,
  325. "address": in.Address,
  326. "port": in.Port,
  327. "base_path": in.BasePath,
  328. "api_token": in.ApiToken,
  329. "enable": in.Enable,
  330. "allow_private_address": in.AllowPrivateAddress,
  331. "tls_verify_mode": in.TlsVerifyMode,
  332. "pinned_cert_sha256": in.PinnedCertSha256,
  333. "inbound_sync_mode": in.InboundSyncMode,
  334. "inbound_tags": string(inboundTagsJSON),
  335. "outbound_tag": in.OutboundTag,
  336. }
  337. if err := db.Model(model.Node{}).Where("id = ?", id).Updates(updates).Error; err != nil {
  338. return err
  339. }
  340. if mgr := runtime.GetManager(); mgr != nil {
  341. mgr.InvalidateNode(id)
  342. }
  343. return nil
  344. }
  345. func (s *NodeService) GetRemoteInboundOptions(ctx context.Context, n *model.Node) ([]runtime.RemoteInboundOption, error) {
  346. if err := s.normalize(n); err != nil {
  347. return nil, err
  348. }
  349. if n.OutboundTag == "" {
  350. return runtime.NewRemote(n, nil).ListInboundOptions(ctx)
  351. }
  352. // Mirror ProbeWithOutbound: a node being added/edited has no persistent
  353. // egress bridge yet, so route the list call through a temporary one or the
  354. // remote panel stays unreachable and the request times out.
  355. var options []runtime.RemoteInboundOption
  356. var err error
  357. s.withOutboundBridge(n.Id, n.OutboundTag, func(proxyURL string) {
  358. options, err = runtime.NewRemote(n, staticEgressResolver(proxyURL)).ListInboundOptions(ctx)
  359. })
  360. return options, err
  361. }
  362. // staticEgressResolver hands a fixed proxy URL to runtime.NewRemote. An empty
  363. // string yields a direct connection, so it doubles as the graceful fallback
  364. // when a temporary bridge can't be built.
  365. type staticEgressResolver string
  366. func (r staticEgressResolver) NodeEgressProxyURL(int) string { return string(r) }
  367. // EnsureInboundTagAllowed adds a panel-managed inbound's tag to the node's
  368. // selection when the node syncs in "selected" mode. Without it, the next
  369. // traffic sync would filter the tag out of the snapshot and the orphan sweep
  370. // would silently delete the central row the panel just created or renamed.
  371. // Tags are only ever added (never removed): on a rename the node may keep
  372. // reporting the old tag until the remote update lands, and a leftover entry
  373. // that matches nothing is harmless.
  374. func (s *NodeService) EnsureInboundTagAllowed(nodeID int, tag string) error {
  375. tag = strings.TrimSpace(tag)
  376. if nodeID <= 0 || tag == "" {
  377. return nil
  378. }
  379. db := database.GetDB()
  380. node := &model.Node{}
  381. if err := db.Where("id = ?", nodeID).First(node).Error; err != nil {
  382. return err
  383. }
  384. if node.InboundSyncMode != "selected" {
  385. return nil
  386. }
  387. if slices.Contains(node.InboundTags, tag) {
  388. return nil
  389. }
  390. buf, err := json.Marshal(append(node.InboundTags, tag))
  391. if err != nil {
  392. return err
  393. }
  394. return db.Model(model.Node{}).Where("id = ?", nodeID).
  395. Updates(map[string]any{"inbound_tags": string(buf)}).Error
  396. }
  397. func FilterNodeSnapshot(n *model.Node, snap *runtime.TrafficSnapshot) {
  398. if n == nil || snap == nil || n.InboundSyncMode != "selected" {
  399. return
  400. }
  401. allowed := make(map[string]struct{}, len(n.InboundTags))
  402. for _, tag := range n.InboundTags {
  403. allowed[tag] = struct{}{}
  404. }
  405. filtered := make([]*model.Inbound, 0, len(snap.Inbounds))
  406. for _, inbound := range snap.Inbounds {
  407. if inbound == nil {
  408. continue
  409. }
  410. if _, ok := allowed[inbound.Tag]; ok {
  411. filtered = append(filtered, inbound)
  412. }
  413. }
  414. snap.Inbounds = filtered
  415. }
  416. func (s *NodeService) Delete(id int) error {
  417. db := database.GetDB()
  418. // Capture the node's guid before deleting the row so we can drop its per-node
  419. // IP attribution (NodeClientIp is keyed by guid, not node id).
  420. var guid string
  421. var n model.Node
  422. if err := db.Select("guid").Where("id = ?", id).First(&n).Error; err == nil {
  423. guid = n.Guid
  424. }
  425. if err := db.Where("id = ?", id).Delete(model.Node{}).Error; err != nil {
  426. return err
  427. }
  428. if err := db.Where("node_id = ?", id).Delete(&model.NodeClientTraffic{}).Error; err != nil {
  429. return err
  430. }
  431. if guid != "" {
  432. if err := db.Where("node_guid = ?", guid).Delete(&model.NodeClientIp{}).Error; err != nil {
  433. return err
  434. }
  435. }
  436. if mgr := runtime.GetManager(); mgr != nil {
  437. mgr.InvalidateNode(id)
  438. }
  439. nodeMetrics.drop(nodeMetricKey(id, "cpu"))
  440. nodeMetrics.drop(nodeMetricKey(id, "mem"))
  441. return nil
  442. }
  443. func (s *NodeService) SetEnable(id int, enable bool) error {
  444. db := database.GetDB()
  445. if err := db.Model(model.Node{}).Where("id = ?", id).Update("enable", enable).Error; err != nil {
  446. return err
  447. }
  448. if mgr := runtime.GetManager(); mgr != nil {
  449. mgr.InvalidateNode(id)
  450. }
  451. return nil
  452. }
  453. // GetWebCertFiles asks a node for its own web TLS certificate/key file paths,
  454. // used by "Set Cert from Panel" so a node-assigned inbound gets paths that
  455. // exist on the node rather than the central panel. See issue #4854.
  456. func (s *NodeService) GetWebCertFiles(id int) (*runtime.WebCertFiles, error) {
  457. n, err := s.GetById(id)
  458. if err != nil || n == nil {
  459. return nil, fmt.Errorf("node not found")
  460. }
  461. if !n.Enable {
  462. return nil, fmt.Errorf("node is disabled")
  463. }
  464. mgr := runtime.GetManager()
  465. if mgr == nil {
  466. return nil, fmt.Errorf("runtime manager unavailable")
  467. }
  468. remote, err := mgr.RemoteFor(n)
  469. if err != nil {
  470. return nil, err
  471. }
  472. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  473. defer cancel()
  474. return remote.GetWebCertFiles(ctx)
  475. }
  476. // NodeUpdateResult reports the outcome of triggering a panel self-update on one
  477. // node so the UI can show per-node success/failure for a bulk request.
  478. type NodeUpdateResult struct {
  479. Id int `json:"id"`
  480. Name string `json:"name"`
  481. OK bool `json:"ok"`
  482. Error string `json:"error,omitempty"`
  483. }
  484. // UpdatePanels triggers the official self-updater on each given node. Only
  485. // enabled, online nodes are eligible — an offline node can't be reached, so it
  486. // is reported as skipped rather than silently dropped.
  487. func (s *NodeService) UpdatePanels(ids []int) ([]NodeUpdateResult, error) {
  488. mgr := runtime.GetManager()
  489. if mgr == nil {
  490. return nil, fmt.Errorf("runtime manager unavailable")
  491. }
  492. results := make([]NodeUpdateResult, 0, len(ids))
  493. for _, id := range ids {
  494. n, err := s.GetById(id)
  495. if err != nil || n == nil {
  496. results = append(results, NodeUpdateResult{Id: id, OK: false, Error: "node not found"})
  497. continue
  498. }
  499. res := NodeUpdateResult{Id: id, Name: n.Name}
  500. switch {
  501. case !n.Enable:
  502. res.Error = "node is disabled"
  503. case n.Status != "online":
  504. res.Error = "node is offline"
  505. default:
  506. remote, remoteErr := mgr.RemoteFor(n)
  507. if remoteErr != nil {
  508. res.Error = remoteErr.Error()
  509. break
  510. }
  511. ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
  512. updErr := remote.UpdatePanel(ctx)
  513. cancel()
  514. if updErr != nil {
  515. res.Error = updErr.Error()
  516. } else {
  517. res.OK = true
  518. }
  519. }
  520. results = append(results, res)
  521. }
  522. return results, nil
  523. }
  524. func (s *NodeService) UpdateHeartbeat(id int, p HeartbeatPatch) error {
  525. db := database.GetDB()
  526. updates := map[string]any{
  527. "status": p.Status,
  528. "last_heartbeat": p.LastHeartbeat,
  529. "latency_ms": p.LatencyMs,
  530. "xray_version": p.XrayVersion,
  531. "panel_version": p.PanelVersion,
  532. "cpu_pct": p.CpuPct,
  533. "mem_pct": p.MemPct,
  534. "uptime_secs": p.UptimeSecs,
  535. "net_up": p.NetUp,
  536. "net_down": p.NetDown,
  537. "last_error": p.LastError,
  538. "xray_state": p.XrayState,
  539. "xray_error": p.XrayError,
  540. }
  541. // Only learn the GUID; never clear a known one if an old-build node (or a
  542. // failed probe) reports none, so the stable identity survives blips.
  543. if p.Guid != "" {
  544. updates["guid"] = p.Guid
  545. }
  546. if err := db.Model(model.Node{}).Where("id = ?", id).Updates(updates).Error; err != nil {
  547. return err
  548. }
  549. if p.Status == "online" {
  550. now := time.Unix(p.LastHeartbeat, 0)
  551. nodeMetrics.append(nodeMetricKey(id, "cpu"), now, p.CpuPct)
  552. nodeMetrics.append(nodeMetricKey(id, "mem"), now, p.MemPct)
  553. nodeMetrics.append(nodeMetricKey(id, "netUp"), now, float64(p.NetUp))
  554. nodeMetrics.append(nodeMetricKey(id, "netDown"), now, float64(p.NetDown))
  555. }
  556. return nil
  557. }
  558. func (s *NodeService) MarkNodeDirty(id int) error {
  559. if id <= 0 {
  560. return nil
  561. }
  562. return database.GetDB().Model(model.Node{}).
  563. Where("id = ?", id).
  564. Updates(map[string]any{
  565. "config_dirty": true,
  566. "config_dirty_at": time.Now().UnixMilli(),
  567. }).Error
  568. }
  569. func (s *NodeService) ClearNodeDirty(id int, dirtyAt int64) error {
  570. if id <= 0 {
  571. return nil
  572. }
  573. return database.GetDB().Model(model.Node{}).
  574. Where("id = ? AND config_dirty_at = ?", id, dirtyAt).
  575. Update("config_dirty", false).Error
  576. }
  577. func (s *NodeService) NodeSyncState(id int) (enabled bool, status string, dirty bool, dirtyAt int64, err error) {
  578. if id <= 0 {
  579. return false, "", false, 0, errors.New("invalid node id")
  580. }
  581. var row model.Node
  582. err = database.GetDB().Model(model.Node{}).
  583. Select("enable", "status", "config_dirty", "config_dirty_at").
  584. Where("id = ?", id).
  585. First(&row).Error
  586. if err != nil {
  587. return false, "", false, 0, err
  588. }
  589. return row.Enable, row.Status, row.ConfigDirty, row.ConfigDirtyAt, nil
  590. }
  591. func (s *NodeService) IsNodePending(id int) bool {
  592. enabled, status, dirty, _, err := s.NodeSyncState(id)
  593. if err != nil {
  594. return false
  595. }
  596. return !enabled || status != "online" || dirty
  597. }
  598. func nodeMetricKey(id int, metric string) string {
  599. return "node:" + strconv.Itoa(id) + ":" + metric
  600. }
  601. func (s *NodeService) AggregateNodeMetric(id int, metric string, bucketSeconds int, maxPoints int) []map[string]any {
  602. return nodeMetrics.aggregate(nodeMetricKey(id, metric), bucketSeconds, maxPoints)
  603. }
  604. func (s *NodeService) Probe(ctx context.Context, n *model.Node) (HeartbeatPatch, error) {
  605. proxyURL := ""
  606. if n.OutboundTag != "" {
  607. if mgr := runtime.GetManager(); mgr != nil {
  608. proxyURL = mgr.NodeEgressProxyURL(n.Id)
  609. }
  610. }
  611. return s.probe(ctx, n, proxyURL)
  612. }
  613. func (s *NodeService) ProbeWithOutbound(ctx context.Context, n *model.Node, outboundTag string) (HeartbeatPatch, error) {
  614. if outboundTag == "" {
  615. return s.Probe(ctx, n)
  616. }
  617. var patch HeartbeatPatch
  618. var err error
  619. s.withOutboundBridge(n.Id, outboundTag, func(proxyURL string) {
  620. if proxyURL == "" {
  621. patch, err = s.Probe(ctx, n)
  622. return
  623. }
  624. patch, err = s.probe(ctx, n, proxyURL)
  625. })
  626. return patch, err
  627. }
  628. // withOutboundBridge stands up a temporary loopback SOCKS5 inbound in the
  629. // running Xray, routes it through outboundTag, and runs fn with the bridge's
  630. // proxy URL before tearing it down. It is used to reach a node through its
  631. // connection outbound before the persistent egress bridge has been injected
  632. // into the config (e.g. while the node is still being added or edited). When
  633. // Xray isn't running or the bridge can't be built, fn runs with an empty
  634. // proxyURL so callers fall back to a direct connection.
  635. func (s *NodeService) withOutboundBridge(nodeID int, outboundTag string, fn func(proxyURL string)) {
  636. proc := XrayProcess()
  637. if proc == nil || !proc.IsRunning() {
  638. fn("")
  639. return
  640. }
  641. apiPort := proc.GetAPIPort()
  642. if apiPort <= 0 {
  643. fn("")
  644. return
  645. }
  646. listener, err := net.Listen("tcp", "127.0.0.1:0")
  647. if err != nil {
  648. fn("")
  649. return
  650. }
  651. port := listener.Addr().(*net.TCPAddr).Port
  652. listener.Close()
  653. tag := fmt.Sprintf("node-test-%d-%d", nodeID, time.Now().UnixNano())
  654. proxyURL := fmt.Sprintf("socks5://127.0.0.1:%d", port)
  655. inboundJSON, err := json.Marshal(xray.InboundConfig{
  656. Listen: json_util.RawMessage(`"127.0.0.1"`),
  657. Port: port,
  658. Protocol: "socks",
  659. Settings: json_util.RawMessage(`{"auth":"noauth","udp":false}`),
  660. Tag: tag,
  661. })
  662. if err != nil {
  663. fn("")
  664. return
  665. }
  666. cfg := proc.GetConfig()
  667. routing := map[string]any{}
  668. if len(cfg.RouterConfig) > 0 {
  669. _ = json.Unmarshal(cfg.RouterConfig, &routing)
  670. }
  671. rules, _ := routing["rules"].([]any)
  672. rule := map[string]any{
  673. "type": "field",
  674. "inboundTag": []any{tag},
  675. }
  676. if routingTagIsBalancer(routing, outboundTag) {
  677. rule["balancerTag"] = outboundTag
  678. } else {
  679. rule["outboundTag"] = outboundTag
  680. }
  681. routing["rules"] = append([]any{rule}, rules...)
  682. routingJSON, err := json.Marshal(routing)
  683. if err != nil {
  684. fn("")
  685. return
  686. }
  687. originalRoutingJSON := cfg.RouterConfig
  688. api := xray.XrayAPI{}
  689. if err := api.Init(apiPort); err != nil {
  690. fn("")
  691. return
  692. }
  693. defer api.Close()
  694. if err := api.AddInbound(inboundJSON); err != nil {
  695. fn("")
  696. return
  697. }
  698. defer func() {
  699. if err := api.DelInbound(tag); err != nil {
  700. logger.Warning("remove temp node bridge inbound failed:", err)
  701. }
  702. }()
  703. if err := api.ApplyRoutingConfig(routingJSON); err != nil {
  704. fn("")
  705. return
  706. }
  707. defer func() {
  708. restore := originalRoutingJSON
  709. if len(restore) == 0 {
  710. restore = []byte("{}")
  711. }
  712. if err := api.ApplyRoutingConfig(restore); err != nil {
  713. logger.Warning("restore routing after node bridge failed:", err)
  714. }
  715. }()
  716. fn(proxyURL)
  717. }
  718. func (s *NodeService) probe(ctx context.Context, n *model.Node, proxyURL string) (HeartbeatPatch, error) {
  719. patch := HeartbeatPatch{LastHeartbeat: time.Now().Unix()}
  720. addr, err := netsafe.NormalizeHost(n.Address)
  721. if err != nil {
  722. patch.LastError = err.Error()
  723. return patch, err
  724. }
  725. scheme := n.Scheme
  726. if scheme != "http" && scheme != "https" {
  727. scheme = "https"
  728. }
  729. if n.Port <= 0 || n.Port > 65535 {
  730. patch.LastError = "node port must be 1-65535"
  731. return patch, errors.New(patch.LastError)
  732. }
  733. probeURL := &url.URL{
  734. Scheme: scheme,
  735. Host: net.JoinHostPort(addr, strconv.Itoa(n.Port)),
  736. Path: normalizeBasePath(n.BasePath) + "panel/api/server/status",
  737. }
  738. req, err := http.NewRequestWithContext(
  739. netsafe.ContextWithAllowPrivate(ctx, n.AllowPrivateAddress),
  740. http.MethodGet, probeURL.String(), nil)
  741. if err != nil {
  742. patch.LastError = err.Error()
  743. return patch, err
  744. }
  745. if n.ApiToken != "" {
  746. req.Header.Set("Authorization", "Bearer "+n.ApiToken)
  747. }
  748. req.Header.Set("Accept", "application/json")
  749. client, err := runtime.HTTPClientForNode(n, proxyURL)
  750. if err != nil {
  751. patch.LastError = err.Error()
  752. return patch, err
  753. }
  754. start := time.Now()
  755. resp, err := client.Do(req)
  756. if err != nil {
  757. patch.LastError = err.Error()
  758. return patch, err
  759. }
  760. defer resp.Body.Close()
  761. patch.LatencyMs = int(time.Since(start) / time.Millisecond)
  762. if resp.StatusCode != http.StatusOK {
  763. patch.LastError = fmt.Sprintf("HTTP %d from remote panel", resp.StatusCode)
  764. return patch, errors.New(patch.LastError)
  765. }
  766. var envelope struct {
  767. Success bool `json:"success"`
  768. Msg string `json:"msg"`
  769. Obj *struct {
  770. CpuPct float64 `json:"cpu"`
  771. Mem struct {
  772. Current uint64 `json:"current"`
  773. Total uint64 `json:"total"`
  774. } `json:"mem"`
  775. Xray struct {
  776. Version string `json:"version"`
  777. State string `json:"state"`
  778. ErrorMsg string `json:"errorMsg"`
  779. } `json:"xray"`
  780. PanelVersion string `json:"panelVersion"`
  781. PanelGuid string `json:"panelGuid"`
  782. Uptime uint64 `json:"uptime"`
  783. NetIO struct {
  784. Up uint64 `json:"up"`
  785. Down uint64 `json:"down"`
  786. } `json:"netIO"`
  787. } `json:"obj"`
  788. }
  789. if err := json.NewDecoder(resp.Body).Decode(&envelope); err != nil {
  790. patch.LastError = "decode response: " + err.Error()
  791. return patch, err
  792. }
  793. if !envelope.Success || envelope.Obj == nil {
  794. patch.LastError = "remote returned success=false: " + envelope.Msg
  795. return patch, errors.New(patch.LastError)
  796. }
  797. o := envelope.Obj
  798. patch.CpuPct = o.CpuPct
  799. if o.Mem.Total > 0 {
  800. patch.MemPct = float64(o.Mem.Current) * 100.0 / float64(o.Mem.Total)
  801. }
  802. patch.XrayVersion = o.Xray.Version
  803. patch.XrayState = o.Xray.State
  804. patch.XrayError = o.Xray.ErrorMsg
  805. patch.PanelVersion = o.PanelVersion
  806. patch.Guid = o.PanelGuid
  807. patch.UptimeSecs = o.Uptime
  808. patch.NetUp = o.NetIO.Up
  809. patch.NetDown = o.NetIO.Down
  810. return patch, nil
  811. }
  812. type ProbeResultUI struct {
  813. Status string `json:"status" example:"online"`
  814. LatencyMs int `json:"latencyMs" example:"42"`
  815. XrayVersion string `json:"xrayVersion" example:"25.10.31"`
  816. PanelVersion string `json:"panelVersion" example:"v3.x.x"`
  817. CpuPct float64 `json:"cpuPct" example:"12.5"`
  818. MemPct float64 `json:"memPct" example:"45.2"`
  819. UptimeSecs uint64 `json:"uptimeSecs" example:"86400"`
  820. Error string `json:"error"`
  821. // XrayState/XrayError are populated on successful probes even when the node's
  822. // Xray core is not healthy. The UI uses them for a distinct "panel ok, xray failed" indicator.
  823. XrayState string `json:"xrayState"`
  824. XrayError string `json:"xrayError"`
  825. }
  826. func (p HeartbeatPatch) ToUI(ok bool) ProbeResultUI {
  827. r := ProbeResultUI{
  828. LatencyMs: p.LatencyMs,
  829. XrayVersion: p.XrayVersion,
  830. PanelVersion: p.PanelVersion,
  831. CpuPct: p.CpuPct,
  832. MemPct: p.MemPct,
  833. UptimeSecs: p.UptimeSecs,
  834. Error: FriendlyProbeError(p.LastError),
  835. XrayState: p.XrayState,
  836. XrayError: p.XrayError,
  837. }
  838. if ok {
  839. r.Status = "online"
  840. } else {
  841. r.Status = "offline"
  842. }
  843. return r
  844. }
  845. func FriendlyProbeError(msg string) string {
  846. if strings.Contains(msg, "server gave HTTP response to HTTPS client") {
  847. return "the server speaks HTTP, not HTTPS; set the node scheme to http"
  848. }
  849. return msg
  850. }