node.go 41 KB

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