node.go 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386
  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. for _, metric := range NodeMetricKeys {
  842. nodeMetrics.drop(nodeMetricKey(id, metric))
  843. }
  844. return nil
  845. }
  846. func (s *NodeService) SetEnable(id int, enable bool) error {
  847. db := database.GetDB()
  848. if err := db.Model(model.Node{}).Where("id = ?", id).Update("enable", enable).Error; err != nil {
  849. return err
  850. }
  851. if mgr := runtime.GetManager(); mgr != nil {
  852. mgr.InvalidateNode(id)
  853. }
  854. return nil
  855. }
  856. // GetWebCertFiles asks a node for its own web TLS certificate/key file paths,
  857. // used by "Set Cert from Panel" so a node-assigned inbound gets paths that
  858. // exist on the node rather than the central panel. See issue #4854.
  859. func (s *NodeService) GetWebCertFiles(id int) (*runtime.WebCertFiles, error) {
  860. n, err := s.GetById(id)
  861. if err != nil || n == nil {
  862. return nil, fmt.Errorf("node not found")
  863. }
  864. if !n.Enable {
  865. return nil, fmt.Errorf("node is disabled")
  866. }
  867. mgr := runtime.GetManager()
  868. if mgr == nil {
  869. return nil, fmt.Errorf("runtime manager unavailable")
  870. }
  871. remote, err := mgr.RemoteFor(n)
  872. if err != nil {
  873. return nil, err
  874. }
  875. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  876. defer cancel()
  877. return remote.GetWebCertFiles(ctx)
  878. }
  879. // NodeUpdateResult reports the outcome of triggering a panel self-update on one
  880. // node so the UI can show per-node success/failure for a bulk request.
  881. type NodeUpdateResult struct {
  882. Id int `json:"id"`
  883. Name string `json:"name"`
  884. OK bool `json:"ok"`
  885. Error string `json:"error,omitempty"`
  886. }
  887. // UpdatePanels triggers the official self-updater on each given node. Only
  888. // enabled, online nodes are eligible — an offline node can't be reached, so it
  889. // is reported as skipped rather than silently dropped.
  890. func (s *NodeService) UpdatePanels(ids []int, dev bool) ([]NodeUpdateResult, error) {
  891. mgr := runtime.GetManager()
  892. if mgr == nil {
  893. return nil, fmt.Errorf("runtime manager unavailable")
  894. }
  895. results, panics := fanoutInboundResults(ids, nodeFanoutConcurrency, func(i int) NodeUpdateResult {
  896. id := ids[i]
  897. n, err := s.GetById(id)
  898. if err != nil || n == nil {
  899. return NodeUpdateResult{Id: id, OK: false, Error: "node not found"}
  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. return res
  923. })
  924. for i, panicErr := range panics {
  925. if panicErr != nil {
  926. results[i] = NodeUpdateResult{Id: ids[i], Error: panicErr.Error()}
  927. }
  928. }
  929. return results, nil
  930. }
  931. func (s *NodeService) UpdateHeartbeat(id int, p HeartbeatPatch) error {
  932. db := database.GetDB()
  933. updates := map[string]any{
  934. "status": p.Status,
  935. "last_heartbeat": p.LastHeartbeat,
  936. "latency_ms": p.LatencyMs,
  937. "xray_version": p.XrayVersion,
  938. "panel_version": p.PanelVersion,
  939. "cpu_pct": p.CpuPct,
  940. "mem_pct": p.MemPct,
  941. "uptime_secs": p.UptimeSecs,
  942. "net_up": p.NetUp,
  943. "net_down": p.NetDown,
  944. "last_error": p.LastError,
  945. "xray_state": p.XrayState,
  946. "xray_error": p.XrayError,
  947. }
  948. // Only learn the GUID; never clear a known one if an old-build node (or a
  949. // failed probe) reports none, so the stable identity survives blips.
  950. if p.Guid != "" {
  951. updates["guid"] = p.Guid
  952. s.warnOnDuplicateGuid(id, p.Guid)
  953. }
  954. if err := db.Model(model.Node{}).Where("id = ?", id).Updates(updates).Error; err != nil {
  955. return err
  956. }
  957. if p.Status == "online" {
  958. now := time.Unix(p.LastHeartbeat, 0)
  959. nodeMetrics.append(nodeMetricKey(id, "cpu"), now, p.CpuPct)
  960. nodeMetrics.append(nodeMetricKey(id, "mem"), now, p.MemPct)
  961. nodeMetrics.append(nodeMetricKey(id, "netUp"), now, float64(p.NetUp))
  962. nodeMetrics.append(nodeMetricKey(id, "netDown"), now, float64(p.NetDown))
  963. }
  964. return nil
  965. }
  966. // warnedDupGuid remembers the (nodeID -> guid) pairs already warned about so a
  967. // cloned-server collision is logged once, not every heartbeat.
  968. var warnedDupGuid sync.Map
  969. // warnOnDuplicateGuid logs once when a node reports a panelGuid already held by
  970. // another node or by the master itself (the cloned-server footgun). Attribution
  971. // still works — it falls back to node-unique keys — but the operator should
  972. // regenerate the duplicate panelGuid to restore real identity and per-node IP
  973. // attribution. Re-arms if the collision later clears.
  974. func (s *NodeService) warnOnDuplicateGuid(id int, guid string) {
  975. var clash int64
  976. database.GetDB().Model(&model.Node{}).Where("guid = ? AND id <> ?", guid, id).Count(&clash)
  977. masterGuid, _ := (&SettingService{}).GetPanelGuid()
  978. if clash == 0 && guid != masterGuid {
  979. warnedDupGuid.Delete(id)
  980. return
  981. }
  982. if prev, ok := warnedDupGuid.Load(id); ok && prev == guid {
  983. return
  984. }
  985. warnedDupGuid.Store(id, guid)
  986. 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)
  987. }
  988. func (s *NodeService) MarkNodeDirty(id int) error {
  989. return s.MarkNodeDirtyTx(database.GetDB(), id)
  990. }
  991. func (s *NodeService) MarkNodeDirtyTx(tx *gorm.DB, id int) error {
  992. if id <= 0 {
  993. return nil
  994. }
  995. if tx == nil {
  996. return errors.New("nil db transaction")
  997. }
  998. return tx.Model(model.Node{}).
  999. Where("id = ?", id).
  1000. Updates(map[string]any{
  1001. "config_dirty": true,
  1002. "config_dirty_at": time.Now().UnixMilli(),
  1003. }).Error
  1004. }
  1005. func (s *NodeService) ClearNodeDirty(id int, dirtyAt int64) error {
  1006. if id <= 0 {
  1007. return nil
  1008. }
  1009. return database.GetDB().Model(model.Node{}).
  1010. Where("id = ? AND config_dirty_at = ?", id, dirtyAt).
  1011. Update("config_dirty", false).Error
  1012. }
  1013. func (s *NodeService) MarkNodeInboundsAdopted(id int) error {
  1014. if id <= 0 {
  1015. return nil
  1016. }
  1017. return database.GetDB().Model(model.Node{}).
  1018. Where("id = ? AND inbounds_adopted_at = 0", id).
  1019. Update("inbounds_adopted_at", time.Now().Unix()).Error
  1020. }
  1021. func (s *NodeService) NodeSyncState(id int) (enabled bool, status string, dirty bool, dirtyAt int64, err error) {
  1022. if id <= 0 {
  1023. return false, "", false, 0, errors.New("invalid node id")
  1024. }
  1025. var row model.Node
  1026. err = database.GetDB().Model(model.Node{}).
  1027. Select("enable", "status", "config_dirty", "config_dirty_at").
  1028. Where("id = ?", id).
  1029. First(&row).Error
  1030. if err != nil {
  1031. return false, "", false, 0, err
  1032. }
  1033. return row.Enable, row.Status, row.ConfigDirty, row.ConfigDirtyAt, nil
  1034. }
  1035. // IsNodePending reports whether a save targeting this node was deferred because
  1036. // the node is unreachable right now — offline or disabled — so the edit only
  1037. // reaches it on the next reconcile. It deliberately ignores config_dirty: that
  1038. // flag is set on EVERY node-backed edit as the reconcile self-heal marker,
  1039. // including edits pushed live to an online node, so keying the user-facing
  1040. // "saved, node offline, will sync" toast off it fired the warning on every save
  1041. // to a perfectly healthy online node.
  1042. func (s *NodeService) IsNodePending(id int) bool {
  1043. enabled, status, _, _, err := s.NodeSyncState(id)
  1044. if err != nil {
  1045. return false
  1046. }
  1047. return !enabled || status != "online"
  1048. }
  1049. func nodeMetricKey(id int, metric string) string {
  1050. return "node:" + strconv.Itoa(id) + ":" + metric
  1051. }
  1052. func (s *NodeService) AggregateNodeMetric(id int, metric string, bucketSeconds int, maxPoints int) []map[string]any {
  1053. return nodeMetrics.aggregate(nodeMetricKey(id, metric), bucketSeconds, maxPoints)
  1054. }
  1055. func (s *NodeService) Probe(ctx context.Context, n *model.Node) (HeartbeatPatch, error) {
  1056. proxyURL := ""
  1057. if n.OutboundTag != "" {
  1058. if mgr := runtime.GetManager(); mgr != nil {
  1059. proxyURL = mgr.NodeEgressProxyURL(n.Id)
  1060. }
  1061. }
  1062. return s.probe(ctx, n, proxyURL)
  1063. }
  1064. func (s *NodeService) ProbeWithOutbound(ctx context.Context, n *model.Node, outboundTag string) (HeartbeatPatch, error) {
  1065. if outboundTag == "" {
  1066. return s.Probe(ctx, n)
  1067. }
  1068. var patch HeartbeatPatch
  1069. var err error
  1070. s.withOutboundBridge(n.Id, outboundTag, func(proxyURL string) {
  1071. if proxyURL == "" {
  1072. patch, err = s.Probe(ctx, n)
  1073. return
  1074. }
  1075. patch, err = s.probe(ctx, n, proxyURL)
  1076. })
  1077. return patch, err
  1078. }
  1079. // withOutboundBridge stands up a temporary loopback SOCKS5 inbound in the
  1080. // running Xray, routes it through outboundTag, and runs fn with the bridge's
  1081. // proxy URL before tearing it down. It is used to reach a node through its
  1082. // connection outbound before the persistent egress bridge has been injected
  1083. // into the config (e.g. while the node is still being added or edited). When
  1084. // Xray isn't running or the bridge can't be built, fn runs with an empty
  1085. // proxyURL so callers fall back to a direct connection.
  1086. func (s *NodeService) withOutboundBridge(nodeID int, outboundTag string, fn func(proxyURL string)) {
  1087. proc := XrayProcess()
  1088. if proc == nil || !proc.IsRunning() {
  1089. fn("")
  1090. return
  1091. }
  1092. apiPort := proc.GetAPIPort()
  1093. if apiPort <= 0 {
  1094. fn("")
  1095. return
  1096. }
  1097. listener, err := (&net.ListenConfig{}).Listen(context.Background(), "tcp", "127.0.0.1:0")
  1098. if err != nil {
  1099. fn("")
  1100. return
  1101. }
  1102. port := listener.Addr().(*net.TCPAddr).Port
  1103. listener.Close()
  1104. tag := fmt.Sprintf("node-test-%d-%d", nodeID, time.Now().UnixNano())
  1105. proxyURL := fmt.Sprintf("socks5://127.0.0.1:%d", port)
  1106. inboundJSON, err := json.Marshal(xray.InboundConfig{
  1107. Listen: json_util.RawMessage(`"127.0.0.1"`),
  1108. Port: port,
  1109. Protocol: "socks",
  1110. Settings: json_util.RawMessage(`{"auth":"noauth","udp":false}`),
  1111. Tag: tag,
  1112. })
  1113. if err != nil {
  1114. fn("")
  1115. return
  1116. }
  1117. cfg := proc.GetConfig()
  1118. routing := map[string]any{}
  1119. if len(cfg.RouterConfig) > 0 {
  1120. _ = json.Unmarshal(cfg.RouterConfig, &routing)
  1121. }
  1122. rules, _ := routing["rules"].([]any)
  1123. rule := map[string]any{
  1124. "type": "field",
  1125. "inboundTag": []any{tag},
  1126. }
  1127. if routingTagIsBalancer(routing, outboundTag) {
  1128. rule["balancerTag"] = outboundTag
  1129. } else {
  1130. rule["outboundTag"] = outboundTag
  1131. }
  1132. routing["rules"] = append([]any{rule}, rules...)
  1133. routingJSON, err := json.Marshal(routing)
  1134. if err != nil {
  1135. fn("")
  1136. return
  1137. }
  1138. originalRoutingJSON := cfg.RouterConfig
  1139. api := xray.XrayAPI{}
  1140. if err := api.Init(apiPort); err != nil {
  1141. fn("")
  1142. return
  1143. }
  1144. defer api.Close()
  1145. if err := api.AddInbound(inboundJSON); err != nil {
  1146. fn("")
  1147. return
  1148. }
  1149. defer func() {
  1150. if err := api.DelInbound(tag); err != nil {
  1151. logger.Warning("remove temp node bridge inbound failed:", err)
  1152. }
  1153. }()
  1154. if err := api.ApplyRoutingConfig(routingJSON); err != nil {
  1155. fn("")
  1156. return
  1157. }
  1158. defer func() {
  1159. restore := originalRoutingJSON
  1160. if len(restore) == 0 {
  1161. restore = []byte("{}")
  1162. }
  1163. if err := api.ApplyRoutingConfig(restore); err != nil {
  1164. logger.Warning("restore routing after node bridge failed:", err)
  1165. }
  1166. }()
  1167. fn(proxyURL)
  1168. }
  1169. // A status envelope holds a handful of scalars; the cap keeps a hostile or
  1170. // broken node from dictating the master's allocation on every heartbeat.
  1171. const maxProbeBodyBytes = 1 << 20 // 1 MiB
  1172. func (s *NodeService) probe(ctx context.Context, n *model.Node, proxyURL string) (HeartbeatPatch, error) {
  1173. patch := HeartbeatPatch{LastHeartbeat: time.Now().Unix()}
  1174. addr, err := netsafe.NormalizeHost(n.Address)
  1175. if err != nil {
  1176. patch.LastError = err.Error()
  1177. return patch, err
  1178. }
  1179. scheme := n.Scheme
  1180. if scheme != "http" && scheme != "https" {
  1181. scheme = "https"
  1182. }
  1183. if n.Port <= 0 || n.Port > 65535 {
  1184. patch.LastError = "node port must be 1-65535"
  1185. return patch, errors.New(patch.LastError)
  1186. }
  1187. probeURL := &url.URL{
  1188. Scheme: scheme,
  1189. Host: net.JoinHostPort(addr, strconv.Itoa(n.Port)),
  1190. Path: normalizeBasePath(n.BasePath) + "panel/api/server/status",
  1191. }
  1192. req, err := http.NewRequestWithContext(
  1193. netsafe.ContextWithAllowPrivate(ctx, n.AllowPrivateAddress),
  1194. http.MethodGet, probeURL.String(), nil)
  1195. if err != nil {
  1196. patch.LastError = err.Error()
  1197. return patch, err
  1198. }
  1199. if n.ApiToken != "" {
  1200. token, derr := nodetoken.Decrypt(n.Id, n.ApiToken)
  1201. if derr != nil {
  1202. patch.LastError = derr.Error()
  1203. return patch, derr
  1204. }
  1205. req.Header.Set("Authorization", "Bearer "+token)
  1206. }
  1207. req.Header.Set("Accept", "application/json")
  1208. client, err := runtime.HTTPClientForNode(n, proxyURL)
  1209. if err != nil {
  1210. patch.LastError = err.Error()
  1211. return patch, err
  1212. }
  1213. start := time.Now()
  1214. resp, err := client.Do(req)
  1215. if err != nil {
  1216. patch.LastError = err.Error()
  1217. return patch, err
  1218. }
  1219. defer resp.Body.Close()
  1220. patch.LatencyMs = int(time.Since(start) / time.Millisecond)
  1221. if resp.StatusCode != http.StatusOK {
  1222. patch.LastError = fmt.Sprintf("HTTP %d from remote panel", resp.StatusCode)
  1223. return patch, errors.New(patch.LastError)
  1224. }
  1225. var envelope struct {
  1226. Success bool `json:"success"`
  1227. Msg string `json:"msg"`
  1228. Obj *struct {
  1229. CpuPct float64 `json:"cpu"`
  1230. Mem struct {
  1231. Current uint64 `json:"current"`
  1232. Total uint64 `json:"total"`
  1233. } `json:"mem"`
  1234. Xray struct {
  1235. Version string `json:"version"`
  1236. State string `json:"state"`
  1237. ErrorMsg string `json:"errorMsg"`
  1238. } `json:"xray"`
  1239. PanelVersion string `json:"panelVersion"`
  1240. PanelGuid string `json:"panelGuid"`
  1241. Uptime uint64 `json:"uptime"`
  1242. NetIO struct {
  1243. Up uint64 `json:"up"`
  1244. Down uint64 `json:"down"`
  1245. } `json:"netIO"`
  1246. } `json:"obj"`
  1247. }
  1248. if err := json.NewDecoder(io.LimitReader(resp.Body, maxProbeBodyBytes)).Decode(&envelope); err != nil {
  1249. patch.LastError = "decode response: " + err.Error()
  1250. return patch, err
  1251. }
  1252. if !envelope.Success || envelope.Obj == nil {
  1253. patch.LastError = "remote returned success=false: " + envelope.Msg
  1254. return patch, errors.New(patch.LastError)
  1255. }
  1256. o := envelope.Obj
  1257. patch.CpuPct = o.CpuPct
  1258. if o.Mem.Total > 0 {
  1259. patch.MemPct = float64(o.Mem.Current) * 100.0 / float64(o.Mem.Total)
  1260. }
  1261. patch.XrayVersion = o.Xray.Version
  1262. patch.XrayState = o.Xray.State
  1263. patch.XrayError = o.Xray.ErrorMsg
  1264. patch.PanelVersion = o.PanelVersion
  1265. patch.Guid = o.PanelGuid
  1266. patch.UptimeSecs = o.Uptime
  1267. patch.NetUp = o.NetIO.Up
  1268. patch.NetDown = o.NetIO.Down
  1269. return patch, nil
  1270. }
  1271. type ProbeResultUI struct {
  1272. Status string `json:"status" example:"online"`
  1273. LatencyMs int `json:"latencyMs" example:"42"`
  1274. XrayVersion string `json:"xrayVersion" example:"25.10.31"`
  1275. PanelVersion string `json:"panelVersion" example:"v3.x.x"`
  1276. CpuPct float64 `json:"cpuPct" example:"12.5"`
  1277. MemPct float64 `json:"memPct" example:"45.2"`
  1278. UptimeSecs uint64 `json:"uptimeSecs" example:"86400"`
  1279. Error string `json:"error"`
  1280. // XrayState/XrayError are populated on successful probes even when the node's
  1281. // Xray core is not healthy. The UI uses them for a distinct "panel ok, xray failed" indicator.
  1282. XrayState string `json:"xrayState"`
  1283. XrayError string `json:"xrayError"`
  1284. }
  1285. func (p HeartbeatPatch) ToUI(ok bool) ProbeResultUI {
  1286. r := ProbeResultUI{
  1287. LatencyMs: p.LatencyMs,
  1288. XrayVersion: p.XrayVersion,
  1289. PanelVersion: p.PanelVersion,
  1290. CpuPct: p.CpuPct,
  1291. MemPct: p.MemPct,
  1292. UptimeSecs: p.UptimeSecs,
  1293. Error: FriendlyProbeError(p.LastError),
  1294. XrayState: p.XrayState,
  1295. XrayError: p.XrayError,
  1296. }
  1297. if ok {
  1298. r.Status = "online"
  1299. } else {
  1300. r.Status = "offline"
  1301. }
  1302. return r
  1303. }
  1304. func FriendlyProbeError(msg string) string {
  1305. if strings.Contains(msg, "server gave HTTP response to HTTPS client") {
  1306. return "the server speaks HTTP, not HTTPS; set the node scheme to http"
  1307. }
  1308. return msg
  1309. }