1
0

node.go 28 KB

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