db.go 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676
  1. // Package database provides database initialization, migration, and management utilities
  2. // for the 3x-ui panel using GORM with SQLite or PostgreSQL.
  3. package database
  4. import (
  5. "bytes"
  6. "context"
  7. "encoding/json"
  8. "errors"
  9. "fmt"
  10. "io"
  11. "log"
  12. "math"
  13. "os"
  14. "os/exec"
  15. "path"
  16. "runtime"
  17. "slices"
  18. "strconv"
  19. "strings"
  20. "time"
  21. "github.com/mhsanaei/3x-ui/v3/internal/config"
  22. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  23. "github.com/mhsanaei/3x-ui/v3/internal/util/crypto"
  24. "github.com/mhsanaei/3x-ui/v3/internal/util/random"
  25. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  26. "gorm.io/driver/postgres"
  27. "gorm.io/driver/sqlite"
  28. "gorm.io/gorm"
  29. "gorm.io/gorm/logger"
  30. )
  31. var db *gorm.DB
  32. const (
  33. DialectSQLite = "sqlite"
  34. DialectPostgres = "postgres"
  35. )
  36. // IsPostgres reports whether the active connection is a PostgreSQL backend.
  37. func IsPostgres() bool {
  38. if db == nil {
  39. return config.GetDBKind() == "postgres"
  40. }
  41. return db.Name() == "postgres"
  42. }
  43. // Dialect returns the active GORM dialect name, or "" if the DB is not open.
  44. func Dialect() string {
  45. if db == nil {
  46. return ""
  47. }
  48. return db.Name()
  49. }
  50. const (
  51. defaultUsername = "admin"
  52. defaultPassword = "admin"
  53. )
  54. func initModels() error {
  55. models := []any{
  56. &model.User{},
  57. &model.Inbound{},
  58. &model.OutboundTraffics{},
  59. &model.Setting{},
  60. &model.InboundClientIps{},
  61. &xray.ClientTraffic{},
  62. &model.HistoryOfSeeders{},
  63. &model.Node{},
  64. &model.ApiToken{},
  65. &model.ClientRecord{},
  66. &model.ClientInbound{},
  67. &model.ClientExternalLink{},
  68. &model.ClientGroup{},
  69. &model.InboundFallback{},
  70. &model.Host{},
  71. &model.NodeClientTraffic{},
  72. &model.NodeClientIp{},
  73. &model.ClientGlobalTraffic{},
  74. &model.OutboundSubscription{},
  75. }
  76. for _, mdl := range models {
  77. if IsPostgres() && postgresModelSettled(mdl) {
  78. continue
  79. }
  80. if err := db.AutoMigrate(mdl); err != nil {
  81. if isIgnorableDuplicateColumnErr(err, mdl) {
  82. log.Printf("Ignoring duplicate column during auto migration for %T: %v", mdl, err)
  83. continue
  84. }
  85. log.Printf("Error auto migrating model: %v", err)
  86. return err
  87. }
  88. }
  89. if err := migrateHostVerifyPeerCertByNameColumn(); err != nil {
  90. return err
  91. }
  92. if err := normalizeApiTokenCreatedAtSeconds(); err != nil {
  93. return err
  94. }
  95. if err := dropLegacyForeignKeys(); err != nil {
  96. return err
  97. }
  98. if err := pruneOrphanedClientInbounds(); err != nil {
  99. return err
  100. }
  101. if err := pruneOrphanedHosts(); err != nil {
  102. return err
  103. }
  104. if err := normalizeInboundSubSortIndex(); err != nil {
  105. return err
  106. }
  107. if err := repairOverflowedTrafficCounters(); err != nil {
  108. return err
  109. }
  110. if err := dedupeInboundSettingsClients(); err != nil {
  111. return err
  112. }
  113. if err := migrateLegacySocksInboundsToMixed(); err != nil {
  114. return err
  115. }
  116. if IsPostgres() {
  117. if err := resyncPostgresSequences(db, models); err != nil {
  118. log.Printf("Error resyncing postgres sequences: %v", err)
  119. return err
  120. }
  121. }
  122. return nil
  123. }
  124. // postgresModelSettled skips AutoMigrate when table, columns, and indexes all exist:
  125. // its catalog-filtered column probe misdetects on some setups and re-ADDs columns forever (#5665).
  126. func postgresModelSettled(mdl any) bool {
  127. migrator := db.Migrator()
  128. if !migrator.HasTable(mdl) {
  129. return false
  130. }
  131. stmt := &gorm.Statement{DB: db}
  132. if err := stmt.Parse(mdl); err != nil || stmt.Schema == nil {
  133. return false
  134. }
  135. for _, dbName := range stmt.Schema.DBNames {
  136. if !migrator.HasColumn(mdl, dbName) {
  137. return false
  138. }
  139. }
  140. for _, idx := range stmt.Schema.ParseIndexes() {
  141. if !migrator.HasIndex(mdl, idx.Name) {
  142. return false
  143. }
  144. }
  145. return true
  146. }
  147. func dropLegacyForeignKeys() error {
  148. if !IsPostgres() {
  149. return nil
  150. }
  151. if err := db.Exec("ALTER TABLE client_traffics DROP CONSTRAINT IF EXISTS fk_inbounds_client_stats").Error; err != nil {
  152. log.Printf("Error dropping legacy foreign key fk_inbounds_client_stats: %v", err)
  153. return err
  154. }
  155. return nil
  156. }
  157. // migrateHostVerifyPeerCertByNameColumn converts hosts.verify_peer_cert_by_name
  158. // from its original boolean shape to the comma-separated string xray-core's
  159. // verifyPeerCertByName (vcn) actually expects. The legacy boolean was dead
  160. // (never emitted into links), so its value carries no meaning and is discarded.
  161. // Idempotent by construction (no HistoryOfSeeders row — writing one here would
  162. // flip the fresh-DB detection in runSeeders). Runs right after AutoMigrate,
  163. // before anything reads or writes Host rows (critical on Postgres, where the
  164. // column stays boolean-typed until the ALTER below).
  165. func migrateHostVerifyPeerCertByNameColumn() error {
  166. if !db.Migrator().HasColumn(&model.Host{}, "verify_peer_cert_by_name") {
  167. return nil
  168. }
  169. if IsPostgres() {
  170. // Only convert a still-boolean column; once it is text this is a no-op,
  171. // so a user-set name is never wiped on a later restart.
  172. var dataType string
  173. if err := db.Raw(
  174. `SELECT data_type FROM information_schema.columns WHERE table_name = 'hosts' AND column_name = 'verify_peer_cert_by_name'`,
  175. ).Scan(&dataType).Error; err != nil {
  176. return err
  177. }
  178. if dataType != "boolean" {
  179. return nil
  180. }
  181. if err := db.Exec(`ALTER TABLE hosts ALTER COLUMN verify_peer_cert_by_name DROP DEFAULT`).Error; err != nil {
  182. return err
  183. }
  184. return db.Exec(`ALTER TABLE hosts ALTER COLUMN verify_peer_cert_by_name TYPE text USING ''`).Error
  185. }
  186. // SQLite keeps the original numeric-affinity column; blank any legacy
  187. // integer/null value so it doesn't read back as "0"/"1". After conversion
  188. // every value is text, so re-running touches nothing.
  189. return db.Exec(`UPDATE hosts SET verify_peer_cert_by_name = '' WHERE verify_peer_cert_by_name IS NULL OR typeof(verify_peer_cert_by_name) <> 'text'`).Error
  190. }
  191. // seedHostsFromExternalProxy is a one-time, self-gated migration that creates a
  192. // Host row for every legacy externalProxy entry on every inbound. Additive: the
  193. // externalProxy arrays are left intact in StreamSettings.
  194. func seedHostsFromExternalProxy() error {
  195. var history []string
  196. if err := db.Model(&model.HistoryOfSeeders{}).Pluck("seeder_name", &history).Error; err != nil {
  197. return err
  198. }
  199. if slices.Contains(history, "HostsFromExternalProxy") {
  200. return nil
  201. }
  202. var inbounds []model.Inbound
  203. if err := db.Find(&inbounds).Error; err != nil {
  204. return err
  205. }
  206. return db.Transaction(func(tx *gorm.DB) error {
  207. for _, inbound := range inbounds {
  208. if _, err := CreateHostsFromExternalProxy(tx, inbound.Id, inbound.StreamSettings); err != nil {
  209. return err
  210. }
  211. }
  212. return tx.Create(&model.HistoryOfSeeders{SeederName: "HostsFromExternalProxy"}).Error
  213. })
  214. }
  215. // seedWireguardPeersToClients is a one-time, self-gated migration that converts
  216. // legacy single-config WireGuard inbounds into the multi-client model: each
  217. // settings.peers[] entry becomes a managed client in the clients table attached
  218. // to the inbound, and the inbound settings are rewritten so peers becomes a
  219. // clients[] array (GetXrayConfig re-projects clients back to peers for xray).
  220. // Idempotent: gated on the history row and skipped per-inbound once it already
  221. // has client links.
  222. func seedWireguardPeersToClients() error {
  223. var history []string
  224. if err := db.Model(&model.HistoryOfSeeders{}).Pluck("seeder_name", &history).Error; err != nil {
  225. return err
  226. }
  227. if slices.Contains(history, "WireguardPeersToClients") {
  228. return nil
  229. }
  230. var inbounds []model.Inbound
  231. if err := db.Where("protocol = ?", string(model.WireGuard)).Find(&inbounds).Error; err != nil {
  232. return err
  233. }
  234. return db.Transaction(func(tx *gorm.DB) error {
  235. usedEmails := map[string]struct{}{}
  236. var existingEmails []string
  237. if err := tx.Model(&model.ClientRecord{}).Pluck("email", &existingEmails).Error; err != nil {
  238. return err
  239. }
  240. for _, e := range existingEmails {
  241. usedEmails[e] = struct{}{}
  242. }
  243. for _, inbound := range inbounds {
  244. if strings.TrimSpace(inbound.Settings) == "" {
  245. continue
  246. }
  247. var settings map[string]any
  248. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  249. log.Printf("WireguardPeersToClients: skip inbound %d (invalid settings json): %v", inbound.Id, err)
  250. continue
  251. }
  252. peers, ok := settings["peers"].([]any)
  253. if !ok || len(peers) == 0 {
  254. continue
  255. }
  256. var linkCount int64
  257. if err := tx.Model(&model.ClientInbound{}).Where("inbound_id = ?", inbound.Id).Count(&linkCount).Error; err != nil {
  258. return err
  259. }
  260. if linkCount > 0 {
  261. continue
  262. }
  263. clientObjs := make([]any, 0, len(peers))
  264. for i, raw := range peers {
  265. obj, ok := raw.(map[string]any)
  266. if !ok {
  267. continue
  268. }
  269. email := wireguardPeerEmail(inbound.Remark, obj, i, usedEmails)
  270. usedEmails[email] = struct{}{}
  271. obj["email"] = email
  272. if sub, _ := obj["subId"].(string); strings.TrimSpace(sub) == "" {
  273. obj["subId"] = random.NumLower(16)
  274. }
  275. if _, ok := obj["enable"]; !ok {
  276. obj["enable"] = true
  277. }
  278. blob, err := json.Marshal(obj)
  279. if err != nil {
  280. continue
  281. }
  282. var c model.Client
  283. if err := json.Unmarshal(blob, &c); err != nil {
  284. log.Printf("WireguardPeersToClients: skip peer in inbound %d: %v", inbound.Id, err)
  285. continue
  286. }
  287. c.Email = email
  288. incoming := c.ToRecord()
  289. var row model.ClientRecord
  290. err = tx.Where("email = ?", email).First(&row).Error
  291. if errors.Is(err, gorm.ErrRecordNotFound) {
  292. if err := tx.Create(incoming).Error; err != nil {
  293. return err
  294. }
  295. row = *incoming
  296. } else if err != nil {
  297. return err
  298. } else {
  299. model.MergeClientRecord(&row, incoming)
  300. if err := tx.Save(&row).Error; err != nil {
  301. return err
  302. }
  303. }
  304. link := model.ClientInbound{ClientId: row.Id, InboundId: inbound.Id}
  305. if err := tx.Where("client_id = ? AND inbound_id = ?", row.Id, inbound.Id).
  306. FirstOrCreate(&link).Error; err != nil {
  307. return err
  308. }
  309. clientObjs = append(clientObjs, obj)
  310. }
  311. delete(settings, "peers")
  312. settings["clients"] = clientObjs
  313. newSettings, err := json.Marshal(settings)
  314. if err != nil {
  315. return err
  316. }
  317. if err := tx.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
  318. Update("settings", string(newSettings)).Error; err != nil {
  319. return err
  320. }
  321. }
  322. return tx.Create(&model.HistoryOfSeeders{SeederName: "WireguardPeersToClients"}).Error
  323. })
  324. }
  325. // wireguardPeerEmail derives a stable, unique client email for a migrated peer
  326. // from the inbound remark plus the peer's comment (or its 1-based index).
  327. func wireguardPeerEmail(remark string, peer map[string]any, index int, used map[string]struct{}) string {
  328. base := strings.TrimSpace(remark)
  329. if base == "" {
  330. base = "wg"
  331. }
  332. suffix := strconv.Itoa(index + 1)
  333. if c, ok := peer["comment"].(string); ok && strings.TrimSpace(c) != "" {
  334. suffix = strings.TrimSpace(c)
  335. }
  336. email := strings.ReplaceAll(base+"-"+suffix, " ", "-")
  337. candidate := email
  338. for n := 2; ; n++ {
  339. if _, taken := used[candidate]; !taken {
  340. return candidate
  341. }
  342. candidate = email + "-" + strconv.Itoa(n)
  343. }
  344. }
  345. // seedMtprotoSecretsToClients converts each legacy single-secret mtproto inbound
  346. // into a one-client inbound so MTProto joins the shared multi-client model: the
  347. // inbound-level secret becomes the first client's FakeTLS secret, and a
  348. // ClientRecord + client_inbounds link are created so per-client traffic, limits,
  349. // and share links work exactly like every other protocol. One-time, self-gated
  350. // on the "MtprotoSecretsToClients" seeder row. Mirrors seedWireguardPeersToClients.
  351. func seedMtprotoSecretsToClients() error {
  352. var history []string
  353. if err := db.Model(&model.HistoryOfSeeders{}).Pluck("seeder_name", &history).Error; err != nil {
  354. return err
  355. }
  356. if slices.Contains(history, "MtprotoSecretsToClients") {
  357. return nil
  358. }
  359. var inbounds []model.Inbound
  360. if err := db.Where("protocol = ?", string(model.MTProto)).Find(&inbounds).Error; err != nil {
  361. return err
  362. }
  363. return db.Transaction(func(tx *gorm.DB) error {
  364. usedEmails := map[string]struct{}{}
  365. var existingEmails []string
  366. if err := tx.Model(&model.ClientRecord{}).Pluck("email", &existingEmails).Error; err != nil {
  367. return err
  368. }
  369. for _, e := range existingEmails {
  370. usedEmails[e] = struct{}{}
  371. }
  372. for _, inbound := range inbounds {
  373. if strings.TrimSpace(inbound.Settings) == "" {
  374. continue
  375. }
  376. var settings map[string]any
  377. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  378. log.Printf("MtprotoSecretsToClients: skip inbound %d (invalid settings json): %v", inbound.Id, err)
  379. continue
  380. }
  381. if clients, ok := settings["clients"].([]any); ok && len(clients) > 0 {
  382. continue
  383. }
  384. var linkCount int64
  385. if err := tx.Model(&model.ClientInbound{}).Where("inbound_id = ?", inbound.Id).Count(&linkCount).Error; err != nil {
  386. return err
  387. }
  388. if linkCount > 0 {
  389. continue
  390. }
  391. secret, _ := settings["secret"].(string)
  392. secret = strings.TrimSpace(secret)
  393. if secret == "" {
  394. domain, _ := settings["fakeTlsDomain"].(string)
  395. secret = model.GenerateFakeTLSSecret(strings.TrimSpace(domain))
  396. }
  397. email := mtprotoInboundClientEmail(inbound.Remark, usedEmails)
  398. usedEmails[email] = struct{}{}
  399. obj := map[string]any{
  400. "email": email,
  401. "secret": secret,
  402. "enable": true,
  403. "subId": random.NumLower(16),
  404. }
  405. c := model.Client{Email: email, Secret: secret, Enable: true, SubID: obj["subId"].(string)}
  406. incoming := c.ToRecord()
  407. var row model.ClientRecord
  408. err := tx.Where("email = ?", email).First(&row).Error
  409. if errors.Is(err, gorm.ErrRecordNotFound) {
  410. if err := tx.Create(incoming).Error; err != nil {
  411. return err
  412. }
  413. row = *incoming
  414. } else if err != nil {
  415. return err
  416. } else {
  417. model.MergeClientRecord(&row, incoming)
  418. if err := tx.Save(&row).Error; err != nil {
  419. return err
  420. }
  421. }
  422. link := model.ClientInbound{ClientId: row.Id, InboundId: inbound.Id}
  423. if err := tx.Where("client_id = ? AND inbound_id = ?", row.Id, inbound.Id).
  424. FirstOrCreate(&link).Error; err != nil {
  425. return err
  426. }
  427. delete(settings, "secret")
  428. settings["clients"] = []any{obj}
  429. newSettings, err := json.Marshal(settings)
  430. if err != nil {
  431. return err
  432. }
  433. if err := tx.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
  434. Update("settings", string(newSettings)).Error; err != nil {
  435. return err
  436. }
  437. }
  438. return tx.Create(&model.HistoryOfSeeders{SeederName: "MtprotoSecretsToClients"}).Error
  439. })
  440. }
  441. // mtprotoInboundClientEmail derives a stable, unique client email for a migrated
  442. // mtproto inbound from its remark.
  443. func mtprotoInboundClientEmail(remark string, used map[string]struct{}) string {
  444. base := strings.TrimSpace(remark)
  445. if base == "" {
  446. base = "mtproto"
  447. }
  448. email := strings.ReplaceAll(base, " ", "-")
  449. candidate := email
  450. for n := 2; ; n++ {
  451. if _, taken := used[candidate]; !taken {
  452. return candidate
  453. }
  454. candidate = email + "-" + strconv.Itoa(n)
  455. }
  456. }
  457. // CreateHostsFromExternalProxy parses a legacy streamSettings.externalProxy array
  458. // and inserts one Host row per entry on tx, returning the number of rows created.
  459. // It is the shared core of both the one-time seedHostsFromExternalProxy startup
  460. // migration and the inbound-import path: an inbound exported from a build that
  461. // predated the hosts table carries its external proxies inline in
  462. // streamSettings.externalProxy, and the startup migration is gated off after its
  463. // first run, so a freshly imported inbound must be converted here instead. Blank
  464. // or malformed streamSettings, or one without externalProxy entries, is a no-op.
  465. func CreateHostsFromExternalProxy(tx *gorm.DB, inboundId int, streamSettings string) (int, error) {
  466. if strings.TrimSpace(streamSettings) == "" {
  467. return 0, nil
  468. }
  469. var stream map[string]any
  470. if err := json.Unmarshal([]byte(streamSettings), &stream); err != nil {
  471. return 0, nil
  472. }
  473. eps, ok := stream["externalProxy"].([]any)
  474. if !ok || len(eps) == 0 {
  475. return 0, nil
  476. }
  477. created := 0
  478. for i, raw := range eps {
  479. ep, ok := raw.(map[string]any)
  480. if !ok {
  481. continue
  482. }
  483. if err := tx.Create(externalProxyEntryToHost(inboundId, i, ep)).Error; err != nil {
  484. return created, err
  485. }
  486. created++
  487. }
  488. return created, nil
  489. }
  490. // externalProxyEntryToHost maps one legacy externalProxy entry onto a Host.
  491. // forceTls (same|tls|none) maps straight to Security; an unknown value falls back
  492. // to "same" (inherit). An empty remark gets a stable generated label so the row
  493. // stays valid/editable, and the remark is capped at the model's 256-char limit.
  494. func externalProxyEntryToHost(inboundId, index int, ep map[string]any) *model.Host {
  495. security, _ := ep["forceTls"].(string)
  496. switch security {
  497. case "same", "tls", "none":
  498. default:
  499. security = "same"
  500. }
  501. dest, _ := ep["dest"].(string)
  502. port := 0
  503. if p, ok := ep["port"].(float64); ok {
  504. port = int(p)
  505. }
  506. remark, _ := ep["remark"].(string)
  507. if strings.TrimSpace(remark) == "" {
  508. remark = "imported " + strconv.Itoa(index+1)
  509. }
  510. if len(remark) > 256 {
  511. remark = remark[:256]
  512. }
  513. sni, _ := ep["sni"].(string)
  514. fingerprint, _ := ep["fingerprint"].(string)
  515. ech, _ := ep["echConfigList"].(string)
  516. return &model.Host{
  517. InboundId: inboundId,
  518. SortOrder: index,
  519. Remark: remark,
  520. Address: dest,
  521. Port: port,
  522. Security: security,
  523. Sni: sni,
  524. Fingerprint: fingerprint,
  525. Alpn: anyToNonEmptyStrings(ep["alpn"]),
  526. PinnedPeerCertSha256: anyToNonEmptyStrings(ep["pinnedPeerCertSha256"]),
  527. EchConfigList: ech,
  528. }
  529. }
  530. func anyToNonEmptyStrings(v any) []string {
  531. switch t := v.(type) {
  532. case []any:
  533. out := make([]string, 0, len(t))
  534. for _, e := range t {
  535. if s, ok := e.(string); ok && s != "" {
  536. out = append(out, s)
  537. }
  538. }
  539. return out
  540. case []string:
  541. out := make([]string, 0, len(t))
  542. for _, s := range t {
  543. if s != "" {
  544. out = append(out, s)
  545. }
  546. }
  547. return out
  548. default:
  549. return nil
  550. }
  551. }
  552. func pruneOrphanedHosts() error {
  553. res := db.Exec("DELETE FROM hosts WHERE inbound_id NOT IN (SELECT id FROM inbounds)")
  554. if res.Error != nil {
  555. log.Printf("Error pruning orphaned hosts rows: %v", res.Error)
  556. return res.Error
  557. }
  558. if res.RowsAffected > 0 {
  559. log.Printf("Pruned %d orphaned hosts row(s)", res.RowsAffected)
  560. }
  561. return nil
  562. }
  563. func pruneOrphanedClientInbounds() error {
  564. res := db.Exec("DELETE FROM client_inbounds WHERE inbound_id NOT IN (SELECT id FROM inbounds)")
  565. if res.Error != nil {
  566. log.Printf("Error pruning orphaned client_inbounds rows: %v", res.Error)
  567. return res.Error
  568. }
  569. if res.RowsAffected > 0 {
  570. log.Printf("Pruned %d orphaned client_inbounds row(s)", res.RowsAffected)
  571. }
  572. return nil
  573. }
  574. // migrateLegacySocksInboundsToMixed renames legacy socks inbounds to mixed.
  575. // The protocol enum dropped socks in favor of mixed (identical settings shape,
  576. // same behavior plus HTTP on the shared port), so rows predating the rename
  577. // fail model validation — most visibly when pushed to a node, where one legacy
  578. // inbound stalled the entire node's config and traffic sync (#5685).
  579. func migrateLegacySocksInboundsToMixed() error {
  580. res := db.Exec("UPDATE inbounds SET protocol = 'mixed' WHERE protocol = 'socks'")
  581. if res.Error != nil {
  582. log.Printf("Error migrating legacy socks inbounds to mixed: %v", res.Error)
  583. return res.Error
  584. }
  585. if res.RowsAffected > 0 {
  586. log.Printf("Migrated %d legacy socks inbound(s) to mixed", res.RowsAffected)
  587. }
  588. return nil
  589. }
  590. // normalizeInboundSubSortIndex lifts sub_sort_index values below the 1-based
  591. // minimum (rows written by builds that defaulted the column to 0, or by nodes
  592. // predating the field) so they cannot sort ahead of explicitly ranked inbounds.
  593. func normalizeInboundSubSortIndex() error {
  594. res := db.Exec("UPDATE inbounds SET sub_sort_index = 1 WHERE sub_sort_index < 1")
  595. if res.Error != nil {
  596. log.Printf("Error normalizing inbound sub_sort_index: %v", res.Error)
  597. return res.Error
  598. }
  599. if res.RowsAffected > 0 {
  600. log.Printf("Normalized sub_sort_index on %d inbound(s)", res.RowsAffected)
  601. }
  602. return nil
  603. }
  604. // repairOverflowedTrafficCounters heals traffic counters that historic
  605. // compounding bugs pushed past int64: on SQLite an overflowing INTEGER is
  606. // silently promoted to REAL, after which the column no longer scans into the
  607. // Go int64 field and every reader of the table fails (#5762). REAL cells are
  608. // cast back to INTEGER (SQLite caps the cast at math.MaxInt64), then values
  609. // are clamped into [0, TrafficMax] on both backends so the next delta cannot
  610. // overflow again.
  611. func repairOverflowedTrafficCounters() error {
  612. targets := []struct {
  613. table string
  614. columns []string
  615. }{
  616. {"client_traffics", []string{"up", "down"}},
  617. {"inbounds", []string{"up", "down"}},
  618. {"outbound_traffics", []string{"up", "down", "total"}},
  619. {"node_client_traffics", []string{"up", "down"}},
  620. }
  621. for _, target := range targets {
  622. for _, col := range target.columns {
  623. statements := []string{
  624. fmt.Sprintf("UPDATE %s SET %s = %d WHERE %s > %d", target.table, col, TrafficMax, col, TrafficMax),
  625. fmt.Sprintf("UPDATE %s SET %s = 0 WHERE %s < 0", target.table, col, col),
  626. }
  627. if !IsPostgres() {
  628. statements = append([]string{
  629. fmt.Sprintf("UPDATE %s SET %s = CAST(%s AS INTEGER) WHERE typeof(%s) = 'real'", target.table, col, col, col),
  630. }, statements...)
  631. }
  632. var repaired int64
  633. for _, statement := range statements {
  634. res := db.Exec(statement)
  635. if res.Error != nil {
  636. log.Printf("Error repairing %s.%s: %v", target.table, col, res.Error)
  637. return res.Error
  638. }
  639. repaired += res.RowsAffected
  640. }
  641. if repaired > 0 {
  642. log.Printf("Repaired %d overflowed %s.%s value(s)", repaired, target.table, col)
  643. }
  644. }
  645. }
  646. return nil
  647. }
  648. // dedupeInboundSettingsClients collapses duplicate same-email entries inside
  649. // every inbound's settings.clients array, keeping the first occurrence.
  650. // Retried or raced multi-node client adds on older builds appended the same
  651. // client several times (#5770), which the client lists then rendered as
  652. // phantom duplicates. Runs on every start (idempotent, writes only changed
  653. // rows) because a restored backup or a not-yet-upgraded node's snapshot can
  654. // reintroduce duplicates.
  655. func dedupeInboundSettingsClients() error {
  656. var inbounds []model.Inbound
  657. if err := db.Find(&inbounds).Error; err != nil {
  658. return err
  659. }
  660. repaired := int64(0)
  661. for _, inbound := range inbounds {
  662. if strings.TrimSpace(inbound.Settings) == "" {
  663. continue
  664. }
  665. var settings map[string]any
  666. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  667. continue
  668. }
  669. clients, _ := settings["clients"].([]any)
  670. if len(clients) < 2 {
  671. continue
  672. }
  673. seen := make(map[string]struct{}, len(clients))
  674. kept := make([]any, 0, len(clients))
  675. for _, c := range clients {
  676. if cm, ok := c.(map[string]any); ok {
  677. if email, _ := cm["email"].(string); email != "" {
  678. key := strings.ToLower(email)
  679. if _, dup := seen[key]; dup {
  680. continue
  681. }
  682. seen[key] = struct{}{}
  683. }
  684. }
  685. kept = append(kept, c)
  686. }
  687. if len(kept) == len(clients) {
  688. continue
  689. }
  690. settings["clients"] = kept
  691. newSettings, err := json.MarshalIndent(settings, "", " ")
  692. if err != nil {
  693. log.Printf("dedupeInboundSettingsClients: skip inbound %d (marshal failed): %v", inbound.Id, err)
  694. continue
  695. }
  696. if err := db.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
  697. Update("settings", string(newSettings)).Error; err != nil {
  698. return err
  699. }
  700. repaired++
  701. }
  702. if repaired > 0 {
  703. log.Printf("Removed duplicate client entries from %d inbound(s)", repaired)
  704. }
  705. return nil
  706. }
  707. func isIgnorableDuplicateColumnErr(err error, mdl any) bool {
  708. if err == nil {
  709. return false
  710. }
  711. errMsg := strings.ToLower(err.Error())
  712. // SQLite: "duplicate column name: foo"
  713. // Postgres: `pq: column "foo" of relation "bar" already exists` / `sqlstate 42701`
  714. const sqlitePrefix = "duplicate column name:"
  715. if _, after, ok := strings.Cut(errMsg, sqlitePrefix); ok {
  716. col := strings.TrimSpace(after)
  717. col = strings.Trim(col, "`\"[]")
  718. return col != "" && db != nil && db.Migrator().HasColumn(mdl, col)
  719. }
  720. if strings.Contains(errMsg, "already exists") && strings.Contains(errMsg, "column ") {
  721. // Best effort: extract the column name between the first pair of double quotes.
  722. if _, after, ok := strings.Cut(errMsg, "column \""); ok {
  723. rest := after
  724. if e := strings.Index(rest, "\""); e > 0 {
  725. col := rest[:e]
  726. return col != "" && db != nil && db.Migrator().HasColumn(mdl, col)
  727. }
  728. }
  729. }
  730. return false
  731. }
  732. // initUser creates a default admin user if the users table is empty.
  733. func initUser() error {
  734. empty, err := isTableEmpty("users")
  735. if err != nil {
  736. log.Printf("Error checking if users table is empty: %v", err)
  737. return err
  738. }
  739. if empty {
  740. hashedPassword, err := crypto.HashPasswordAsBcrypt(defaultPassword)
  741. if err != nil {
  742. log.Printf("Error hashing default password: %v", err)
  743. return err
  744. }
  745. user := &model.User{
  746. Username: defaultUsername,
  747. Password: hashedPassword,
  748. }
  749. return db.Create(user).Error
  750. }
  751. return nil
  752. }
  753. // runSeeders migrates user passwords to bcrypt and records seeder execution to prevent re-running.
  754. func runSeeders(isUsersEmpty bool) error {
  755. empty, err := isTableEmpty("history_of_seeders")
  756. if err != nil {
  757. log.Printf("Error checking if users table is empty: %v", err)
  758. return err
  759. }
  760. if empty && isUsersEmpty {
  761. seeders := []string{"UserPasswordHash", "ClientsTable", "InboundClientsArrayFix", "InboundClientTgIdFix", "InboundClientSubIdFix", "FreedomFinalRulesReverseFix", "ApiTokensHash", "LegacyProxySettingsCleanup", "WireguardPeersToClients", "MtprotoSecretsToClients"}
  762. for _, name := range seeders {
  763. if err := db.Create(&model.HistoryOfSeeders{SeederName: name}).Error; err != nil {
  764. return err
  765. }
  766. }
  767. return seedApiTokens()
  768. }
  769. var seedersHistory []string
  770. if err := db.Model(&model.HistoryOfSeeders{}).Pluck("seeder_name", &seedersHistory).Error; err != nil {
  771. log.Printf("Error fetching seeder history: %v", err)
  772. return err
  773. }
  774. if !slices.Contains(seedersHistory, "UserPasswordHash") && !isUsersEmpty {
  775. var users []model.User
  776. if err := db.Find(&users).Error; err != nil {
  777. log.Printf("Error fetching users for password migration: %v", err)
  778. return err
  779. }
  780. for _, user := range users {
  781. if crypto.IsHashed(user.Password) {
  782. continue
  783. }
  784. hashedPassword, err := crypto.HashPasswordAsBcrypt(user.Password)
  785. if err != nil {
  786. log.Printf("Error hashing password for user '%s': %v", user.Username, err)
  787. return err
  788. }
  789. if err := db.Model(&user).Update("password", hashedPassword).Error; err != nil {
  790. log.Printf("Error updating password for user '%s': %v", user.Username, err)
  791. return err
  792. }
  793. }
  794. hashSeeder := &model.HistoryOfSeeders{
  795. SeederName: "UserPasswordHash",
  796. }
  797. if err := db.Create(hashSeeder).Error; err != nil {
  798. return err
  799. }
  800. }
  801. if !slices.Contains(seedersHistory, "ApiTokensTable") {
  802. if err := seedApiTokens(); err != nil {
  803. return err
  804. }
  805. }
  806. if !slices.Contains(seedersHistory, "ApiTokensHash") {
  807. if err := hashExistingApiTokens(); err != nil {
  808. return err
  809. }
  810. }
  811. if !slices.Contains(seedersHistory, "ClientsTable") {
  812. if err := seedClientsFromInboundJSON(); err != nil {
  813. return err
  814. }
  815. }
  816. if !slices.Contains(seedersHistory, "InboundClientsArrayFix") {
  817. if err := normalizeInboundClientsArray(); err != nil {
  818. return err
  819. }
  820. }
  821. if !slices.Contains(seedersHistory, "InboundClientTgIdFix") {
  822. if err := normalizeInboundClientTgId(); err != nil {
  823. return err
  824. }
  825. }
  826. if !slices.Contains(seedersHistory, "InboundClientSubIdFix") {
  827. if err := normalizeInboundClientSubId(); err != nil {
  828. return err
  829. }
  830. }
  831. if !slices.Contains(seedersHistory, "FreedomFinalRulesReverseFix") {
  832. if err := normalizeFreedomFinalRules(); err != nil {
  833. return err
  834. }
  835. }
  836. if !slices.Contains(seedersHistory, "LegacyProxySettingsCleanup") {
  837. if err := clearLegacyProxySettings(); err != nil {
  838. return err
  839. }
  840. }
  841. // Self-gated on the "HostsFromExternalProxy" row, so it is safe to call
  842. // unconditionally here.
  843. if err := seedHostsFromExternalProxy(); err != nil {
  844. return err
  845. }
  846. // Self-gated on the "ResetIpLimitNoFail2ban" row.
  847. if err := resetIpLimitsWithoutFail2ban(); err != nil {
  848. return err
  849. }
  850. // Self-gated on the "WireguardPeersToClients" row.
  851. if err := seedWireguardPeersToClients(); err != nil {
  852. return err
  853. }
  854. // Self-gated on the "MtprotoSecretsToClients" row.
  855. if err := seedMtprotoSecretsToClients(); err != nil {
  856. return err
  857. }
  858. // Idempotent, not seeder-gated: bad values can re-enter via a restored
  859. // backup, so re-check on every start.
  860. return normalizeSettingPaths()
  861. }
  862. // resetIpLimitsWithoutFail2ban zeroes every client's IP limit on hosts where
  863. // fail2ban can't enforce it (not installed, or the integration disabled). The
  864. // limit silently does nothing there yet kept logging a repeated warning, so a
  865. // stale value is just misleading — the panel also disables the field on these
  866. // hosts. One-time, self-gated on the seeder row.
  867. func resetIpLimitsWithoutFail2ban() error {
  868. var history []string
  869. if err := db.Model(&model.HistoryOfSeeders{}).Pluck("seeder_name", &history).Error; err != nil {
  870. return err
  871. }
  872. if slices.Contains(history, "ResetIpLimitNoFail2ban") {
  873. return nil
  874. }
  875. if fail2banCanEnforce() {
  876. return db.Create(&model.HistoryOfSeeders{SeederName: "ResetIpLimitNoFail2ban"}).Error
  877. }
  878. var inbounds []model.Inbound
  879. if err := db.Find(&inbounds).Error; err != nil {
  880. return err
  881. }
  882. return db.Transaction(func(tx *gorm.DB) error {
  883. for _, inbound := range inbounds {
  884. if strings.TrimSpace(inbound.Settings) == "" {
  885. continue
  886. }
  887. var settings map[string]any
  888. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  889. log.Printf("ResetIpLimitNoFail2ban: skip inbound %d (invalid settings json): %v", inbound.Id, err)
  890. continue
  891. }
  892. clients, ok := settings["clients"].([]any)
  893. if !ok {
  894. continue
  895. }
  896. mutated := false
  897. for i, raw := range clients {
  898. obj, ok := raw.(map[string]any)
  899. if !ok {
  900. continue
  901. }
  902. v, present := obj["limitIp"]
  903. if !present {
  904. continue
  905. }
  906. if n, isNum := v.(float64); isNum && n == 0 {
  907. continue
  908. }
  909. obj["limitIp"] = 0
  910. clients[i] = obj
  911. mutated = true
  912. }
  913. if !mutated {
  914. continue
  915. }
  916. settings["clients"] = clients
  917. newSettings, err := json.MarshalIndent(settings, "", " ")
  918. if err != nil {
  919. log.Printf("ResetIpLimitNoFail2ban: skip inbound %d (marshal failed): %v", inbound.Id, err)
  920. continue
  921. }
  922. if err := tx.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
  923. Update("settings", string(newSettings)).Error; err != nil {
  924. return err
  925. }
  926. }
  927. if err := tx.Model(&model.ClientRecord{}).Where("limit_ip <> ?", 0).
  928. Update("limit_ip", 0).Error; err != nil {
  929. return err
  930. }
  931. return tx.Create(&model.HistoryOfSeeders{SeederName: "ResetIpLimitNoFail2ban"}).Error
  932. })
  933. }
  934. // fail2banCanEnforce reports whether per-client IP limits can actually be
  935. // enforced on this host: the integration must be enabled (XUI_ENABLE_FAIL2BAN)
  936. // and fail2ban-client must be present. Mirrors the service-layer check, kept
  937. // local to avoid an import cycle.
  938. func fail2banCanEnforce() bool {
  939. if v, ok := os.LookupEnv("XUI_ENABLE_FAIL2BAN"); ok && v != "true" {
  940. return false
  941. }
  942. if runtime.GOOS == "windows" {
  943. return false
  944. }
  945. return exec.CommandContext(context.Background(), "fail2ban-client", "-h").Run() == nil
  946. }
  947. // clearLegacyProxySettings drops the deprecated panelProxy/tgBotProxy rows so a
  948. // stale tgBotProxy no longer masks the panelOutbound egress fallback.
  949. func clearLegacyProxySettings() error {
  950. return db.Transaction(func(tx *gorm.DB) error {
  951. if err := tx.Where("key IN ?", []string{"panelProxy", "tgBotProxy"}).
  952. Delete(&model.Setting{}).Error; err != nil {
  953. return err
  954. }
  955. return tx.Create(&model.HistoryOfSeeders{SeederName: "LegacyProxySettingsCleanup"}).Error
  956. })
  957. }
  958. // normalizeSettingPaths repairs URI-path settings persisted before the
  959. // leading/trailing-slash rules existed (or restored from an old backup),
  960. // mirroring entity.AllSetting.CheckValid. CheckValid self-heals these on save,
  961. // but the frontend rejects the whole Settings form on the bad stored value
  962. // before a save can ever reach it (#5726), so the stored rows themselves must
  963. // be fixed. Idempotent; runs on every start.
  964. func normalizeSettingPaths() error {
  965. pathKeys := []string{"webBasePath", "subPath", "subJsonPath", "subClashPath"}
  966. var rows []model.Setting
  967. if err := db.Where("key IN ?", pathKeys).Find(&rows).Error; err != nil {
  968. return err
  969. }
  970. for _, row := range rows {
  971. fixed := row.Value
  972. if !strings.HasPrefix(fixed, "/") {
  973. fixed = "/" + fixed
  974. }
  975. if !strings.HasSuffix(fixed, "/") {
  976. fixed += "/"
  977. }
  978. if fixed == row.Value {
  979. continue
  980. }
  981. if err := db.Model(&model.Setting{}).Where("id = ?", row.Id).
  982. Update("value", fixed).Error; err != nil {
  983. return err
  984. }
  985. }
  986. return nil
  987. }
  988. func normalizeInboundClientTgId() error {
  989. var inbounds []model.Inbound
  990. if err := db.Find(&inbounds).Error; err != nil {
  991. return err
  992. }
  993. return db.Transaction(func(tx *gorm.DB) error {
  994. for _, inbound := range inbounds {
  995. if strings.TrimSpace(inbound.Settings) == "" {
  996. continue
  997. }
  998. var settings map[string]any
  999. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1000. log.Printf("InboundClientTgIdFix: skip inbound %d (invalid settings json): %v", inbound.Id, err)
  1001. continue
  1002. }
  1003. clients, ok := settings["clients"].([]any)
  1004. if !ok {
  1005. continue
  1006. }
  1007. mutated := false
  1008. for i, raw := range clients {
  1009. obj, ok := raw.(map[string]any)
  1010. if !ok {
  1011. continue
  1012. }
  1013. tgRaw, present := obj["tgId"]
  1014. if !present {
  1015. continue
  1016. }
  1017. v, isFloat := tgRaw.(float64)
  1018. if isFloat && !math.IsNaN(v) && !math.IsInf(v, 0) && v == math.Trunc(v) {
  1019. continue
  1020. }
  1021. obj["tgId"] = int64(0)
  1022. clients[i] = obj
  1023. mutated = true
  1024. }
  1025. if !mutated {
  1026. continue
  1027. }
  1028. settings["clients"] = clients
  1029. newSettings, err := json.MarshalIndent(settings, "", " ")
  1030. if err != nil {
  1031. log.Printf("InboundClientTgIdFix: skip inbound %d (marshal failed): %v", inbound.Id, err)
  1032. continue
  1033. }
  1034. if err := tx.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
  1035. Update("settings", string(newSettings)).Error; err != nil {
  1036. return err
  1037. }
  1038. }
  1039. return tx.Create(&model.HistoryOfSeeders{SeederName: "InboundClientTgIdFix"}).Error
  1040. })
  1041. }
  1042. func normalizeInboundClientSubId() error {
  1043. var inbounds []model.Inbound
  1044. if err := db.Find(&inbounds).Error; err != nil {
  1045. return err
  1046. }
  1047. return db.Transaction(func(tx *gorm.DB) error {
  1048. for _, inbound := range inbounds {
  1049. if strings.TrimSpace(inbound.Settings) == "" {
  1050. continue
  1051. }
  1052. var settings map[string]any
  1053. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1054. log.Printf("InboundClientSubIdFix: skip inbound %d (invalid settings json): %v", inbound.Id, err)
  1055. continue
  1056. }
  1057. clients, ok := settings["clients"].([]any)
  1058. if !ok {
  1059. continue
  1060. }
  1061. mutated := false
  1062. for i, raw := range clients {
  1063. obj, ok := raw.(map[string]any)
  1064. if !ok {
  1065. continue
  1066. }
  1067. existing, _ := obj["subId"].(string)
  1068. if strings.TrimSpace(existing) != "" {
  1069. continue
  1070. }
  1071. obj["subId"] = random.NumLower(16)
  1072. clients[i] = obj
  1073. mutated = true
  1074. }
  1075. if !mutated {
  1076. continue
  1077. }
  1078. settings["clients"] = clients
  1079. newSettings, err := json.MarshalIndent(settings, "", " ")
  1080. if err != nil {
  1081. log.Printf("InboundClientSubIdFix: skip inbound %d (marshal failed): %v", inbound.Id, err)
  1082. continue
  1083. }
  1084. if err := tx.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
  1085. Update("settings", string(newSettings)).Error; err != nil {
  1086. return err
  1087. }
  1088. }
  1089. return tx.Create(&model.HistoryOfSeeders{SeederName: "InboundClientSubIdFix"}).Error
  1090. })
  1091. }
  1092. func normalizeInboundClientsArray() error {
  1093. var inbounds []model.Inbound
  1094. if err := db.Find(&inbounds).Error; err != nil {
  1095. return err
  1096. }
  1097. return db.Transaction(func(tx *gorm.DB) error {
  1098. for _, inbound := range inbounds {
  1099. if strings.TrimSpace(inbound.Settings) == "" {
  1100. continue
  1101. }
  1102. var settings map[string]any
  1103. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1104. log.Printf("InboundClientsArrayFix: skip inbound %d (invalid settings json): %v", inbound.Id, err)
  1105. continue
  1106. }
  1107. raw, exists := settings["clients"]
  1108. if !exists || raw != nil {
  1109. continue
  1110. }
  1111. settings["clients"] = []any{}
  1112. newSettings, err := json.MarshalIndent(settings, "", " ")
  1113. if err != nil {
  1114. log.Printf("InboundClientsArrayFix: skip inbound %d (marshal failed): %v", inbound.Id, err)
  1115. continue
  1116. }
  1117. if err := tx.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
  1118. Update("settings", string(newSettings)).Error; err != nil {
  1119. return err
  1120. }
  1121. }
  1122. return tx.Create(&model.HistoryOfSeeders{SeederName: "InboundClientsArrayFix"}).Error
  1123. })
  1124. }
  1125. func normalizeFreedomFinalRules() error {
  1126. var setting model.Setting
  1127. err := db.Model(model.Setting{}).Where("key = ?", "xrayTemplateConfig").First(&setting).Error
  1128. if errors.Is(err, gorm.ErrRecordNotFound) {
  1129. return db.Create(&model.HistoryOfSeeders{SeederName: "FreedomFinalRulesReverseFix"}).Error
  1130. }
  1131. if err != nil {
  1132. return err
  1133. }
  1134. updated, changed, rErr := rewriteFreedomFinalRules(setting.Value)
  1135. if rErr != nil {
  1136. log.Printf("FreedomFinalRulesReverseFix: skip (invalid xrayTemplateConfig json): %v", rErr)
  1137. return db.Create(&model.HistoryOfSeeders{SeederName: "FreedomFinalRulesReverseFix"}).Error
  1138. }
  1139. return db.Transaction(func(tx *gorm.DB) error {
  1140. if changed {
  1141. if err := tx.Model(&model.Setting{}).Where("key = ?", "xrayTemplateConfig").
  1142. Update("value", updated).Error; err != nil {
  1143. return err
  1144. }
  1145. }
  1146. return tx.Create(&model.HistoryOfSeeders{SeederName: "FreedomFinalRulesReverseFix"}).Error
  1147. })
  1148. }
  1149. func rewriteFreedomFinalRules(raw string) (string, bool, error) {
  1150. if strings.TrimSpace(raw) == "" {
  1151. return raw, false, nil
  1152. }
  1153. var cfg map[string]any
  1154. if err := json.Unmarshal([]byte(raw), &cfg); err != nil {
  1155. return raw, false, err
  1156. }
  1157. outbounds, ok := cfg["outbounds"].([]any)
  1158. if !ok {
  1159. return raw, false, nil
  1160. }
  1161. changed := false
  1162. for _, ob := range outbounds {
  1163. obj, ok := ob.(map[string]any)
  1164. if !ok {
  1165. continue
  1166. }
  1167. if proto, _ := obj["protocol"].(string); proto != "freedom" {
  1168. continue
  1169. }
  1170. settings, ok := obj["settings"].(map[string]any)
  1171. if !ok {
  1172. continue
  1173. }
  1174. if !isLegacyPrivateOnlyFinalRules(settings["finalRules"]) {
  1175. continue
  1176. }
  1177. settings["finalRules"] = []any{map[string]any{"action": "allow"}}
  1178. changed = true
  1179. }
  1180. if !changed {
  1181. return raw, false, nil
  1182. }
  1183. out, err := json.MarshalIndent(cfg, "", " ")
  1184. if err != nil {
  1185. return raw, false, err
  1186. }
  1187. return string(out), true, nil
  1188. }
  1189. func isLegacyPrivateOnlyFinalRules(v any) bool {
  1190. rules, ok := v.([]any)
  1191. if !ok || len(rules) != 1 {
  1192. return false
  1193. }
  1194. rule, ok := rules[0].(map[string]any)
  1195. if !ok {
  1196. return false
  1197. }
  1198. if action, _ := rule["action"].(string); action != "allow" {
  1199. return false
  1200. }
  1201. ips, ok := rule["ip"].([]any)
  1202. if !ok || len(ips) != 1 {
  1203. return false
  1204. }
  1205. if s, _ := ips[0].(string); s != "geoip:private" {
  1206. return false
  1207. }
  1208. for k := range rule {
  1209. if k != "action" && k != "ip" {
  1210. return false
  1211. }
  1212. }
  1213. return true
  1214. }
  1215. // normalizeClientJSONFields coerces loosely-typed numeric fields in a raw
  1216. // settings.clients entry so json.Unmarshal into model.Client doesn't fail
  1217. // when older rows wrote tgId/limitIp/totalGB/etc. as strings. Empty strings
  1218. // drop the key so the field falls back to its zero value.
  1219. func normalizeClientJSONFields(obj map[string]any) {
  1220. normalizeInt := func(key string) {
  1221. raw, exists := obj[key]
  1222. if !exists {
  1223. return
  1224. }
  1225. s, ok := raw.(string)
  1226. if !ok {
  1227. return
  1228. }
  1229. trimmed := strings.ReplaceAll(strings.TrimSpace(s), " ", "")
  1230. if trimmed == "" {
  1231. delete(obj, key)
  1232. return
  1233. }
  1234. if n, err := strconv.ParseInt(trimmed, 10, 64); err == nil {
  1235. obj[key] = n
  1236. } else {
  1237. delete(obj, key)
  1238. }
  1239. }
  1240. for _, k := range []string{"tgId", "limitIp", "totalGB", "expiryTime", "reset", "created_at", "updated_at"} {
  1241. normalizeInt(k)
  1242. }
  1243. }
  1244. func seedClientsFromInboundJSON() error {
  1245. var inbounds []model.Inbound
  1246. if err := db.Find(&inbounds).Error; err != nil {
  1247. return err
  1248. }
  1249. return db.Transaction(func(tx *gorm.DB) error {
  1250. byEmail := map[string]*model.ClientRecord{}
  1251. var existing []model.ClientRecord
  1252. if err := tx.Find(&existing).Error; err != nil {
  1253. return err
  1254. }
  1255. for i := range existing {
  1256. byEmail[existing[i].Email] = &existing[i]
  1257. }
  1258. for _, inbound := range inbounds {
  1259. if strings.TrimSpace(inbound.Settings) == "" {
  1260. continue
  1261. }
  1262. var settings map[string]any
  1263. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1264. log.Printf("ClientsTable seed: skip inbound %d (invalid settings json): %v", inbound.Id, err)
  1265. continue
  1266. }
  1267. rawList, ok := settings["clients"].([]any)
  1268. if !ok {
  1269. continue
  1270. }
  1271. for _, raw := range rawList {
  1272. obj, ok := raw.(map[string]any)
  1273. if !ok {
  1274. continue
  1275. }
  1276. normalizeClientJSONFields(obj)
  1277. blob, err := json.Marshal(obj)
  1278. if err != nil {
  1279. continue
  1280. }
  1281. var c model.Client
  1282. if err := json.Unmarshal(blob, &c); err != nil {
  1283. log.Printf("ClientsTable seed: skip client in inbound %d (unmarshal failed): %v; payload=%s",
  1284. inbound.Id, err, string(blob))
  1285. continue
  1286. }
  1287. email := strings.TrimSpace(c.Email)
  1288. if email == "" {
  1289. continue
  1290. }
  1291. incoming := c.ToRecord()
  1292. row, dup := byEmail[email]
  1293. if !dup {
  1294. if err := tx.Create(incoming).Error; err != nil {
  1295. return err
  1296. }
  1297. byEmail[email] = incoming
  1298. row = incoming
  1299. } else {
  1300. conflicts := model.MergeClientRecord(row, incoming)
  1301. for _, x := range conflicts {
  1302. log.Printf("client merge: email=%s conflict on %s old=%v new=%v kept=%v",
  1303. email, x.Field, x.Old, x.New, x.Kept)
  1304. }
  1305. if err := tx.Save(row).Error; err != nil {
  1306. return err
  1307. }
  1308. }
  1309. link := model.ClientInbound{
  1310. ClientId: row.Id,
  1311. InboundId: inbound.Id,
  1312. FlowOverride: c.Flow,
  1313. }
  1314. if err := tx.Where("client_id = ? AND inbound_id = ?", row.Id, inbound.Id).
  1315. FirstOrCreate(&link).Error; err != nil {
  1316. return err
  1317. }
  1318. }
  1319. }
  1320. return tx.Create(&model.HistoryOfSeeders{SeederName: "ClientsTable"}).Error
  1321. })
  1322. }
  1323. // seedApiTokens copies the legacy `apiToken` setting into the new
  1324. // api_tokens table as a row named "default" so existing central panels
  1325. // keep working after the upgrade. Idempotent — records itself in
  1326. // history_of_seeders and only runs when api_tokens is empty.
  1327. func seedApiTokens() error {
  1328. empty, err := isTableEmpty("api_tokens")
  1329. if err != nil {
  1330. return err
  1331. }
  1332. if empty {
  1333. var legacy model.Setting
  1334. err := db.Model(model.Setting{}).Where("key = ?", "apiToken").First(&legacy).Error
  1335. if err == nil && legacy.Value != "" {
  1336. row := &model.ApiToken{
  1337. Name: "default",
  1338. Token: legacy.Value,
  1339. Enabled: true,
  1340. }
  1341. if err := db.Create(row).Error; err != nil {
  1342. log.Printf("Error migrating legacy apiToken: %v", err)
  1343. return err
  1344. }
  1345. }
  1346. }
  1347. return db.Create(&model.HistoryOfSeeders{SeederName: "ApiTokensTable"}).Error
  1348. }
  1349. // hashExistingApiTokens replaces any plaintext token stored before tokens were
  1350. // hashed at rest with its SHA-256 digest. Callers keep their plaintext copy
  1351. // (used on remote nodes), so existing tokens keep authenticating; the panel
  1352. // just can no longer reveal them. Idempotent — already-hashed rows are skipped.
  1353. func hashExistingApiTokens() error {
  1354. var rows []*model.ApiToken
  1355. if err := db.Find(&rows).Error; err != nil {
  1356. return err
  1357. }
  1358. for _, r := range rows {
  1359. if crypto.IsSHA256Hex(r.Token) {
  1360. continue
  1361. }
  1362. hashed := crypto.HashTokenSHA256(r.Token)
  1363. if err := db.Model(model.ApiToken{}).Where("id = ?", r.Id).Update("token", hashed).Error; err != nil {
  1364. log.Printf("Error hashing api token %d: %v", r.Id, err)
  1365. return err
  1366. }
  1367. }
  1368. return db.Create(&model.HistoryOfSeeders{SeederName: "ApiTokensHash"}).Error
  1369. }
  1370. // isTableEmpty returns true if the named table contains zero rows.
  1371. func isTableEmpty(tableName string) (bool, error) {
  1372. var count int64
  1373. err := db.Table(tableName).Count(&count).Error
  1374. return count == 0, err
  1375. }
  1376. // InitDB sets up the database connection, migrates models, and runs seeders.
  1377. // When XUI_DB_TYPE=postgres, dbPath is ignored and XUI_DB_DSN is used instead.
  1378. func InitDB(dbPath string) error {
  1379. var gormLogger logger.Interface
  1380. if config.IsDebug() {
  1381. gormLogger = logger.New(
  1382. log.New(os.Stdout, "\r\n", log.LstdFlags),
  1383. logger.Config{
  1384. SlowThreshold: time.Second,
  1385. LogLevel: logger.Info,
  1386. IgnoreRecordNotFoundError: true,
  1387. Colorful: true,
  1388. },
  1389. )
  1390. } else {
  1391. gormLogger = logger.Discard
  1392. }
  1393. c := &gorm.Config{Logger: gormLogger, DisableForeignKeyConstraintWhenMigrating: true}
  1394. var err error
  1395. switch config.GetDBKind() {
  1396. case "postgres":
  1397. dsn := config.GetDBDSN()
  1398. if dsn == "" {
  1399. return errors.New("XUI_DB_TYPE=postgres but XUI_DB_DSN is empty")
  1400. }
  1401. db, err = gorm.Open(postgres.Open(dsn), c)
  1402. if err != nil {
  1403. return err
  1404. }
  1405. default:
  1406. dir := path.Dir(dbPath)
  1407. if err = os.MkdirAll(dir, 0o755); err != nil {
  1408. return err
  1409. }
  1410. // Keep journal_mode=DELETE so the DB stays a single file (no -wal/-shm
  1411. // sidecars). synchronous defaults to FULL for durability but is tunable.
  1412. sync := sqliteSynchronous()
  1413. dsn := dbPath + "?_journal_mode=DELETE&_busy_timeout=10000&_synchronous=" + sync + "&_txlock=immediate"
  1414. db, err = gorm.Open(sqlite.Open(dsn), c)
  1415. if err != nil {
  1416. return err
  1417. }
  1418. sqlDB, err := db.DB()
  1419. if err != nil {
  1420. return err
  1421. }
  1422. // Re-assert the DSN pragmas plus scan-friendly ones for large datasets.
  1423. // cache_size/mmap_size/temp_store create no extra files, so the single-file
  1424. // guarantee holds; they just cut disk I/O on the 50k-row hot paths.
  1425. pragmas := []string{
  1426. "PRAGMA journal_mode=DELETE",
  1427. "PRAGMA busy_timeout=10000",
  1428. "PRAGMA synchronous=" + sync,
  1429. fmt.Sprintf("PRAGMA cache_size=-%d", envInt("XUI_DB_CACHE_MB", 32)*1024),
  1430. fmt.Sprintf("PRAGMA mmap_size=%d", int64(envInt("XUI_DB_MMAP_MB", 256))*1024*1024),
  1431. "PRAGMA temp_store=MEMORY",
  1432. }
  1433. for _, p := range pragmas {
  1434. if _, err := sqlDB.ExecContext(context.Background(), p); err != nil {
  1435. return err
  1436. }
  1437. }
  1438. }
  1439. sqlDB, err := db.DB()
  1440. if err != nil {
  1441. return err
  1442. }
  1443. var maxOpen, maxIdle int
  1444. switch config.GetDBKind() {
  1445. case "postgres":
  1446. maxOpen = envInt("XUI_DB_MAX_OPEN_CONNS", 25)
  1447. maxIdle = envInt("XUI_DB_MAX_IDLE_CONNS", 25)
  1448. default:
  1449. maxOpen = envInt("XUI_DB_MAX_OPEN_CONNS", 8)
  1450. maxIdle = envInt("XUI_DB_MAX_IDLE_CONNS", 4)
  1451. }
  1452. sqlDB.SetMaxOpenConns(maxOpen)
  1453. sqlDB.SetMaxIdleConns(maxIdle)
  1454. sqlDB.SetConnMaxLifetime(time.Hour)
  1455. sqlDB.SetConnMaxIdleTime(30 * time.Minute)
  1456. if err := initModels(); err != nil {
  1457. return err
  1458. }
  1459. isUsersEmpty, err := isTableEmpty("users")
  1460. if err != nil {
  1461. return err
  1462. }
  1463. if err := initUser(); err != nil {
  1464. return err
  1465. }
  1466. return runSeeders(isUsersEmpty)
  1467. }
  1468. // normalizeApiTokenCreatedAtSeconds repairs rows written while ApiToken used
  1469. // autoCreateTime:milli. The threshold separates modern Unix milliseconds from
  1470. // Unix seconds and makes this safe to run on every startup.
  1471. func normalizeApiTokenCreatedAtSeconds() error {
  1472. return db.Model(&model.ApiToken{}).
  1473. Where("created_at >= ?", model.ApiTokenUnixMillisecondsThreshold).
  1474. UpdateColumn("created_at", gorm.Expr("created_at / ?", 1000)).Error
  1475. }
  1476. // sqliteSynchronous returns the SQLite synchronous mode, defaulting to FULL.
  1477. // Whitelisted because the value is interpolated directly into a PRAGMA string.
  1478. func sqliteSynchronous() string {
  1479. switch strings.ToUpper(strings.TrimSpace(os.Getenv("XUI_DB_SYNCHRONOUS"))) {
  1480. case "OFF":
  1481. return "OFF"
  1482. case "NORMAL":
  1483. return "NORMAL"
  1484. case "EXTRA":
  1485. return "EXTRA"
  1486. default:
  1487. return "FULL"
  1488. }
  1489. }
  1490. func envInt(key string, def int) int {
  1491. v := strings.TrimSpace(os.Getenv(key))
  1492. if v == "" {
  1493. return def
  1494. }
  1495. n, err := strconv.Atoi(v)
  1496. if err != nil || n <= 0 {
  1497. return def
  1498. }
  1499. return n
  1500. }
  1501. // CloseDB closes the database connection if it exists.
  1502. func CloseDB() error {
  1503. if db != nil {
  1504. sqlDB, err := db.DB()
  1505. if err != nil {
  1506. return err
  1507. }
  1508. return sqlDB.Close()
  1509. }
  1510. return nil
  1511. }
  1512. // GetDB returns the global GORM database instance.
  1513. func GetDB() *gorm.DB {
  1514. return db
  1515. }
  1516. func IsNotFound(err error) bool {
  1517. return errors.Is(err, gorm.ErrRecordNotFound)
  1518. }
  1519. // IsSQLiteDB checks if the given file is a valid SQLite database by reading its signature.
  1520. func IsSQLiteDB(file io.ReaderAt) (bool, error) {
  1521. signature := []byte("SQLite format 3\x00")
  1522. buf := make([]byte, len(signature))
  1523. _, err := file.ReadAt(buf, 0)
  1524. if err != nil {
  1525. return false, err
  1526. }
  1527. return bytes.Equal(buf, signature), nil
  1528. }
  1529. // Checkpoint performs a WAL checkpoint on the SQLite database to ensure data consistency.
  1530. // No-op on PostgreSQL (WAL there is managed by the server).
  1531. func Checkpoint() error {
  1532. if IsPostgres() {
  1533. return nil
  1534. }
  1535. return db.Exec("PRAGMA wal_checkpoint;").Error
  1536. }
  1537. // ValidateSQLiteDB opens the provided sqlite DB path with a throw-away connection
  1538. // and runs a PRAGMA integrity_check to ensure the file is structurally sound.
  1539. // It does not mutate global state or run migrations.
  1540. func ValidateSQLiteDB(dbPath string) error {
  1541. if _, err := os.Stat(dbPath); err != nil { // file must exist
  1542. return err
  1543. }
  1544. gdb, err := gorm.Open(sqlite.Open(dbPath), &gorm.Config{Logger: logger.Discard})
  1545. if err != nil {
  1546. return err
  1547. }
  1548. sqlDB, err := gdb.DB()
  1549. if err != nil {
  1550. return err
  1551. }
  1552. defer sqlDB.Close()
  1553. var res string
  1554. if err := gdb.Raw("PRAGMA integrity_check;").Scan(&res).Error; err != nil {
  1555. return err
  1556. }
  1557. if res != "ok" {
  1558. return errors.New("sqlite integrity check failed: " + res)
  1559. }
  1560. return nil
  1561. }