1
0

node.go 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381
  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. // nodeSelectionGrew reports a save that starts managing inbounds the panel has
  466. // not imported yet; the sweep must wait for the next clean sync to adopt them.
  467. func nodeSelectionGrew(existing, in *model.Node) bool {
  468. if in.InboundSyncMode != "selected" {
  469. return existing.InboundSyncMode == "selected"
  470. }
  471. old := make(map[string]struct{}, len(existing.InboundTags))
  472. for _, tag := range existing.InboundTags {
  473. old[tag] = struct{}{}
  474. }
  475. for _, tag := range in.InboundTags {
  476. if _, ok := old[tag]; !ok {
  477. return true
  478. }
  479. }
  480. return false
  481. }
  482. func (s *NodeService) Update(id int, in *model.Node) error {
  483. if err := s.normalize(in); err != nil {
  484. return err
  485. }
  486. inboundTagsJSON, err := json.Marshal(in.InboundTags)
  487. if err != nil {
  488. return err
  489. }
  490. db := database.GetDB()
  491. existing := &model.Node{}
  492. if err := db.Where("id = ?", id).First(existing).Error; err != nil {
  493. return err
  494. }
  495. // Blank means keep the hidden stored token; non-blank values are encrypted.
  496. apiToken := existing.ApiToken
  497. if in.ApiToken != "" {
  498. enc, eerr := nodetoken.Encrypt(id, in.ApiToken)
  499. if eerr != nil {
  500. return eerr
  501. }
  502. apiToken = enc
  503. }
  504. updates := map[string]any{
  505. "name": in.Name,
  506. "remark": in.Remark,
  507. "scheme": in.Scheme,
  508. "address": in.Address,
  509. "port": in.Port,
  510. "base_path": in.BasePath,
  511. "api_token": apiToken,
  512. "enable": in.Enable,
  513. "allow_private_address": in.AllowPrivateAddress,
  514. "tls_verify_mode": in.TlsVerifyMode,
  515. "pinned_cert_sha256": in.PinnedCertSha256,
  516. "inbound_sync_mode": in.InboundSyncMode,
  517. "inbound_tags": string(inboundTagsJSON),
  518. "outbound_tag": in.OutboundTag,
  519. }
  520. if nodeSelectionGrew(existing, in) {
  521. updates["inbounds_adopted_at"] = 0
  522. }
  523. if err := db.Transaction(func(tx *gorm.DB) error {
  524. if err := tx.Model(model.Node{}).Where("id = ?", id).Updates(updates).Error; err != nil {
  525. return err
  526. }
  527. return s.MarkNodeDirtyTx(tx, id)
  528. }); err != nil {
  529. return err
  530. }
  531. if mgr := runtime.GetManager(); mgr != nil {
  532. mgr.InvalidateNode(id)
  533. }
  534. return nil
  535. }
  536. func (s *NodeService) UpdateFromRequest(id int, req *NodeMutationRequest) error {
  537. if err := req.validateCredentials(false); err != nil {
  538. return err
  539. }
  540. in := req.toNode()
  541. if err := s.normalize(in); err != nil {
  542. return err
  543. }
  544. inboundTagsJSON, err := json.Marshal(in.InboundTags)
  545. if err != nil {
  546. return err
  547. }
  548. db := database.GetDB()
  549. existing := &model.Node{}
  550. if err := db.Where("id = ?", id).First(existing).Error; err != nil {
  551. return err
  552. }
  553. apiToken := existing.ApiToken
  554. switch {
  555. case req.ClearApiToken:
  556. apiToken = ""
  557. case req.ApiToken != nil:
  558. apiToken, err = nodetoken.Encrypt(id, *req.ApiToken)
  559. if err != nil {
  560. return err
  561. }
  562. }
  563. if apiToken == "" && in.Enable && in.TlsVerifyMode != "mtls" {
  564. return common.NewError("apiToken is required unless mtls is enabled")
  565. }
  566. updates := map[string]any{
  567. "name": in.Name,
  568. "remark": in.Remark,
  569. "scheme": in.Scheme,
  570. "address": in.Address,
  571. "port": in.Port,
  572. "base_path": in.BasePath,
  573. "api_token": apiToken,
  574. "enable": in.Enable,
  575. "allow_private_address": in.AllowPrivateAddress,
  576. "tls_verify_mode": in.TlsVerifyMode,
  577. "pinned_cert_sha256": in.PinnedCertSha256,
  578. "inbound_sync_mode": in.InboundSyncMode,
  579. "inbound_tags": string(inboundTagsJSON),
  580. "outbound_tag": in.OutboundTag,
  581. }
  582. if nodeSelectionGrew(existing, in) {
  583. updates["inbounds_adopted_at"] = 0
  584. }
  585. if err := db.Transaction(func(tx *gorm.DB) error {
  586. if err := tx.Model(model.Node{}).Where("id = ?", id).Updates(updates).Error; err != nil {
  587. return err
  588. }
  589. return s.MarkNodeDirtyTx(tx, id)
  590. }); err != nil {
  591. return err
  592. }
  593. if mgr := runtime.GetManager(); mgr != nil {
  594. mgr.InvalidateNode(id)
  595. }
  596. return nil
  597. }
  598. func (s *NodeService) RuntimeNodeFromRequest(id int, req *NodeMutationRequest) (*model.Node, error) {
  599. if err := req.validateCredentials(id == 0); err != nil {
  600. return nil, err
  601. }
  602. var n *model.Node
  603. if id > 0 {
  604. existing, err := s.GetById(id)
  605. if err != nil {
  606. return nil, err
  607. }
  608. n = existing
  609. } else {
  610. n = &model.Node{}
  611. }
  612. overlay := req.toNode()
  613. overlay.Id = id
  614. if req.ApiToken == nil {
  615. overlay.ApiToken = n.ApiToken
  616. }
  617. if req.ClearApiToken {
  618. overlay.ApiToken = ""
  619. }
  620. *n = *overlay
  621. if err := s.normalize(n); err != nil {
  622. return nil, err
  623. }
  624. if n.ApiToken == "" && n.Enable && n.TlsVerifyMode != "mtls" {
  625. return nil, common.NewError("apiToken is required unless mtls is enabled")
  626. }
  627. return n, nil
  628. }
  629. func (s *NodeService) NodeFromRequestForCertificate(req *NodeMutationRequest) (*model.Node, error) {
  630. if req == nil {
  631. return nil, common.NewError("node request is required")
  632. }
  633. n := req.toNode()
  634. if n.Scheme == "" {
  635. n.Scheme = "https"
  636. }
  637. if n.BasePath == "" {
  638. n.BasePath = "/"
  639. }
  640. if err := s.normalize(n); err != nil {
  641. return nil, err
  642. }
  643. return n, nil
  644. }
  645. // MigrateNodeTokensToActiveKey uses compare-and-swap to avoid clobbering live
  646. // changes. Current-key rows are skipped; changed and skipped counts are returned.
  647. func (s *NodeService) MigrateNodeTokensToActiveKey() (int, int, error) {
  648. codec := nodetoken.Active()
  649. if !codec.Enabled() {
  650. return 0, 0, errors.New("node-token encryption is off; set NODE_TOKEN_ENCRYPTION=migration|required and a key first")
  651. }
  652. db := database.GetDB()
  653. var nodes []*model.Node
  654. if err := db.Model(model.Node{}).Order("id asc").Find(&nodes).Error; err != nil {
  655. return 0, 0, err
  656. }
  657. changed, skipped := 0, 0
  658. for _, n := range nodes {
  659. old := n.ApiToken
  660. if old == "" {
  661. skipped++
  662. continue
  663. }
  664. if codec.EncryptedWithActive(old) {
  665. if _, err := codec.Decrypt(n.Id, old); err != nil {
  666. return changed, skipped, fmt.Errorf("node %d validate active ciphertext: %w", n.Id, err)
  667. }
  668. skipped++
  669. continue
  670. }
  671. plain, err := codec.Decrypt(n.Id, old) // plaintext passes through; old-key ciphertext is decrypted
  672. if err != nil {
  673. return changed, skipped, fmt.Errorf("node %d decrypt: %w", n.Id, err)
  674. }
  675. enc, err := codec.Encrypt(n.Id, plain)
  676. if err != nil {
  677. return changed, skipped, fmt.Errorf("node %d encrypt: %w", n.Id, err)
  678. }
  679. res := db.Model(model.Node{}).Where("id = ? AND api_token = ?", n.Id, old).Update("api_token", enc)
  680. if res.Error != nil {
  681. return changed, skipped, res.Error
  682. }
  683. if res.RowsAffected == 1 {
  684. changed++
  685. } else {
  686. skipped++ // raced with a live update; a later run handles it
  687. }
  688. }
  689. return changed, skipped, nil
  690. }
  691. func (s *NodeService) GetRemoteInboundOptions(ctx context.Context, n *model.Node) ([]runtime.RemoteInboundOption, error) {
  692. if err := s.normalize(n); err != nil {
  693. return nil, err
  694. }
  695. if n.OutboundTag == "" {
  696. return runtime.NewRemote(n, nil).ListInboundOptions(ctx)
  697. }
  698. // Mirror ProbeWithOutbound: a node being added/edited has no persistent
  699. // egress bridge yet, so route the list call through a temporary one or the
  700. // remote panel stays unreachable and the request times out.
  701. var options []runtime.RemoteInboundOption
  702. var err error
  703. s.withOutboundBridge(n.Id, n.OutboundTag, func(proxyURL string) {
  704. options, err = runtime.NewRemote(n, staticEgressResolver(proxyURL)).ListInboundOptions(ctx)
  705. })
  706. return options, err
  707. }
  708. // staticEgressResolver hands a fixed proxy URL to runtime.NewRemote. An empty
  709. // string yields a direct connection, so it doubles as the graceful fallback
  710. // when a temporary bridge can't be built.
  711. type staticEgressResolver string
  712. func (r staticEgressResolver) NodeEgressProxyURL(int) string { return string(r) }
  713. // EnsureInboundTagAllowed adds a panel-managed inbound's tag to the node's
  714. // selection when the node syncs in "selected" mode. Without it, the next
  715. // traffic sync would filter the tag out of the snapshot and the orphan sweep
  716. // would silently delete the central row the panel just created or renamed.
  717. // Tags are only ever added (never removed): on a rename the node may keep
  718. // reporting the old tag until the remote update lands, and a leftover entry
  719. // that matches nothing is harmless.
  720. func (s *NodeService) EnsureInboundTagAllowed(nodeID int, tag string) error {
  721. return s.EnsureInboundTagAllowedTx(database.GetDB(), nodeID, tag)
  722. }
  723. func (s *NodeService) EnsureInboundTagAllowedTx(tx *gorm.DB, nodeID int, tag string) error {
  724. tag = strings.TrimSpace(tag)
  725. if nodeID <= 0 || tag == "" {
  726. return nil
  727. }
  728. if tx == nil {
  729. tx = database.GetDB()
  730. }
  731. node := &model.Node{}
  732. if err := tx.Where("id = ?", nodeID).First(node).Error; err != nil {
  733. return err
  734. }
  735. if node.InboundSyncMode != "selected" {
  736. return nil
  737. }
  738. if slices.Contains(node.InboundTags, tag) {
  739. return nil
  740. }
  741. buf, err := json.Marshal(append(node.InboundTags, tag))
  742. if err != nil {
  743. return err
  744. }
  745. return tx.Model(model.Node{}).Where("id = ?", nodeID).
  746. Updates(map[string]any{"inbound_tags": string(buf)}).Error
  747. }
  748. func nodeSelectedTagSet(n *model.Node) map[string]struct{} {
  749. if n == nil || n.InboundSyncMode != "selected" {
  750. return nil
  751. }
  752. prefix := nodeTagPrefix(&n.Id)
  753. allowed := make(map[string]struct{}, len(n.InboundTags)*2)
  754. for _, tag := range n.InboundTags {
  755. allowed[tag] = struct{}{}
  756. if prefix != "" {
  757. if stripped, found := strings.CutPrefix(tag, prefix); found {
  758. allowed[stripped] = struct{}{}
  759. } else {
  760. allowed[prefix+tag] = struct{}{}
  761. }
  762. }
  763. }
  764. return allowed
  765. }
  766. // A deselected tag is still served by the node — FilterNodeSnapshot just stops
  767. // reporting it — so its absence must never be read as "the node deleted it".
  768. func unmanagedTagPredicate(n *model.Node) func(string) bool {
  769. managed := nodeSelectedTagSet(n)
  770. if managed == nil {
  771. return func(string) bool { return false }
  772. }
  773. return func(tag string) bool {
  774. _, ok := managed[tag]
  775. return !ok
  776. }
  777. }
  778. func FilterNodeSnapshot(n *model.Node, snap *runtime.TrafficSnapshot) {
  779. if n == nil || snap == nil || n.InboundSyncMode != "selected" {
  780. return
  781. }
  782. allowed := nodeSelectedTagSet(n)
  783. for _, tag := range snap.ManagedAliases {
  784. allowed[tag] = struct{}{}
  785. }
  786. filtered := make([]*model.Inbound, 0, len(snap.Inbounds))
  787. for _, inbound := range snap.Inbounds {
  788. if inbound == nil {
  789. continue
  790. }
  791. if _, ok := allowed[inbound.Tag]; ok {
  792. filtered = append(filtered, inbound)
  793. }
  794. }
  795. snap.Inbounds = filtered
  796. }
  797. func (s *NodeService) Delete(id int) error {
  798. db := database.GetDB()
  799. // Refuse to delete a node that still owns inbounds: dropping the node row
  800. // while inbounds keep its node_id leaves orphaned, dangling references that
  801. // confuse node sync, subscriptions and cleanup. The operator must detach or
  802. // remove those inbounds first. (DB-002)
  803. var attached int64
  804. if err := db.Model(&model.Inbound{}).Where("node_id = ?", id).Count(&attached).Error; err != nil {
  805. return err
  806. }
  807. if attached > 0 {
  808. return common.NewError(fmt.Sprintf("cannot delete node: %d inbound(s) still attached to it; detach or delete them first", attached))
  809. }
  810. // Capture the node's guid before deleting the row so we can drop its per-node
  811. // IP attribution. NodeClientIp is keyed by the node's attribution key, which
  812. // is its guid normally but its node-unique key for a cloned/ambiguous-guid
  813. // node (see effectiveNodeKey) — so we purge both below.
  814. var guid string
  815. var n model.Node
  816. if err := db.Select("guid").Where("id = ?", id).First(&n).Error; err == nil {
  817. guid = n.Guid
  818. }
  819. // Delete the node row and its per-node child rows atomically. Remove the
  820. // children (traffic baselines, IP attribution) before the parent node row so
  821. // the ordering already matches a future ON DELETE constraint. Delete stays
  822. // tolerant of a missing node row so it can still clean up orphaned baselines.
  823. if err := db.Transaction(func(tx *gorm.DB) error {
  824. if err := tx.Where("node_id = ?", id).Delete(&model.NodeClientTraffic{}).Error; err != nil {
  825. return err
  826. }
  827. guids := []string{synthNodeGuid(id)}
  828. if guid != "" {
  829. guids = append(guids, guid)
  830. }
  831. if err := tx.Where("node_guid IN ?", guids).Delete(&model.NodeClientIp{}).Error; err != nil {
  832. return err
  833. }
  834. return tx.Where("id = ?", id).Delete(&model.Node{}).Error
  835. }); err != nil {
  836. return err
  837. }
  838. if mgr := runtime.GetManager(); mgr != nil {
  839. mgr.InvalidateNode(id)
  840. }
  841. nodeMetrics.drop(nodeMetricKey(id, "cpu"))
  842. nodeMetrics.drop(nodeMetricKey(id, "mem"))
  843. return nil
  844. }
  845. func (s *NodeService) SetEnable(id int, enable bool) error {
  846. db := database.GetDB()
  847. if err := db.Model(model.Node{}).Where("id = ?", id).Update("enable", enable).Error; err != nil {
  848. return err
  849. }
  850. if mgr := runtime.GetManager(); mgr != nil {
  851. mgr.InvalidateNode(id)
  852. }
  853. return nil
  854. }
  855. // GetWebCertFiles asks a node for its own web TLS certificate/key file paths,
  856. // used by "Set Cert from Panel" so a node-assigned inbound gets paths that
  857. // exist on the node rather than the central panel. See issue #4854.
  858. func (s *NodeService) GetWebCertFiles(id int) (*runtime.WebCertFiles, error) {
  859. n, err := s.GetById(id)
  860. if err != nil || n == nil {
  861. return nil, fmt.Errorf("node not found")
  862. }
  863. if !n.Enable {
  864. return nil, fmt.Errorf("node is disabled")
  865. }
  866. mgr := runtime.GetManager()
  867. if mgr == nil {
  868. return nil, fmt.Errorf("runtime manager unavailable")
  869. }
  870. remote, err := mgr.RemoteFor(n)
  871. if err != nil {
  872. return nil, err
  873. }
  874. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  875. defer cancel()
  876. return remote.GetWebCertFiles(ctx)
  877. }
  878. // NodeUpdateResult reports the outcome of triggering a panel self-update on one
  879. // node so the UI can show per-node success/failure for a bulk request.
  880. type NodeUpdateResult struct {
  881. Id int `json:"id"`
  882. Name string `json:"name"`
  883. OK bool `json:"ok"`
  884. Error string `json:"error,omitempty"`
  885. }
  886. // UpdatePanels triggers the official self-updater on each given node. Only
  887. // enabled, online nodes are eligible — an offline node can't be reached, so it
  888. // is reported as skipped rather than silently dropped.
  889. func (s *NodeService) UpdatePanels(ids []int, dev bool) ([]NodeUpdateResult, error) {
  890. mgr := runtime.GetManager()
  891. if mgr == nil {
  892. return nil, fmt.Errorf("runtime manager unavailable")
  893. }
  894. results := make([]NodeUpdateResult, 0, len(ids))
  895. for _, id := range ids {
  896. n, err := s.GetById(id)
  897. if err != nil || n == nil {
  898. results = append(results, NodeUpdateResult{Id: id, OK: false, Error: "node not found"})
  899. continue
  900. }
  901. res := NodeUpdateResult{Id: id, Name: n.Name}
  902. switch {
  903. case !n.Enable:
  904. res.Error = "node is disabled"
  905. case n.Status != "online":
  906. res.Error = "node is offline"
  907. default:
  908. remote, remoteErr := mgr.RemoteFor(n)
  909. if remoteErr != nil {
  910. res.Error = remoteErr.Error()
  911. break
  912. }
  913. ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
  914. updErr := remote.UpdatePanel(ctx, dev)
  915. cancel()
  916. if updErr != nil {
  917. res.Error = updErr.Error()
  918. } else {
  919. res.OK = true
  920. }
  921. }
  922. results = append(results, res)
  923. }
  924. return results, nil
  925. }
  926. func (s *NodeService) UpdateHeartbeat(id int, p HeartbeatPatch) error {
  927. db := database.GetDB()
  928. updates := map[string]any{
  929. "status": p.Status,
  930. "last_heartbeat": p.LastHeartbeat,
  931. "latency_ms": p.LatencyMs,
  932. "xray_version": p.XrayVersion,
  933. "panel_version": p.PanelVersion,
  934. "cpu_pct": p.CpuPct,
  935. "mem_pct": p.MemPct,
  936. "uptime_secs": p.UptimeSecs,
  937. "net_up": p.NetUp,
  938. "net_down": p.NetDown,
  939. "last_error": p.LastError,
  940. "xray_state": p.XrayState,
  941. "xray_error": p.XrayError,
  942. }
  943. // Only learn the GUID; never clear a known one if an old-build node (or a
  944. // failed probe) reports none, so the stable identity survives blips.
  945. if p.Guid != "" {
  946. updates["guid"] = p.Guid
  947. s.warnOnDuplicateGuid(id, p.Guid)
  948. }
  949. if err := db.Model(model.Node{}).Where("id = ?", id).Updates(updates).Error; err != nil {
  950. return err
  951. }
  952. if p.Status == "online" {
  953. now := time.Unix(p.LastHeartbeat, 0)
  954. nodeMetrics.append(nodeMetricKey(id, "cpu"), now, p.CpuPct)
  955. nodeMetrics.append(nodeMetricKey(id, "mem"), now, p.MemPct)
  956. nodeMetrics.append(nodeMetricKey(id, "netUp"), now, float64(p.NetUp))
  957. nodeMetrics.append(nodeMetricKey(id, "netDown"), now, float64(p.NetDown))
  958. }
  959. return nil
  960. }
  961. // warnedDupGuid remembers the (nodeID -> guid) pairs already warned about so a
  962. // cloned-server collision is logged once, not every heartbeat.
  963. var warnedDupGuid sync.Map
  964. // warnOnDuplicateGuid logs once when a node reports a panelGuid already held by
  965. // another node or by the master itself (the cloned-server footgun). Attribution
  966. // still works — it falls back to node-unique keys — but the operator should
  967. // regenerate the duplicate panelGuid to restore real identity and per-node IP
  968. // attribution. Re-arms if the collision later clears.
  969. func (s *NodeService) warnOnDuplicateGuid(id int, guid string) {
  970. var clash int64
  971. database.GetDB().Model(&model.Node{}).Where("guid = ? AND id <> ?", guid, id).Count(&clash)
  972. masterGuid, _ := (&SettingService{}).GetPanelGuid()
  973. if clash == 0 && guid != masterGuid {
  974. warnedDupGuid.Delete(id)
  975. return
  976. }
  977. if prev, ok := warnedDupGuid.Load(id); ok && prev == guid {
  978. return
  979. }
  980. warnedDupGuid.Store(id, guid)
  981. 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)
  982. }
  983. func (s *NodeService) MarkNodeDirty(id int) error {
  984. return s.MarkNodeDirtyTx(database.GetDB(), id)
  985. }
  986. func (s *NodeService) MarkNodeDirtyTx(tx *gorm.DB, id int) error {
  987. if id <= 0 {
  988. return nil
  989. }
  990. if tx == nil {
  991. return errors.New("nil db transaction")
  992. }
  993. return tx.Model(model.Node{}).
  994. Where("id = ?", id).
  995. Updates(map[string]any{
  996. "config_dirty": true,
  997. "config_dirty_at": time.Now().UnixMilli(),
  998. }).Error
  999. }
  1000. func (s *NodeService) ClearNodeDirty(id int, dirtyAt int64) error {
  1001. if id <= 0 {
  1002. return nil
  1003. }
  1004. return database.GetDB().Model(model.Node{}).
  1005. Where("id = ? AND config_dirty_at = ?", id, dirtyAt).
  1006. Update("config_dirty", false).Error
  1007. }
  1008. func (s *NodeService) MarkNodeInboundsAdopted(id int) error {
  1009. if id <= 0 {
  1010. return nil
  1011. }
  1012. return database.GetDB().Model(model.Node{}).
  1013. Where("id = ? AND inbounds_adopted_at = 0", id).
  1014. Update("inbounds_adopted_at", time.Now().Unix()).Error
  1015. }
  1016. func (s *NodeService) NodeSyncState(id int) (enabled bool, status string, dirty bool, dirtyAt int64, err error) {
  1017. if id <= 0 {
  1018. return false, "", false, 0, errors.New("invalid node id")
  1019. }
  1020. var row model.Node
  1021. err = database.GetDB().Model(model.Node{}).
  1022. Select("enable", "status", "config_dirty", "config_dirty_at").
  1023. Where("id = ?", id).
  1024. First(&row).Error
  1025. if err != nil {
  1026. return false, "", false, 0, err
  1027. }
  1028. return row.Enable, row.Status, row.ConfigDirty, row.ConfigDirtyAt, nil
  1029. }
  1030. // IsNodePending reports whether a save targeting this node was deferred because
  1031. // the node is unreachable right now — offline or disabled — so the edit only
  1032. // reaches it on the next reconcile. It deliberately ignores config_dirty: that
  1033. // flag is set on EVERY node-backed edit as the reconcile self-heal marker,
  1034. // including edits pushed live to an online node, so keying the user-facing
  1035. // "saved, node offline, will sync" toast off it fired the warning on every save
  1036. // to a perfectly healthy online node.
  1037. func (s *NodeService) IsNodePending(id int) bool {
  1038. enabled, status, _, _, err := s.NodeSyncState(id)
  1039. if err != nil {
  1040. return false
  1041. }
  1042. return !enabled || status != "online"
  1043. }
  1044. func nodeMetricKey(id int, metric string) string {
  1045. return "node:" + strconv.Itoa(id) + ":" + metric
  1046. }
  1047. func (s *NodeService) AggregateNodeMetric(id int, metric string, bucketSeconds int, maxPoints int) []map[string]any {
  1048. return nodeMetrics.aggregate(nodeMetricKey(id, metric), bucketSeconds, maxPoints)
  1049. }
  1050. func (s *NodeService) Probe(ctx context.Context, n *model.Node) (HeartbeatPatch, error) {
  1051. proxyURL := ""
  1052. if n.OutboundTag != "" {
  1053. if mgr := runtime.GetManager(); mgr != nil {
  1054. proxyURL = mgr.NodeEgressProxyURL(n.Id)
  1055. }
  1056. }
  1057. return s.probe(ctx, n, proxyURL)
  1058. }
  1059. func (s *NodeService) ProbeWithOutbound(ctx context.Context, n *model.Node, outboundTag string) (HeartbeatPatch, error) {
  1060. if outboundTag == "" {
  1061. return s.Probe(ctx, n)
  1062. }
  1063. var patch HeartbeatPatch
  1064. var err error
  1065. s.withOutboundBridge(n.Id, outboundTag, func(proxyURL string) {
  1066. if proxyURL == "" {
  1067. patch, err = s.Probe(ctx, n)
  1068. return
  1069. }
  1070. patch, err = s.probe(ctx, n, proxyURL)
  1071. })
  1072. return patch, err
  1073. }
  1074. // withOutboundBridge stands up a temporary loopback SOCKS5 inbound in the
  1075. // running Xray, routes it through outboundTag, and runs fn with the bridge's
  1076. // proxy URL before tearing it down. It is used to reach a node through its
  1077. // connection outbound before the persistent egress bridge has been injected
  1078. // into the config (e.g. while the node is still being added or edited). When
  1079. // Xray isn't running or the bridge can't be built, fn runs with an empty
  1080. // proxyURL so callers fall back to a direct connection.
  1081. func (s *NodeService) withOutboundBridge(nodeID int, outboundTag string, fn func(proxyURL string)) {
  1082. proc := XrayProcess()
  1083. if proc == nil || !proc.IsRunning() {
  1084. fn("")
  1085. return
  1086. }
  1087. apiPort := proc.GetAPIPort()
  1088. if apiPort <= 0 {
  1089. fn("")
  1090. return
  1091. }
  1092. listener, err := (&net.ListenConfig{}).Listen(context.Background(), "tcp", "127.0.0.1:0")
  1093. if err != nil {
  1094. fn("")
  1095. return
  1096. }
  1097. port := listener.Addr().(*net.TCPAddr).Port
  1098. listener.Close()
  1099. tag := fmt.Sprintf("node-test-%d-%d", nodeID, time.Now().UnixNano())
  1100. proxyURL := fmt.Sprintf("socks5://127.0.0.1:%d", port)
  1101. inboundJSON, err := json.Marshal(xray.InboundConfig{
  1102. Listen: json_util.RawMessage(`"127.0.0.1"`),
  1103. Port: port,
  1104. Protocol: "socks",
  1105. Settings: json_util.RawMessage(`{"auth":"noauth","udp":false}`),
  1106. Tag: tag,
  1107. })
  1108. if err != nil {
  1109. fn("")
  1110. return
  1111. }
  1112. cfg := proc.GetConfig()
  1113. routing := map[string]any{}
  1114. if len(cfg.RouterConfig) > 0 {
  1115. _ = json.Unmarshal(cfg.RouterConfig, &routing)
  1116. }
  1117. rules, _ := routing["rules"].([]any)
  1118. rule := map[string]any{
  1119. "type": "field",
  1120. "inboundTag": []any{tag},
  1121. }
  1122. if routingTagIsBalancer(routing, outboundTag) {
  1123. rule["balancerTag"] = outboundTag
  1124. } else {
  1125. rule["outboundTag"] = outboundTag
  1126. }
  1127. routing["rules"] = append([]any{rule}, rules...)
  1128. routingJSON, err := json.Marshal(routing)
  1129. if err != nil {
  1130. fn("")
  1131. return
  1132. }
  1133. originalRoutingJSON := cfg.RouterConfig
  1134. api := xray.XrayAPI{}
  1135. if err := api.Init(apiPort); err != nil {
  1136. fn("")
  1137. return
  1138. }
  1139. defer api.Close()
  1140. if err := api.AddInbound(inboundJSON); err != nil {
  1141. fn("")
  1142. return
  1143. }
  1144. defer func() {
  1145. if err := api.DelInbound(tag); err != nil {
  1146. logger.Warning("remove temp node bridge inbound failed:", err)
  1147. }
  1148. }()
  1149. if err := api.ApplyRoutingConfig(routingJSON); err != nil {
  1150. fn("")
  1151. return
  1152. }
  1153. defer func() {
  1154. restore := originalRoutingJSON
  1155. if len(restore) == 0 {
  1156. restore = []byte("{}")
  1157. }
  1158. if err := api.ApplyRoutingConfig(restore); err != nil {
  1159. logger.Warning("restore routing after node bridge failed:", err)
  1160. }
  1161. }()
  1162. fn(proxyURL)
  1163. }
  1164. // A status envelope holds a handful of scalars; the cap keeps a hostile or
  1165. // broken node from dictating the master's allocation on every heartbeat.
  1166. const maxProbeBodyBytes = 1 << 20 // 1 MiB
  1167. func (s *NodeService) probe(ctx context.Context, n *model.Node, proxyURL string) (HeartbeatPatch, error) {
  1168. patch := HeartbeatPatch{LastHeartbeat: time.Now().Unix()}
  1169. addr, err := netsafe.NormalizeHost(n.Address)
  1170. if err != nil {
  1171. patch.LastError = err.Error()
  1172. return patch, err
  1173. }
  1174. scheme := n.Scheme
  1175. if scheme != "http" && scheme != "https" {
  1176. scheme = "https"
  1177. }
  1178. if n.Port <= 0 || n.Port > 65535 {
  1179. patch.LastError = "node port must be 1-65535"
  1180. return patch, errors.New(patch.LastError)
  1181. }
  1182. probeURL := &url.URL{
  1183. Scheme: scheme,
  1184. Host: net.JoinHostPort(addr, strconv.Itoa(n.Port)),
  1185. Path: normalizeBasePath(n.BasePath) + "panel/api/server/status",
  1186. }
  1187. req, err := http.NewRequestWithContext(
  1188. netsafe.ContextWithAllowPrivate(ctx, n.AllowPrivateAddress),
  1189. http.MethodGet, probeURL.String(), nil)
  1190. if err != nil {
  1191. patch.LastError = err.Error()
  1192. return patch, err
  1193. }
  1194. if n.ApiToken != "" {
  1195. token, derr := nodetoken.Decrypt(n.Id, n.ApiToken)
  1196. if derr != nil {
  1197. patch.LastError = derr.Error()
  1198. return patch, derr
  1199. }
  1200. req.Header.Set("Authorization", "Bearer "+token)
  1201. }
  1202. req.Header.Set("Accept", "application/json")
  1203. client, err := runtime.HTTPClientForNode(n, proxyURL)
  1204. if err != nil {
  1205. patch.LastError = err.Error()
  1206. return patch, err
  1207. }
  1208. start := time.Now()
  1209. resp, err := client.Do(req)
  1210. if err != nil {
  1211. patch.LastError = err.Error()
  1212. return patch, err
  1213. }
  1214. defer resp.Body.Close()
  1215. patch.LatencyMs = int(time.Since(start) / time.Millisecond)
  1216. if resp.StatusCode != http.StatusOK {
  1217. patch.LastError = fmt.Sprintf("HTTP %d from remote panel", resp.StatusCode)
  1218. return patch, errors.New(patch.LastError)
  1219. }
  1220. var envelope struct {
  1221. Success bool `json:"success"`
  1222. Msg string `json:"msg"`
  1223. Obj *struct {
  1224. CpuPct float64 `json:"cpu"`
  1225. Mem struct {
  1226. Current uint64 `json:"current"`
  1227. Total uint64 `json:"total"`
  1228. } `json:"mem"`
  1229. Xray struct {
  1230. Version string `json:"version"`
  1231. State string `json:"state"`
  1232. ErrorMsg string `json:"errorMsg"`
  1233. } `json:"xray"`
  1234. PanelVersion string `json:"panelVersion"`
  1235. PanelGuid string `json:"panelGuid"`
  1236. Uptime uint64 `json:"uptime"`
  1237. NetIO struct {
  1238. Up uint64 `json:"up"`
  1239. Down uint64 `json:"down"`
  1240. } `json:"netIO"`
  1241. } `json:"obj"`
  1242. }
  1243. if err := json.NewDecoder(io.LimitReader(resp.Body, maxProbeBodyBytes)).Decode(&envelope); err != nil {
  1244. patch.LastError = "decode response: " + err.Error()
  1245. return patch, err
  1246. }
  1247. if !envelope.Success || envelope.Obj == nil {
  1248. patch.LastError = "remote returned success=false: " + envelope.Msg
  1249. return patch, errors.New(patch.LastError)
  1250. }
  1251. o := envelope.Obj
  1252. patch.CpuPct = o.CpuPct
  1253. if o.Mem.Total > 0 {
  1254. patch.MemPct = float64(o.Mem.Current) * 100.0 / float64(o.Mem.Total)
  1255. }
  1256. patch.XrayVersion = o.Xray.Version
  1257. patch.XrayState = o.Xray.State
  1258. patch.XrayError = o.Xray.ErrorMsg
  1259. patch.PanelVersion = o.PanelVersion
  1260. patch.Guid = o.PanelGuid
  1261. patch.UptimeSecs = o.Uptime
  1262. patch.NetUp = o.NetIO.Up
  1263. patch.NetDown = o.NetIO.Down
  1264. return patch, nil
  1265. }
  1266. type ProbeResultUI struct {
  1267. Status string `json:"status" example:"online"`
  1268. LatencyMs int `json:"latencyMs" example:"42"`
  1269. XrayVersion string `json:"xrayVersion" example:"25.10.31"`
  1270. PanelVersion string `json:"panelVersion" example:"v3.x.x"`
  1271. CpuPct float64 `json:"cpuPct" example:"12.5"`
  1272. MemPct float64 `json:"memPct" example:"45.2"`
  1273. UptimeSecs uint64 `json:"uptimeSecs" example:"86400"`
  1274. Error string `json:"error"`
  1275. // XrayState/XrayError are populated on successful probes even when the node's
  1276. // Xray core is not healthy. The UI uses them for a distinct "panel ok, xray failed" indicator.
  1277. XrayState string `json:"xrayState"`
  1278. XrayError string `json:"xrayError"`
  1279. }
  1280. func (p HeartbeatPatch) ToUI(ok bool) ProbeResultUI {
  1281. r := ProbeResultUI{
  1282. LatencyMs: p.LatencyMs,
  1283. XrayVersion: p.XrayVersion,
  1284. PanelVersion: p.PanelVersion,
  1285. CpuPct: p.CpuPct,
  1286. MemPct: p.MemPct,
  1287. UptimeSecs: p.UptimeSecs,
  1288. Error: FriendlyProbeError(p.LastError),
  1289. XrayState: p.XrayState,
  1290. XrayError: p.XrayError,
  1291. }
  1292. if ok {
  1293. r.Status = "online"
  1294. } else {
  1295. r.Status = "offline"
  1296. }
  1297. return r
  1298. }
  1299. func FriendlyProbeError(msg string) string {
  1300. if strings.Contains(msg, "server gave HTTP response to HTTPS client") {
  1301. return "the server speaks HTTP, not HTTPS; set the node scheme to http"
  1302. }
  1303. return msg
  1304. }