1
0

node.go 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078
  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. "sync"
  17. "time"
  18. "github.com/mhsanaei/3x-ui/v3/internal/database"
  19. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  20. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  21. "github.com/mhsanaei/3x-ui/v3/internal/util/common"
  22. "github.com/mhsanaei/3x-ui/v3/internal/util/json_util"
  23. "github.com/mhsanaei/3x-ui/v3/internal/util/netsafe"
  24. "github.com/mhsanaei/3x-ui/v3/internal/web/runtime"
  25. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  26. "gorm.io/gorm"
  27. )
  28. type HeartbeatPatch struct {
  29. Status string
  30. LastHeartbeat int64
  31. LatencyMs int
  32. XrayVersion string
  33. PanelVersion string
  34. Guid string
  35. CpuPct float64
  36. MemPct float64
  37. UptimeSecs uint64
  38. // NetUp/NetDown are the node's current interface throughput (bytes/sec),
  39. // summed over non-virtual interfaces, read from its status response.
  40. NetUp uint64
  41. NetDown uint64
  42. LastError string
  43. // XrayState and XrayError come from the remote /panel/api/server/status when the
  44. // panel API is reachable. They allow distinguishing panel connectivity from
  45. // Xray core health on the node.
  46. XrayState string
  47. XrayError string
  48. }
  49. type NodeService struct{}
  50. // FetchCertFingerprint connects to the node over HTTPS without verifying the
  51. // certificate and returns the leaf certificate's SHA-256 as base64, so the UI
  52. // can offer a "fetch and pin current certificate" action.
  53. func (s *NodeService) FetchCertFingerprint(ctx context.Context, n *model.Node) (string, error) {
  54. addr, err := netsafe.NormalizeHost(n.Address)
  55. if err != nil {
  56. return "", err
  57. }
  58. scheme := n.Scheme
  59. if scheme != "http" && scheme != "https" {
  60. scheme = "https"
  61. }
  62. if scheme != "https" {
  63. return "", common.NewError("certificate pinning is only available for https nodes")
  64. }
  65. if n.Port <= 0 || n.Port > 65535 {
  66. return "", common.NewError("node port must be 1-65535")
  67. }
  68. probeURL := &url.URL{
  69. Scheme: scheme,
  70. Host: net.JoinHostPort(addr, strconv.Itoa(n.Port)),
  71. Path: normalizeBasePath(n.BasePath) + "panel/api/server/status",
  72. }
  73. req, err := http.NewRequestWithContext(
  74. netsafe.ContextWithAllowPrivate(ctx, n.AllowPrivateAddress),
  75. http.MethodGet, probeURL.String(), nil)
  76. if err != nil {
  77. return "", err
  78. }
  79. client := &http.Client{
  80. Transport: &http.Transport{
  81. DialContext: netsafe.SSRFGuardedDialContext,
  82. TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // lgtm[go/disabled-certificate-check]
  83. },
  84. }
  85. resp, err := client.Do(req)
  86. if err != nil {
  87. return "", err
  88. }
  89. defer resp.Body.Close()
  90. if resp.TLS == nil || len(resp.TLS.PeerCertificates) == 0 {
  91. return "", common.NewError("node did not present a TLS certificate")
  92. }
  93. sum := sha256.Sum256(resp.TLS.PeerCertificates[0].Raw)
  94. return base64.StdEncoding.EncodeToString(sum[:]), nil
  95. }
  96. func (s *NodeService) GetAll() ([]*model.Node, error) {
  97. db := database.GetDB()
  98. var nodes []*model.Node
  99. err := db.Model(model.Node{}).Order("id asc").Find(&nodes).Error
  100. if err != nil || len(nodes) == 0 {
  101. return nodes, err
  102. }
  103. type inboundRow struct {
  104. Id int
  105. NodeID int `gorm:"column:node_id"`
  106. }
  107. var inboundRows []inboundRow
  108. if err := db.Table("inbounds").
  109. Select("id, node_id").
  110. Where("node_id IS NOT NULL").
  111. Scan(&inboundRows).Error; err != nil {
  112. return nodes, nil
  113. }
  114. if len(inboundRows) == 0 {
  115. return nodes, nil
  116. }
  117. inboundsByNode := make(map[int][]int, len(nodes))
  118. for _, row := range inboundRows {
  119. inboundsByNode[row.NodeID] = append(inboundsByNode[row.NodeID], row.Id)
  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. depletedByNode := make(map[int]int)
  143. disabledByNode := make(map[int]int)
  144. activeByNode := make(map[int]int)
  145. statuses, _ := s.nodeClientStatuses()
  146. seen := make(map[int]map[int]struct{}, len(nodes))
  147. for _, st := range statuses {
  148. clientsSeen := seen[st.NodeID]
  149. if clientsSeen == nil {
  150. clientsSeen = make(map[int]struct{})
  151. seen[st.NodeID] = clientsSeen
  152. }
  153. if _, dup := clientsSeen[st.ClientID]; dup {
  154. // A client attached to several inbounds of one node counts once,
  155. // matching the distinct ClientCount above.
  156. continue
  157. }
  158. clientsSeen[st.ClientID] = struct{}{}
  159. switch {
  160. case st.Depleted:
  161. depletedByNode[st.NodeID]++
  162. case st.Disabled:
  163. disabledByNode[st.NodeID]++
  164. default:
  165. activeByNode[st.NodeID]++
  166. }
  167. }
  168. onlineByGuid := s.onlineEmailsByGuid()
  169. selfGuid, _ := (&SettingService{}).GetPanelGuid()
  170. ambiguous := ambiguousNodeGuids(nodes, selfGuid)
  171. for _, n := range nodes {
  172. n.InboundCount = len(inboundsByNode[n.Id])
  173. n.DepletedCount = depletedByNode[n.Id]
  174. n.DisabledCount = disabledByNode[n.Id]
  175. n.ActiveCount = activeByNode[n.Id]
  176. // Online is attributed to the node that physically hosts the client
  177. // (by GUID): a client on a sub-node counts under the sub-node, not
  178. // the intermediate node it syncs through (#4983).
  179. n.OnlineCount = len(onlineByGuid[effectiveNodeGuid(n, ambiguous)])
  180. }
  181. return nodes, nil
  182. }
  183. // nodeClientStatus is one node-hosted client's classification, carrying enough
  184. // identity for callers to bucket it by node id or by attribution GUID.
  185. type nodeClientStatus struct {
  186. InboundID int
  187. NodeID int
  188. ClientID int
  189. Depleted bool
  190. Disabled bool
  191. }
  192. // nodeClientStatuses classifies every client attached to a node-hosted inbound as
  193. // depleted / disabled / active, matching client_traffics by EMAIL rather than by
  194. // inbound_id. client_traffics.inbound_id goes stale after an inbound is
  195. // delete+recreated, so filtering by it silently drops most rows; the
  196. // client_inbounds -> clients join is the reliable client set and the email join
  197. // pulls each client's live counters. Precedence matches the inbound page:
  198. // depleted (expired/exhausted) wins over disabled.
  199. func (s *NodeService) nodeClientStatuses() ([]nodeClientStatus, error) {
  200. type row struct {
  201. InboundID int `gorm:"column:inbound_id"`
  202. NodeID int `gorm:"column:node_id"`
  203. ClientID int `gorm:"column:client_id"`
  204. Enable bool `gorm:"column:enable"`
  205. Total int64 `gorm:"column:total"`
  206. Up int64 `gorm:"column:up"`
  207. Down int64 `gorm:"column:down"`
  208. ExpiryTime int64 `gorm:"column:expiry_time"`
  209. }
  210. var rows []row
  211. if err := database.GetDB().Table("inbounds").
  212. Select("inbounds.id AS inbound_id, inbounds.node_id AS node_id, clients.id AS client_id, " +
  213. "clients.enable AS enable, ct.total AS total, ct.up AS up, ct.down AS down, ct.expiry_time AS expiry_time").
  214. Joins("JOIN client_inbounds ON client_inbounds.inbound_id = inbounds.id").
  215. Joins("JOIN clients ON clients.id = client_inbounds.client_id").
  216. Joins("LEFT JOIN client_traffics ct ON ct.email = clients.email").
  217. Where("inbounds.node_id IS NOT NULL").
  218. Scan(&rows).Error; err != nil {
  219. return nil, err
  220. }
  221. now := time.Now().UnixMilli()
  222. out := make([]nodeClientStatus, 0, len(rows))
  223. for _, r := range rows {
  224. st := nodeClientStatus{InboundID: r.InboundID, NodeID: r.NodeID, ClientID: r.ClientID}
  225. expired := r.ExpiryTime > 0 && r.ExpiryTime <= now
  226. exhausted := r.Total > 0 && r.Up+r.Down >= r.Total
  227. switch {
  228. case expired || exhausted:
  229. st.Depleted = true
  230. case !r.Enable:
  231. st.Disabled = true
  232. }
  233. out = append(out, st)
  234. }
  235. return out, nil
  236. }
  237. func (s *NodeService) onlineEmailsByGuid() map[string]map[string]struct{} {
  238. svc := InboundService{}
  239. byGuid := svc.GetOnlineClientsByGuid()
  240. out := make(map[string]map[string]struct{}, len(byGuid))
  241. for guid, emails := range byGuid {
  242. set := make(map[string]struct{}, len(emails))
  243. for _, email := range emails {
  244. set[email] = struct{}{}
  245. }
  246. out[guid] = set
  247. }
  248. return out
  249. }
  250. // effectiveNodeGuid is a node's stable online/inbound attribution key: its
  251. // reported panelGuid, or a master-local synthetic node-id fallback when the node
  252. // has no GUID yet (old build) or its GUID is ambiguous. ambiguous comes from
  253. // ambiguousNodeGuids.
  254. func effectiveNodeGuid(n *model.Node, ambiguous map[string]struct{}) string {
  255. if n.Guid == "" {
  256. return synthNodeGuid(n.Id)
  257. }
  258. if n.Id > 0 {
  259. if _, bad := ambiguous[n.Guid]; bad {
  260. return synthNodeGuid(n.Id)
  261. }
  262. }
  263. return n.Guid
  264. }
  265. // ambiguousNodeGuids returns the panelGuids a node must not be attributed under
  266. // directly, because doing so would merge two distinct identities: a GUID
  267. // reported by more than one of this master's direct nodes (cloned node servers
  268. // ship the same panelGuid in their copied settings), or a GUID equal to the
  269. // master's own panelGuid (a node cloned from the master). A node holding such a
  270. // GUID falls back to its node-unique synthNodeGuid. Transitive sub-nodes (Id 0)
  271. // carry distinct descendant GUIDs by construction and are excluded.
  272. func ambiguousNodeGuids(nodes []*model.Node, selfGuid string) map[string]struct{} {
  273. counts := make(map[string]int, len(nodes))
  274. for _, n := range nodes {
  275. if n.Id > 0 && n.Guid != "" {
  276. counts[n.Guid]++
  277. }
  278. }
  279. ambiguous := make(map[string]struct{})
  280. for guid, c := range counts {
  281. if c > 1 {
  282. ambiguous[guid] = struct{}{}
  283. }
  284. }
  285. if selfGuid != "" {
  286. if _, ok := counts[selfGuid]; ok {
  287. ambiguous[selfGuid] = struct{}{}
  288. }
  289. }
  290. return ambiguous
  291. }
  292. // effectiveNodeKey returns one node's attribution key without a preloaded node
  293. // list — its panelGuid when that GUID uniquely identifies it among the master's
  294. // nodes and differs from the master's own, otherwise its node-unique
  295. // synthNodeGuid. Same rule as effectiveNodeGuid + ambiguousNodeGuids, for the
  296. // write paths that handle a single node (online tree, IP attribution).
  297. func effectiveNodeKey(node *model.Node) string {
  298. if node == nil {
  299. return ""
  300. }
  301. if node.Guid == "" {
  302. return synthNodeGuid(node.Id)
  303. }
  304. var sameGuid int64
  305. database.GetDB().Model(&model.Node{}).Where("guid = ?", node.Guid).Count(&sameGuid)
  306. masterGuid, _ := (&SettingService{}).GetPanelGuid()
  307. if sameGuid > 1 || node.Guid == masterGuid {
  308. return synthNodeGuid(node.Id)
  309. }
  310. return node.Guid
  311. }
  312. func (s *NodeService) GetById(id int) (*model.Node, error) {
  313. db := database.GetDB()
  314. n := &model.Node{}
  315. if err := db.Model(model.Node{}).Where("id = ?", id).First(n).Error; err != nil {
  316. return nil, err
  317. }
  318. return n, nil
  319. }
  320. // NodeExists reports whether a node with the given id exists on this panel.
  321. // Used to drop stale, cross-panel node references on inbound import. A Count
  322. // query distinguishes "no such node" (count 0, no error) from a real DB error.
  323. func (s *NodeService) NodeExists(id int) (bool, error) {
  324. if id <= 0 {
  325. return false, nil
  326. }
  327. var count int64
  328. if err := database.GetDB().Model(model.Node{}).Where("id = ?", id).Count(&count).Error; err != nil {
  329. return false, err
  330. }
  331. return count > 0, nil
  332. }
  333. func normalizeBasePath(p string) string {
  334. p = strings.TrimSpace(p)
  335. if p == "" {
  336. return "/"
  337. }
  338. if !strings.HasPrefix(p, "/") {
  339. p = "/" + p
  340. }
  341. if !strings.HasSuffix(p, "/") {
  342. p = p + "/"
  343. }
  344. return p
  345. }
  346. func (s *NodeService) normalize(n *model.Node) error {
  347. n.Name = strings.TrimSpace(n.Name)
  348. n.ApiToken = strings.TrimSpace(n.ApiToken)
  349. if n.Name == "" {
  350. return common.NewError("node name is required")
  351. }
  352. addr, err := netsafe.NormalizeHost(n.Address)
  353. if err != nil {
  354. return common.NewError(err.Error())
  355. }
  356. n.Address = addr
  357. if n.Port <= 0 || n.Port > 65535 {
  358. return common.NewError("node port must be 1-65535")
  359. }
  360. if n.Scheme != "http" && n.Scheme != "https" {
  361. n.Scheme = "https"
  362. }
  363. if n.TlsVerifyMode != "skip" && n.TlsVerifyMode != "pin" && n.TlsVerifyMode != "mtls" {
  364. n.TlsVerifyMode = "verify"
  365. }
  366. if n.TlsVerifyMode == "mtls" && n.Scheme != "https" {
  367. return common.NewError("mtls requires the node scheme to be https")
  368. }
  369. n.PinnedCertSha256 = strings.TrimSpace(n.PinnedCertSha256)
  370. if n.InboundSyncMode != "selected" {
  371. n.InboundSyncMode = "all"
  372. n.InboundTags = nil
  373. } else {
  374. seen := make(map[string]struct{}, len(n.InboundTags))
  375. tags := make([]string, 0, len(n.InboundTags))
  376. for _, tag := range n.InboundTags {
  377. tag = strings.TrimSpace(tag)
  378. if tag == "" {
  379. continue
  380. }
  381. if _, ok := seen[tag]; ok {
  382. continue
  383. }
  384. seen[tag] = struct{}{}
  385. tags = append(tags, tag)
  386. }
  387. n.InboundTags = tags
  388. }
  389. if n.TlsVerifyMode == "pin" {
  390. if _, err := runtime.DecodeCertPin(n.PinnedCertSha256); err != nil {
  391. return common.NewError(err.Error())
  392. }
  393. }
  394. n.BasePath = normalizeBasePath(n.BasePath)
  395. return nil
  396. }
  397. func (s *NodeService) Create(n *model.Node) error {
  398. if err := s.normalize(n); err != nil {
  399. return err
  400. }
  401. db := database.GetDB()
  402. return db.Create(n).Error
  403. }
  404. func (s *NodeService) Update(id int, in *model.Node) error {
  405. if err := s.normalize(in); err != nil {
  406. return err
  407. }
  408. inboundTagsJSON, err := json.Marshal(in.InboundTags)
  409. if err != nil {
  410. return err
  411. }
  412. db := database.GetDB()
  413. existing := &model.Node{}
  414. if err := db.Where("id = ?", id).First(existing).Error; err != nil {
  415. return err
  416. }
  417. updates := map[string]any{
  418. "name": in.Name,
  419. "remark": in.Remark,
  420. "scheme": in.Scheme,
  421. "address": in.Address,
  422. "port": in.Port,
  423. "base_path": in.BasePath,
  424. "api_token": in.ApiToken,
  425. "enable": in.Enable,
  426. "allow_private_address": in.AllowPrivateAddress,
  427. "tls_verify_mode": in.TlsVerifyMode,
  428. "pinned_cert_sha256": in.PinnedCertSha256,
  429. "inbound_sync_mode": in.InboundSyncMode,
  430. "inbound_tags": string(inboundTagsJSON),
  431. "outbound_tag": in.OutboundTag,
  432. }
  433. if err := db.Transaction(func(tx *gorm.DB) error {
  434. if err := tx.Model(model.Node{}).Where("id = ?", id).Updates(updates).Error; err != nil {
  435. return err
  436. }
  437. return s.MarkNodeDirtyTx(tx, id)
  438. }); err != nil {
  439. return err
  440. }
  441. if mgr := runtime.GetManager(); mgr != nil {
  442. mgr.InvalidateNode(id)
  443. }
  444. return nil
  445. }
  446. func (s *NodeService) GetRemoteInboundOptions(ctx context.Context, n *model.Node) ([]runtime.RemoteInboundOption, error) {
  447. if err := s.normalize(n); err != nil {
  448. return nil, err
  449. }
  450. if n.OutboundTag == "" {
  451. return runtime.NewRemote(n, nil).ListInboundOptions(ctx)
  452. }
  453. // Mirror ProbeWithOutbound: a node being added/edited has no persistent
  454. // egress bridge yet, so route the list call through a temporary one or the
  455. // remote panel stays unreachable and the request times out.
  456. var options []runtime.RemoteInboundOption
  457. var err error
  458. s.withOutboundBridge(n.Id, n.OutboundTag, func(proxyURL string) {
  459. options, err = runtime.NewRemote(n, staticEgressResolver(proxyURL)).ListInboundOptions(ctx)
  460. })
  461. return options, err
  462. }
  463. // staticEgressResolver hands a fixed proxy URL to runtime.NewRemote. An empty
  464. // string yields a direct connection, so it doubles as the graceful fallback
  465. // when a temporary bridge can't be built.
  466. type staticEgressResolver string
  467. func (r staticEgressResolver) NodeEgressProxyURL(int) string { return string(r) }
  468. // EnsureInboundTagAllowed adds a panel-managed inbound's tag to the node's
  469. // selection when the node syncs in "selected" mode. Without it, the next
  470. // traffic sync would filter the tag out of the snapshot and the orphan sweep
  471. // would silently delete the central row the panel just created or renamed.
  472. // Tags are only ever added (never removed): on a rename the node may keep
  473. // reporting the old tag until the remote update lands, and a leftover entry
  474. // that matches nothing is harmless.
  475. func (s *NodeService) EnsureInboundTagAllowed(nodeID int, tag string) error {
  476. return s.EnsureInboundTagAllowedTx(database.GetDB(), nodeID, tag)
  477. }
  478. func (s *NodeService) EnsureInboundTagAllowedTx(tx *gorm.DB, nodeID int, tag string) error {
  479. tag = strings.TrimSpace(tag)
  480. if nodeID <= 0 || tag == "" {
  481. return nil
  482. }
  483. if tx == nil {
  484. tx = database.GetDB()
  485. }
  486. node := &model.Node{}
  487. if err := tx.Where("id = ?", nodeID).First(node).Error; err != nil {
  488. return err
  489. }
  490. if node.InboundSyncMode != "selected" {
  491. return nil
  492. }
  493. if slices.Contains(node.InboundTags, tag) {
  494. return nil
  495. }
  496. buf, err := json.Marshal(append(node.InboundTags, tag))
  497. if err != nil {
  498. return err
  499. }
  500. return tx.Model(model.Node{}).Where("id = ?", nodeID).
  501. Updates(map[string]any{"inbound_tags": string(buf)}).Error
  502. }
  503. func FilterNodeSnapshot(n *model.Node, snap *runtime.TrafficSnapshot) {
  504. if n == nil || snap == nil || n.InboundSyncMode != "selected" {
  505. return
  506. }
  507. allowed := make(map[string]struct{}, len(n.InboundTags))
  508. for _, tag := range n.InboundTags {
  509. allowed[tag] = struct{}{}
  510. }
  511. filtered := make([]*model.Inbound, 0, len(snap.Inbounds))
  512. for _, inbound := range snap.Inbounds {
  513. if inbound == nil {
  514. continue
  515. }
  516. if _, ok := allowed[inbound.Tag]; ok {
  517. filtered = append(filtered, inbound)
  518. }
  519. }
  520. snap.Inbounds = filtered
  521. }
  522. func (s *NodeService) Delete(id int) error {
  523. db := database.GetDB()
  524. // Refuse to delete a node that still owns inbounds: dropping the node row
  525. // while inbounds keep its node_id leaves orphaned, dangling references that
  526. // confuse node sync, subscriptions and cleanup. The operator must detach or
  527. // remove those inbounds first. (DB-002)
  528. var attached int64
  529. if err := db.Model(&model.Inbound{}).Where("node_id = ?", id).Count(&attached).Error; err != nil {
  530. return err
  531. }
  532. if attached > 0 {
  533. return common.NewError(fmt.Sprintf("cannot delete node: %d inbound(s) still attached to it; detach or delete them first", attached))
  534. }
  535. // Capture the node's guid before deleting the row so we can drop its per-node
  536. // IP attribution. NodeClientIp is keyed by the node's attribution key, which
  537. // is its guid normally but its node-unique key for a cloned/ambiguous-guid
  538. // node (see effectiveNodeKey) — so we purge both below.
  539. var guid string
  540. var n model.Node
  541. if err := db.Select("guid").Where("id = ?", id).First(&n).Error; err == nil {
  542. guid = n.Guid
  543. }
  544. // Delete the node row and its per-node child rows atomically. Remove the
  545. // children (traffic baselines, IP attribution) before the parent node row so
  546. // the ordering already matches a future ON DELETE constraint. Delete stays
  547. // tolerant of a missing node row so it can still clean up orphaned baselines.
  548. if err := db.Transaction(func(tx *gorm.DB) error {
  549. if err := tx.Where("node_id = ?", id).Delete(&model.NodeClientTraffic{}).Error; err != nil {
  550. return err
  551. }
  552. guids := []string{synthNodeGuid(id)}
  553. if guid != "" {
  554. guids = append(guids, guid)
  555. }
  556. if err := tx.Where("node_guid IN ?", guids).Delete(&model.NodeClientIp{}).Error; err != nil {
  557. return err
  558. }
  559. return tx.Where("id = ?", id).Delete(&model.Node{}).Error
  560. }); err != nil {
  561. return err
  562. }
  563. if mgr := runtime.GetManager(); mgr != nil {
  564. mgr.InvalidateNode(id)
  565. }
  566. nodeMetrics.drop(nodeMetricKey(id, "cpu"))
  567. nodeMetrics.drop(nodeMetricKey(id, "mem"))
  568. return nil
  569. }
  570. func (s *NodeService) SetEnable(id int, enable bool) error {
  571. db := database.GetDB()
  572. if err := db.Model(model.Node{}).Where("id = ?", id).Update("enable", enable).Error; err != nil {
  573. return err
  574. }
  575. if mgr := runtime.GetManager(); mgr != nil {
  576. mgr.InvalidateNode(id)
  577. }
  578. return nil
  579. }
  580. // GetWebCertFiles asks a node for its own web TLS certificate/key file paths,
  581. // used by "Set Cert from Panel" so a node-assigned inbound gets paths that
  582. // exist on the node rather than the central panel. See issue #4854.
  583. func (s *NodeService) GetWebCertFiles(id int) (*runtime.WebCertFiles, error) {
  584. n, err := s.GetById(id)
  585. if err != nil || n == nil {
  586. return nil, fmt.Errorf("node not found")
  587. }
  588. if !n.Enable {
  589. return nil, fmt.Errorf("node is disabled")
  590. }
  591. mgr := runtime.GetManager()
  592. if mgr == nil {
  593. return nil, fmt.Errorf("runtime manager unavailable")
  594. }
  595. remote, err := mgr.RemoteFor(n)
  596. if err != nil {
  597. return nil, err
  598. }
  599. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  600. defer cancel()
  601. return remote.GetWebCertFiles(ctx)
  602. }
  603. // NodeUpdateResult reports the outcome of triggering a panel self-update on one
  604. // node so the UI can show per-node success/failure for a bulk request.
  605. type NodeUpdateResult struct {
  606. Id int `json:"id"`
  607. Name string `json:"name"`
  608. OK bool `json:"ok"`
  609. Error string `json:"error,omitempty"`
  610. }
  611. // UpdatePanels triggers the official self-updater on each given node. Only
  612. // enabled, online nodes are eligible — an offline node can't be reached, so it
  613. // is reported as skipped rather than silently dropped.
  614. func (s *NodeService) UpdatePanels(ids []int, dev bool) ([]NodeUpdateResult, error) {
  615. mgr := runtime.GetManager()
  616. if mgr == nil {
  617. return nil, fmt.Errorf("runtime manager unavailable")
  618. }
  619. results := make([]NodeUpdateResult, 0, len(ids))
  620. for _, id := range ids {
  621. n, err := s.GetById(id)
  622. if err != nil || n == nil {
  623. results = append(results, NodeUpdateResult{Id: id, OK: false, Error: "node not found"})
  624. continue
  625. }
  626. res := NodeUpdateResult{Id: id, Name: n.Name}
  627. switch {
  628. case !n.Enable:
  629. res.Error = "node is disabled"
  630. case n.Status != "online":
  631. res.Error = "node is offline"
  632. default:
  633. remote, remoteErr := mgr.RemoteFor(n)
  634. if remoteErr != nil {
  635. res.Error = remoteErr.Error()
  636. break
  637. }
  638. ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
  639. updErr := remote.UpdatePanel(ctx, dev)
  640. cancel()
  641. if updErr != nil {
  642. res.Error = updErr.Error()
  643. } else {
  644. res.OK = true
  645. }
  646. }
  647. results = append(results, res)
  648. }
  649. return results, nil
  650. }
  651. func (s *NodeService) UpdateHeartbeat(id int, p HeartbeatPatch) error {
  652. db := database.GetDB()
  653. updates := map[string]any{
  654. "status": p.Status,
  655. "last_heartbeat": p.LastHeartbeat,
  656. "latency_ms": p.LatencyMs,
  657. "xray_version": p.XrayVersion,
  658. "panel_version": p.PanelVersion,
  659. "cpu_pct": p.CpuPct,
  660. "mem_pct": p.MemPct,
  661. "uptime_secs": p.UptimeSecs,
  662. "net_up": p.NetUp,
  663. "net_down": p.NetDown,
  664. "last_error": p.LastError,
  665. "xray_state": p.XrayState,
  666. "xray_error": p.XrayError,
  667. }
  668. // Only learn the GUID; never clear a known one if an old-build node (or a
  669. // failed probe) reports none, so the stable identity survives blips.
  670. if p.Guid != "" {
  671. updates["guid"] = p.Guid
  672. s.warnOnDuplicateGuid(id, p.Guid)
  673. }
  674. if err := db.Model(model.Node{}).Where("id = ?", id).Updates(updates).Error; err != nil {
  675. return err
  676. }
  677. if p.Status == "online" {
  678. now := time.Unix(p.LastHeartbeat, 0)
  679. nodeMetrics.append(nodeMetricKey(id, "cpu"), now, p.CpuPct)
  680. nodeMetrics.append(nodeMetricKey(id, "mem"), now, p.MemPct)
  681. nodeMetrics.append(nodeMetricKey(id, "netUp"), now, float64(p.NetUp))
  682. nodeMetrics.append(nodeMetricKey(id, "netDown"), now, float64(p.NetDown))
  683. }
  684. return nil
  685. }
  686. // warnedDupGuid remembers the (nodeID -> guid) pairs already warned about so a
  687. // cloned-server collision is logged once, not every heartbeat.
  688. var warnedDupGuid sync.Map
  689. // warnOnDuplicateGuid logs once when a node reports a panelGuid already held by
  690. // another node or by the master itself (the cloned-server footgun). Attribution
  691. // still works — it falls back to node-unique keys — but the operator should
  692. // regenerate the duplicate panelGuid to restore real identity and per-node IP
  693. // attribution. Re-arms if the collision later clears.
  694. func (s *NodeService) warnOnDuplicateGuid(id int, guid string) {
  695. var clash int64
  696. database.GetDB().Model(&model.Node{}).Where("guid = ? AND id <> ?", guid, id).Count(&clash)
  697. masterGuid, _ := (&SettingService{}).GetPanelGuid()
  698. if clash == 0 && guid != masterGuid {
  699. warnedDupGuid.Delete(id)
  700. return
  701. }
  702. if prev, ok := warnedDupGuid.Load(id); ok && prev == guid {
  703. return
  704. }
  705. warnedDupGuid.Store(id, guid)
  706. logger.Warningf("node %d reports panelGuid %s already used by another node or the master (cloned server?) — regenerate it on that node so online and IP attribution stay per-node", id, guid)
  707. }
  708. func (s *NodeService) MarkNodeDirty(id int) error {
  709. return s.MarkNodeDirtyTx(database.GetDB(), id)
  710. }
  711. func (s *NodeService) MarkNodeDirtyTx(tx *gorm.DB, id int) error {
  712. if id <= 0 {
  713. return nil
  714. }
  715. if tx == nil {
  716. return errors.New("nil db transaction")
  717. }
  718. return tx.Model(model.Node{}).
  719. Where("id = ?", id).
  720. Updates(map[string]any{
  721. "config_dirty": true,
  722. "config_dirty_at": time.Now().UnixMilli(),
  723. }).Error
  724. }
  725. func (s *NodeService) ClearNodeDirty(id int, dirtyAt int64) error {
  726. if id <= 0 {
  727. return nil
  728. }
  729. return database.GetDB().Model(model.Node{}).
  730. Where("id = ? AND config_dirty_at = ?", id, dirtyAt).
  731. Update("config_dirty", false).Error
  732. }
  733. func (s *NodeService) NodeSyncState(id int) (enabled bool, status string, dirty bool, dirtyAt int64, err error) {
  734. if id <= 0 {
  735. return false, "", false, 0, errors.New("invalid node id")
  736. }
  737. var row model.Node
  738. err = database.GetDB().Model(model.Node{}).
  739. Select("enable", "status", "config_dirty", "config_dirty_at").
  740. Where("id = ?", id).
  741. First(&row).Error
  742. if err != nil {
  743. return false, "", false, 0, err
  744. }
  745. return row.Enable, row.Status, row.ConfigDirty, row.ConfigDirtyAt, nil
  746. }
  747. // IsNodePending reports whether a save targeting this node was deferred because
  748. // the node is unreachable right now — offline or disabled — so the edit only
  749. // reaches it on the next reconcile. It deliberately ignores config_dirty: that
  750. // flag is set on EVERY node-backed edit as the reconcile self-heal marker,
  751. // including edits pushed live to an online node, so keying the user-facing
  752. // "saved, node offline, will sync" toast off it fired the warning on every save
  753. // to a perfectly healthy online node.
  754. func (s *NodeService) IsNodePending(id int) bool {
  755. enabled, status, _, _, err := s.NodeSyncState(id)
  756. if err != nil {
  757. return false
  758. }
  759. return !enabled || status != "online"
  760. }
  761. func nodeMetricKey(id int, metric string) string {
  762. return "node:" + strconv.Itoa(id) + ":" + metric
  763. }
  764. func (s *NodeService) AggregateNodeMetric(id int, metric string, bucketSeconds int, maxPoints int) []map[string]any {
  765. return nodeMetrics.aggregate(nodeMetricKey(id, metric), bucketSeconds, maxPoints)
  766. }
  767. func (s *NodeService) Probe(ctx context.Context, n *model.Node) (HeartbeatPatch, error) {
  768. proxyURL := ""
  769. if n.OutboundTag != "" {
  770. if mgr := runtime.GetManager(); mgr != nil {
  771. proxyURL = mgr.NodeEgressProxyURL(n.Id)
  772. }
  773. }
  774. return s.probe(ctx, n, proxyURL)
  775. }
  776. func (s *NodeService) ProbeWithOutbound(ctx context.Context, n *model.Node, outboundTag string) (HeartbeatPatch, error) {
  777. if outboundTag == "" {
  778. return s.Probe(ctx, n)
  779. }
  780. var patch HeartbeatPatch
  781. var err error
  782. s.withOutboundBridge(n.Id, outboundTag, func(proxyURL string) {
  783. if proxyURL == "" {
  784. patch, err = s.Probe(ctx, n)
  785. return
  786. }
  787. patch, err = s.probe(ctx, n, proxyURL)
  788. })
  789. return patch, err
  790. }
  791. // withOutboundBridge stands up a temporary loopback SOCKS5 inbound in the
  792. // running Xray, routes it through outboundTag, and runs fn with the bridge's
  793. // proxy URL before tearing it down. It is used to reach a node through its
  794. // connection outbound before the persistent egress bridge has been injected
  795. // into the config (e.g. while the node is still being added or edited). When
  796. // Xray isn't running or the bridge can't be built, fn runs with an empty
  797. // proxyURL so callers fall back to a direct connection.
  798. func (s *NodeService) withOutboundBridge(nodeID int, outboundTag string, fn func(proxyURL string)) {
  799. proc := XrayProcess()
  800. if proc == nil || !proc.IsRunning() {
  801. fn("")
  802. return
  803. }
  804. apiPort := proc.GetAPIPort()
  805. if apiPort <= 0 {
  806. fn("")
  807. return
  808. }
  809. listener, err := (&net.ListenConfig{}).Listen(context.Background(), "tcp", "127.0.0.1:0")
  810. if err != nil {
  811. fn("")
  812. return
  813. }
  814. port := listener.Addr().(*net.TCPAddr).Port
  815. listener.Close()
  816. tag := fmt.Sprintf("node-test-%d-%d", nodeID, time.Now().UnixNano())
  817. proxyURL := fmt.Sprintf("socks5://127.0.0.1:%d", port)
  818. inboundJSON, err := json.Marshal(xray.InboundConfig{
  819. Listen: json_util.RawMessage(`"127.0.0.1"`),
  820. Port: port,
  821. Protocol: "socks",
  822. Settings: json_util.RawMessage(`{"auth":"noauth","udp":false}`),
  823. Tag: tag,
  824. })
  825. if err != nil {
  826. fn("")
  827. return
  828. }
  829. cfg := proc.GetConfig()
  830. routing := map[string]any{}
  831. if len(cfg.RouterConfig) > 0 {
  832. _ = json.Unmarshal(cfg.RouterConfig, &routing)
  833. }
  834. rules, _ := routing["rules"].([]any)
  835. rule := map[string]any{
  836. "type": "field",
  837. "inboundTag": []any{tag},
  838. }
  839. if routingTagIsBalancer(routing, outboundTag) {
  840. rule["balancerTag"] = outboundTag
  841. } else {
  842. rule["outboundTag"] = outboundTag
  843. }
  844. routing["rules"] = append([]any{rule}, rules...)
  845. routingJSON, err := json.Marshal(routing)
  846. if err != nil {
  847. fn("")
  848. return
  849. }
  850. originalRoutingJSON := cfg.RouterConfig
  851. api := xray.XrayAPI{}
  852. if err := api.Init(apiPort); err != nil {
  853. fn("")
  854. return
  855. }
  856. defer api.Close()
  857. if err := api.AddInbound(inboundJSON); err != nil {
  858. fn("")
  859. return
  860. }
  861. defer func() {
  862. if err := api.DelInbound(tag); err != nil {
  863. logger.Warning("remove temp node bridge inbound failed:", err)
  864. }
  865. }()
  866. if err := api.ApplyRoutingConfig(routingJSON); err != nil {
  867. fn("")
  868. return
  869. }
  870. defer func() {
  871. restore := originalRoutingJSON
  872. if len(restore) == 0 {
  873. restore = []byte("{}")
  874. }
  875. if err := api.ApplyRoutingConfig(restore); err != nil {
  876. logger.Warning("restore routing after node bridge failed:", err)
  877. }
  878. }()
  879. fn(proxyURL)
  880. }
  881. func (s *NodeService) probe(ctx context.Context, n *model.Node, proxyURL string) (HeartbeatPatch, error) {
  882. patch := HeartbeatPatch{LastHeartbeat: time.Now().Unix()}
  883. addr, err := netsafe.NormalizeHost(n.Address)
  884. if err != nil {
  885. patch.LastError = err.Error()
  886. return patch, err
  887. }
  888. scheme := n.Scheme
  889. if scheme != "http" && scheme != "https" {
  890. scheme = "https"
  891. }
  892. if n.Port <= 0 || n.Port > 65535 {
  893. patch.LastError = "node port must be 1-65535"
  894. return patch, errors.New(patch.LastError)
  895. }
  896. probeURL := &url.URL{
  897. Scheme: scheme,
  898. Host: net.JoinHostPort(addr, strconv.Itoa(n.Port)),
  899. Path: normalizeBasePath(n.BasePath) + "panel/api/server/status",
  900. }
  901. req, err := http.NewRequestWithContext(
  902. netsafe.ContextWithAllowPrivate(ctx, n.AllowPrivateAddress),
  903. http.MethodGet, probeURL.String(), nil)
  904. if err != nil {
  905. patch.LastError = err.Error()
  906. return patch, err
  907. }
  908. if n.ApiToken != "" {
  909. req.Header.Set("Authorization", "Bearer "+n.ApiToken)
  910. }
  911. req.Header.Set("Accept", "application/json")
  912. client, err := runtime.HTTPClientForNode(n, proxyURL)
  913. if err != nil {
  914. patch.LastError = err.Error()
  915. return patch, err
  916. }
  917. start := time.Now()
  918. resp, err := client.Do(req)
  919. if err != nil {
  920. patch.LastError = err.Error()
  921. return patch, err
  922. }
  923. defer resp.Body.Close()
  924. patch.LatencyMs = int(time.Since(start) / time.Millisecond)
  925. if resp.StatusCode != http.StatusOK {
  926. patch.LastError = fmt.Sprintf("HTTP %d from remote panel", resp.StatusCode)
  927. return patch, errors.New(patch.LastError)
  928. }
  929. var envelope struct {
  930. Success bool `json:"success"`
  931. Msg string `json:"msg"`
  932. Obj *struct {
  933. CpuPct float64 `json:"cpu"`
  934. Mem struct {
  935. Current uint64 `json:"current"`
  936. Total uint64 `json:"total"`
  937. } `json:"mem"`
  938. Xray struct {
  939. Version string `json:"version"`
  940. State string `json:"state"`
  941. ErrorMsg string `json:"errorMsg"`
  942. } `json:"xray"`
  943. PanelVersion string `json:"panelVersion"`
  944. PanelGuid string `json:"panelGuid"`
  945. Uptime uint64 `json:"uptime"`
  946. NetIO struct {
  947. Up uint64 `json:"up"`
  948. Down uint64 `json:"down"`
  949. } `json:"netIO"`
  950. } `json:"obj"`
  951. }
  952. if err := json.NewDecoder(resp.Body).Decode(&envelope); err != nil {
  953. patch.LastError = "decode response: " + err.Error()
  954. return patch, err
  955. }
  956. if !envelope.Success || envelope.Obj == nil {
  957. patch.LastError = "remote returned success=false: " + envelope.Msg
  958. return patch, errors.New(patch.LastError)
  959. }
  960. o := envelope.Obj
  961. patch.CpuPct = o.CpuPct
  962. if o.Mem.Total > 0 {
  963. patch.MemPct = float64(o.Mem.Current) * 100.0 / float64(o.Mem.Total)
  964. }
  965. patch.XrayVersion = o.Xray.Version
  966. patch.XrayState = o.Xray.State
  967. patch.XrayError = o.Xray.ErrorMsg
  968. patch.PanelVersion = o.PanelVersion
  969. patch.Guid = o.PanelGuid
  970. patch.UptimeSecs = o.Uptime
  971. patch.NetUp = o.NetIO.Up
  972. patch.NetDown = o.NetIO.Down
  973. return patch, nil
  974. }
  975. type ProbeResultUI struct {
  976. Status string `json:"status" example:"online"`
  977. LatencyMs int `json:"latencyMs" example:"42"`
  978. XrayVersion string `json:"xrayVersion" example:"25.10.31"`
  979. PanelVersion string `json:"panelVersion" example:"v3.x.x"`
  980. CpuPct float64 `json:"cpuPct" example:"12.5"`
  981. MemPct float64 `json:"memPct" example:"45.2"`
  982. UptimeSecs uint64 `json:"uptimeSecs" example:"86400"`
  983. Error string `json:"error"`
  984. // XrayState/XrayError are populated on successful probes even when the node's
  985. // Xray core is not healthy. The UI uses them for a distinct "panel ok, xray failed" indicator.
  986. XrayState string `json:"xrayState"`
  987. XrayError string `json:"xrayError"`
  988. }
  989. func (p HeartbeatPatch) ToUI(ok bool) ProbeResultUI {
  990. r := ProbeResultUI{
  991. LatencyMs: p.LatencyMs,
  992. XrayVersion: p.XrayVersion,
  993. PanelVersion: p.PanelVersion,
  994. CpuPct: p.CpuPct,
  995. MemPct: p.MemPct,
  996. UptimeSecs: p.UptimeSecs,
  997. Error: FriendlyProbeError(p.LastError),
  998. XrayState: p.XrayState,
  999. XrayError: p.XrayError,
  1000. }
  1001. if ok {
  1002. r.Status = "online"
  1003. } else {
  1004. r.Status = "offline"
  1005. }
  1006. return r
  1007. }
  1008. func FriendlyProbeError(msg string) string {
  1009. if strings.Contains(msg, "server gave HTTP response to HTTPS client") {
  1010. return "the server speaks HTTP, not HTTPS; set the node scheme to http"
  1011. }
  1012. return msg
  1013. }