node.go 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095
  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. prefix := nodeTagPrefix(&n.Id)
  508. allowed := make(map[string]struct{}, len(n.InboundTags)*2)
  509. for _, tag := range n.InboundTags {
  510. allowed[tag] = struct{}{}
  511. if prefix != "" {
  512. if stripped, found := strings.CutPrefix(tag, prefix); found {
  513. allowed[stripped] = struct{}{}
  514. } else {
  515. allowed[prefix+tag] = struct{}{}
  516. }
  517. }
  518. }
  519. filtered := make([]*model.Inbound, 0, len(snap.Inbounds))
  520. for _, inbound := range snap.Inbounds {
  521. if inbound == nil {
  522. continue
  523. }
  524. if _, ok := allowed[inbound.Tag]; ok {
  525. filtered = append(filtered, inbound)
  526. }
  527. }
  528. snap.Inbounds = filtered
  529. }
  530. func (s *NodeService) Delete(id int) error {
  531. db := database.GetDB()
  532. // Refuse to delete a node that still owns inbounds: dropping the node row
  533. // while inbounds keep its node_id leaves orphaned, dangling references that
  534. // confuse node sync, subscriptions and cleanup. The operator must detach or
  535. // remove those inbounds first. (DB-002)
  536. var attached int64
  537. if err := db.Model(&model.Inbound{}).Where("node_id = ?", id).Count(&attached).Error; err != nil {
  538. return err
  539. }
  540. if attached > 0 {
  541. return common.NewError(fmt.Sprintf("cannot delete node: %d inbound(s) still attached to it; detach or delete them first", attached))
  542. }
  543. // Capture the node's guid before deleting the row so we can drop its per-node
  544. // IP attribution. NodeClientIp is keyed by the node's attribution key, which
  545. // is its guid normally but its node-unique key for a cloned/ambiguous-guid
  546. // node (see effectiveNodeKey) — so we purge both below.
  547. var guid string
  548. var n model.Node
  549. if err := db.Select("guid").Where("id = ?", id).First(&n).Error; err == nil {
  550. guid = n.Guid
  551. }
  552. // Delete the node row and its per-node child rows atomically. Remove the
  553. // children (traffic baselines, IP attribution) before the parent node row so
  554. // the ordering already matches a future ON DELETE constraint. Delete stays
  555. // tolerant of a missing node row so it can still clean up orphaned baselines.
  556. if err := db.Transaction(func(tx *gorm.DB) error {
  557. if err := tx.Where("node_id = ?", id).Delete(&model.NodeClientTraffic{}).Error; err != nil {
  558. return err
  559. }
  560. guids := []string{synthNodeGuid(id)}
  561. if guid != "" {
  562. guids = append(guids, guid)
  563. }
  564. if err := tx.Where("node_guid IN ?", guids).Delete(&model.NodeClientIp{}).Error; err != nil {
  565. return err
  566. }
  567. return tx.Where("id = ?", id).Delete(&model.Node{}).Error
  568. }); err != nil {
  569. return err
  570. }
  571. if mgr := runtime.GetManager(); mgr != nil {
  572. mgr.InvalidateNode(id)
  573. }
  574. nodeMetrics.drop(nodeMetricKey(id, "cpu"))
  575. nodeMetrics.drop(nodeMetricKey(id, "mem"))
  576. return nil
  577. }
  578. func (s *NodeService) SetEnable(id int, enable bool) error {
  579. db := database.GetDB()
  580. if err := db.Model(model.Node{}).Where("id = ?", id).Update("enable", enable).Error; err != nil {
  581. return err
  582. }
  583. if mgr := runtime.GetManager(); mgr != nil {
  584. mgr.InvalidateNode(id)
  585. }
  586. return nil
  587. }
  588. // GetWebCertFiles asks a node for its own web TLS certificate/key file paths,
  589. // used by "Set Cert from Panel" so a node-assigned inbound gets paths that
  590. // exist on the node rather than the central panel. See issue #4854.
  591. func (s *NodeService) GetWebCertFiles(id int) (*runtime.WebCertFiles, error) {
  592. n, err := s.GetById(id)
  593. if err != nil || n == nil {
  594. return nil, fmt.Errorf("node not found")
  595. }
  596. if !n.Enable {
  597. return nil, fmt.Errorf("node is disabled")
  598. }
  599. mgr := runtime.GetManager()
  600. if mgr == nil {
  601. return nil, fmt.Errorf("runtime manager unavailable")
  602. }
  603. remote, err := mgr.RemoteFor(n)
  604. if err != nil {
  605. return nil, err
  606. }
  607. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  608. defer cancel()
  609. return remote.GetWebCertFiles(ctx)
  610. }
  611. // NodeUpdateResult reports the outcome of triggering a panel self-update on one
  612. // node so the UI can show per-node success/failure for a bulk request.
  613. type NodeUpdateResult struct {
  614. Id int `json:"id"`
  615. Name string `json:"name"`
  616. OK bool `json:"ok"`
  617. Error string `json:"error,omitempty"`
  618. }
  619. // UpdatePanels triggers the official self-updater on each given node. Only
  620. // enabled, online nodes are eligible — an offline node can't be reached, so it
  621. // is reported as skipped rather than silently dropped.
  622. func (s *NodeService) UpdatePanels(ids []int, dev bool) ([]NodeUpdateResult, error) {
  623. mgr := runtime.GetManager()
  624. if mgr == nil {
  625. return nil, fmt.Errorf("runtime manager unavailable")
  626. }
  627. results := make([]NodeUpdateResult, 0, len(ids))
  628. for _, id := range ids {
  629. n, err := s.GetById(id)
  630. if err != nil || n == nil {
  631. results = append(results, NodeUpdateResult{Id: id, OK: false, Error: "node not found"})
  632. continue
  633. }
  634. res := NodeUpdateResult{Id: id, Name: n.Name}
  635. switch {
  636. case !n.Enable:
  637. res.Error = "node is disabled"
  638. case n.Status != "online":
  639. res.Error = "node is offline"
  640. default:
  641. remote, remoteErr := mgr.RemoteFor(n)
  642. if remoteErr != nil {
  643. res.Error = remoteErr.Error()
  644. break
  645. }
  646. ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
  647. updErr := remote.UpdatePanel(ctx, dev)
  648. cancel()
  649. if updErr != nil {
  650. res.Error = updErr.Error()
  651. } else {
  652. res.OK = true
  653. }
  654. }
  655. results = append(results, res)
  656. }
  657. return results, nil
  658. }
  659. func (s *NodeService) UpdateHeartbeat(id int, p HeartbeatPatch) error {
  660. db := database.GetDB()
  661. updates := map[string]any{
  662. "status": p.Status,
  663. "last_heartbeat": p.LastHeartbeat,
  664. "latency_ms": p.LatencyMs,
  665. "xray_version": p.XrayVersion,
  666. "panel_version": p.PanelVersion,
  667. "cpu_pct": p.CpuPct,
  668. "mem_pct": p.MemPct,
  669. "uptime_secs": p.UptimeSecs,
  670. "net_up": p.NetUp,
  671. "net_down": p.NetDown,
  672. "last_error": p.LastError,
  673. "xray_state": p.XrayState,
  674. "xray_error": p.XrayError,
  675. }
  676. // Only learn the GUID; never clear a known one if an old-build node (or a
  677. // failed probe) reports none, so the stable identity survives blips.
  678. if p.Guid != "" {
  679. updates["guid"] = p.Guid
  680. s.warnOnDuplicateGuid(id, p.Guid)
  681. }
  682. if err := db.Model(model.Node{}).Where("id = ?", id).Updates(updates).Error; err != nil {
  683. return err
  684. }
  685. if p.Status == "online" {
  686. now := time.Unix(p.LastHeartbeat, 0)
  687. nodeMetrics.append(nodeMetricKey(id, "cpu"), now, p.CpuPct)
  688. nodeMetrics.append(nodeMetricKey(id, "mem"), now, p.MemPct)
  689. nodeMetrics.append(nodeMetricKey(id, "netUp"), now, float64(p.NetUp))
  690. nodeMetrics.append(nodeMetricKey(id, "netDown"), now, float64(p.NetDown))
  691. }
  692. return nil
  693. }
  694. // warnedDupGuid remembers the (nodeID -> guid) pairs already warned about so a
  695. // cloned-server collision is logged once, not every heartbeat.
  696. var warnedDupGuid sync.Map
  697. // warnOnDuplicateGuid logs once when a node reports a panelGuid already held by
  698. // another node or by the master itself (the cloned-server footgun). Attribution
  699. // still works — it falls back to node-unique keys — but the operator should
  700. // regenerate the duplicate panelGuid to restore real identity and per-node IP
  701. // attribution. Re-arms if the collision later clears.
  702. func (s *NodeService) warnOnDuplicateGuid(id int, guid string) {
  703. var clash int64
  704. database.GetDB().Model(&model.Node{}).Where("guid = ? AND id <> ?", guid, id).Count(&clash)
  705. masterGuid, _ := (&SettingService{}).GetPanelGuid()
  706. if clash == 0 && guid != masterGuid {
  707. warnedDupGuid.Delete(id)
  708. return
  709. }
  710. if prev, ok := warnedDupGuid.Load(id); ok && prev == guid {
  711. return
  712. }
  713. warnedDupGuid.Store(id, guid)
  714. 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)
  715. }
  716. func (s *NodeService) MarkNodeDirty(id int) error {
  717. return s.MarkNodeDirtyTx(database.GetDB(), id)
  718. }
  719. func (s *NodeService) MarkNodeDirtyTx(tx *gorm.DB, id int) error {
  720. if id <= 0 {
  721. return nil
  722. }
  723. if tx == nil {
  724. return errors.New("nil db transaction")
  725. }
  726. return tx.Model(model.Node{}).
  727. Where("id = ?", id).
  728. Updates(map[string]any{
  729. "config_dirty": true,
  730. "config_dirty_at": time.Now().UnixMilli(),
  731. }).Error
  732. }
  733. func (s *NodeService) ClearNodeDirty(id int, dirtyAt int64) error {
  734. if id <= 0 {
  735. return nil
  736. }
  737. return database.GetDB().Model(model.Node{}).
  738. Where("id = ? AND config_dirty_at = ?", id, dirtyAt).
  739. Update("config_dirty", false).Error
  740. }
  741. func (s *NodeService) MarkNodeInboundsAdopted(id int) error {
  742. if id <= 0 {
  743. return nil
  744. }
  745. return database.GetDB().Model(model.Node{}).
  746. Where("id = ? AND inbounds_adopted_at = 0", id).
  747. Update("inbounds_adopted_at", time.Now().Unix()).Error
  748. }
  749. func (s *NodeService) NodeSyncState(id int) (enabled bool, status string, dirty bool, dirtyAt int64, err error) {
  750. if id <= 0 {
  751. return false, "", false, 0, errors.New("invalid node id")
  752. }
  753. var row model.Node
  754. err = database.GetDB().Model(model.Node{}).
  755. Select("enable", "status", "config_dirty", "config_dirty_at").
  756. Where("id = ?", id).
  757. First(&row).Error
  758. if err != nil {
  759. return false, "", false, 0, err
  760. }
  761. return row.Enable, row.Status, row.ConfigDirty, row.ConfigDirtyAt, nil
  762. }
  763. // IsNodePending reports whether a save targeting this node was deferred because
  764. // the node is unreachable right now — offline or disabled — so the edit only
  765. // reaches it on the next reconcile. It deliberately ignores config_dirty: that
  766. // flag is set on EVERY node-backed edit as the reconcile self-heal marker,
  767. // including edits pushed live to an online node, so keying the user-facing
  768. // "saved, node offline, will sync" toast off it fired the warning on every save
  769. // to a perfectly healthy online node.
  770. func (s *NodeService) IsNodePending(id int) bool {
  771. enabled, status, _, _, err := s.NodeSyncState(id)
  772. if err != nil {
  773. return false
  774. }
  775. return !enabled || status != "online"
  776. }
  777. func nodeMetricKey(id int, metric string) string {
  778. return "node:" + strconv.Itoa(id) + ":" + metric
  779. }
  780. func (s *NodeService) AggregateNodeMetric(id int, metric string, bucketSeconds int, maxPoints int) []map[string]any {
  781. return nodeMetrics.aggregate(nodeMetricKey(id, metric), bucketSeconds, maxPoints)
  782. }
  783. func (s *NodeService) Probe(ctx context.Context, n *model.Node) (HeartbeatPatch, error) {
  784. proxyURL := ""
  785. if n.OutboundTag != "" {
  786. if mgr := runtime.GetManager(); mgr != nil {
  787. proxyURL = mgr.NodeEgressProxyURL(n.Id)
  788. }
  789. }
  790. return s.probe(ctx, n, proxyURL)
  791. }
  792. func (s *NodeService) ProbeWithOutbound(ctx context.Context, n *model.Node, outboundTag string) (HeartbeatPatch, error) {
  793. if outboundTag == "" {
  794. return s.Probe(ctx, n)
  795. }
  796. var patch HeartbeatPatch
  797. var err error
  798. s.withOutboundBridge(n.Id, outboundTag, func(proxyURL string) {
  799. if proxyURL == "" {
  800. patch, err = s.Probe(ctx, n)
  801. return
  802. }
  803. patch, err = s.probe(ctx, n, proxyURL)
  804. })
  805. return patch, err
  806. }
  807. // withOutboundBridge stands up a temporary loopback SOCKS5 inbound in the
  808. // running Xray, routes it through outboundTag, and runs fn with the bridge's
  809. // proxy URL before tearing it down. It is used to reach a node through its
  810. // connection outbound before the persistent egress bridge has been injected
  811. // into the config (e.g. while the node is still being added or edited). When
  812. // Xray isn't running or the bridge can't be built, fn runs with an empty
  813. // proxyURL so callers fall back to a direct connection.
  814. func (s *NodeService) withOutboundBridge(nodeID int, outboundTag string, fn func(proxyURL string)) {
  815. proc := XrayProcess()
  816. if proc == nil || !proc.IsRunning() {
  817. fn("")
  818. return
  819. }
  820. apiPort := proc.GetAPIPort()
  821. if apiPort <= 0 {
  822. fn("")
  823. return
  824. }
  825. listener, err := (&net.ListenConfig{}).Listen(context.Background(), "tcp", "127.0.0.1:0")
  826. if err != nil {
  827. fn("")
  828. return
  829. }
  830. port := listener.Addr().(*net.TCPAddr).Port
  831. listener.Close()
  832. tag := fmt.Sprintf("node-test-%d-%d", nodeID, time.Now().UnixNano())
  833. proxyURL := fmt.Sprintf("socks5://127.0.0.1:%d", port)
  834. inboundJSON, err := json.Marshal(xray.InboundConfig{
  835. Listen: json_util.RawMessage(`"127.0.0.1"`),
  836. Port: port,
  837. Protocol: "socks",
  838. Settings: json_util.RawMessage(`{"auth":"noauth","udp":false}`),
  839. Tag: tag,
  840. })
  841. if err != nil {
  842. fn("")
  843. return
  844. }
  845. cfg := proc.GetConfig()
  846. routing := map[string]any{}
  847. if len(cfg.RouterConfig) > 0 {
  848. _ = json.Unmarshal(cfg.RouterConfig, &routing)
  849. }
  850. rules, _ := routing["rules"].([]any)
  851. rule := map[string]any{
  852. "type": "field",
  853. "inboundTag": []any{tag},
  854. }
  855. if routingTagIsBalancer(routing, outboundTag) {
  856. rule["balancerTag"] = outboundTag
  857. } else {
  858. rule["outboundTag"] = outboundTag
  859. }
  860. routing["rules"] = append([]any{rule}, rules...)
  861. routingJSON, err := json.Marshal(routing)
  862. if err != nil {
  863. fn("")
  864. return
  865. }
  866. originalRoutingJSON := cfg.RouterConfig
  867. api := xray.XrayAPI{}
  868. if err := api.Init(apiPort); err != nil {
  869. fn("")
  870. return
  871. }
  872. defer api.Close()
  873. if err := api.AddInbound(inboundJSON); err != nil {
  874. fn("")
  875. return
  876. }
  877. defer func() {
  878. if err := api.DelInbound(tag); err != nil {
  879. logger.Warning("remove temp node bridge inbound failed:", err)
  880. }
  881. }()
  882. if err := api.ApplyRoutingConfig(routingJSON); err != nil {
  883. fn("")
  884. return
  885. }
  886. defer func() {
  887. restore := originalRoutingJSON
  888. if len(restore) == 0 {
  889. restore = []byte("{}")
  890. }
  891. if err := api.ApplyRoutingConfig(restore); err != nil {
  892. logger.Warning("restore routing after node bridge failed:", err)
  893. }
  894. }()
  895. fn(proxyURL)
  896. }
  897. func (s *NodeService) probe(ctx context.Context, n *model.Node, proxyURL string) (HeartbeatPatch, error) {
  898. patch := HeartbeatPatch{LastHeartbeat: time.Now().Unix()}
  899. addr, err := netsafe.NormalizeHost(n.Address)
  900. if err != nil {
  901. patch.LastError = err.Error()
  902. return patch, err
  903. }
  904. scheme := n.Scheme
  905. if scheme != "http" && scheme != "https" {
  906. scheme = "https"
  907. }
  908. if n.Port <= 0 || n.Port > 65535 {
  909. patch.LastError = "node port must be 1-65535"
  910. return patch, errors.New(patch.LastError)
  911. }
  912. probeURL := &url.URL{
  913. Scheme: scheme,
  914. Host: net.JoinHostPort(addr, strconv.Itoa(n.Port)),
  915. Path: normalizeBasePath(n.BasePath) + "panel/api/server/status",
  916. }
  917. req, err := http.NewRequestWithContext(
  918. netsafe.ContextWithAllowPrivate(ctx, n.AllowPrivateAddress),
  919. http.MethodGet, probeURL.String(), nil)
  920. if err != nil {
  921. patch.LastError = err.Error()
  922. return patch, err
  923. }
  924. if n.ApiToken != "" {
  925. req.Header.Set("Authorization", "Bearer "+n.ApiToken)
  926. }
  927. req.Header.Set("Accept", "application/json")
  928. client, err := runtime.HTTPClientForNode(n, proxyURL)
  929. if err != nil {
  930. patch.LastError = err.Error()
  931. return patch, err
  932. }
  933. start := time.Now()
  934. resp, err := client.Do(req)
  935. if err != nil {
  936. patch.LastError = err.Error()
  937. return patch, err
  938. }
  939. defer resp.Body.Close()
  940. patch.LatencyMs = int(time.Since(start) / time.Millisecond)
  941. if resp.StatusCode != http.StatusOK {
  942. patch.LastError = fmt.Sprintf("HTTP %d from remote panel", resp.StatusCode)
  943. return patch, errors.New(patch.LastError)
  944. }
  945. var envelope struct {
  946. Success bool `json:"success"`
  947. Msg string `json:"msg"`
  948. Obj *struct {
  949. CpuPct float64 `json:"cpu"`
  950. Mem struct {
  951. Current uint64 `json:"current"`
  952. Total uint64 `json:"total"`
  953. } `json:"mem"`
  954. Xray struct {
  955. Version string `json:"version"`
  956. State string `json:"state"`
  957. ErrorMsg string `json:"errorMsg"`
  958. } `json:"xray"`
  959. PanelVersion string `json:"panelVersion"`
  960. PanelGuid string `json:"panelGuid"`
  961. Uptime uint64 `json:"uptime"`
  962. NetIO struct {
  963. Up uint64 `json:"up"`
  964. Down uint64 `json:"down"`
  965. } `json:"netIO"`
  966. } `json:"obj"`
  967. }
  968. if err := json.NewDecoder(resp.Body).Decode(&envelope); err != nil {
  969. patch.LastError = "decode response: " + err.Error()
  970. return patch, err
  971. }
  972. if !envelope.Success || envelope.Obj == nil {
  973. patch.LastError = "remote returned success=false: " + envelope.Msg
  974. return patch, errors.New(patch.LastError)
  975. }
  976. o := envelope.Obj
  977. patch.CpuPct = o.CpuPct
  978. if o.Mem.Total > 0 {
  979. patch.MemPct = float64(o.Mem.Current) * 100.0 / float64(o.Mem.Total)
  980. }
  981. patch.XrayVersion = o.Xray.Version
  982. patch.XrayState = o.Xray.State
  983. patch.XrayError = o.Xray.ErrorMsg
  984. patch.PanelVersion = o.PanelVersion
  985. patch.Guid = o.PanelGuid
  986. patch.UptimeSecs = o.Uptime
  987. patch.NetUp = o.NetIO.Up
  988. patch.NetDown = o.NetIO.Down
  989. return patch, nil
  990. }
  991. type ProbeResultUI struct {
  992. Status string `json:"status" example:"online"`
  993. LatencyMs int `json:"latencyMs" example:"42"`
  994. XrayVersion string `json:"xrayVersion" example:"25.10.31"`
  995. PanelVersion string `json:"panelVersion" example:"v3.x.x"`
  996. CpuPct float64 `json:"cpuPct" example:"12.5"`
  997. MemPct float64 `json:"memPct" example:"45.2"`
  998. UptimeSecs uint64 `json:"uptimeSecs" example:"86400"`
  999. Error string `json:"error"`
  1000. // XrayState/XrayError are populated on successful probes even when the node's
  1001. // Xray core is not healthy. The UI uses them for a distinct "panel ok, xray failed" indicator.
  1002. XrayState string `json:"xrayState"`
  1003. XrayError string `json:"xrayError"`
  1004. }
  1005. func (p HeartbeatPatch) ToUI(ok bool) ProbeResultUI {
  1006. r := ProbeResultUI{
  1007. LatencyMs: p.LatencyMs,
  1008. XrayVersion: p.XrayVersion,
  1009. PanelVersion: p.PanelVersion,
  1010. CpuPct: p.CpuPct,
  1011. MemPct: p.MemPct,
  1012. UptimeSecs: p.UptimeSecs,
  1013. Error: FriendlyProbeError(p.LastError),
  1014. XrayState: p.XrayState,
  1015. XrayError: p.XrayError,
  1016. }
  1017. if ok {
  1018. r.Status = "online"
  1019. } else {
  1020. r.Status = "offline"
  1021. }
  1022. return r
  1023. }
  1024. func FriendlyProbeError(msg string) string {
  1025. if strings.Contains(msg, "server gave HTTP response to HTTPS client") {
  1026. return "the server speaks HTTP, not HTTPS; set the node scheme to http"
  1027. }
  1028. return msg
  1029. }