node.go 25 KB

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