1
0

db.go 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384
  1. package database
  2. import (
  3. "bytes"
  4. "context"
  5. "database/sql"
  6. "encoding/json"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "log"
  11. "math"
  12. "os"
  13. "os/exec"
  14. "path"
  15. "path/filepath"
  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. "github.com/mattn/go-sqlite3"
  27. "gorm.io/driver/postgres"
  28. "gorm.io/driver/sqlite"
  29. "gorm.io/gorm"
  30. "gorm.io/gorm/logger"
  31. )
  32. var db *gorm.DB
  33. var backupSQLiteTimeout = 2 * time.Minute
  34. const (
  35. DialectSQLite = "sqlite"
  36. DialectPostgres = "postgres"
  37. )
  38. func IsPostgres() bool {
  39. if db == nil {
  40. return config.GetDBKind() == "postgres"
  41. }
  42. return db.Name() == "postgres"
  43. }
  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. sqliteBackupDirPrefix = ".x-ui-backup-"
  54. )
  55. func allModels() []any {
  56. return []any{
  57. &model.User{},
  58. &model.Inbound{},
  59. &model.OutboundTraffics{},
  60. &model.Setting{},
  61. &model.InboundClientIps{},
  62. &xray.ClientTraffic{},
  63. &model.HistoryOfSeeders{},
  64. &model.Node{},
  65. &model.ApiToken{},
  66. &model.ClientRecord{},
  67. &model.ClientInbound{},
  68. &model.ClientHwid{},
  69. &model.ClientExternalLink{},
  70. &model.ClientGroup{},
  71. &model.InboundFallback{},
  72. &model.Host{},
  73. &model.NodeClientTraffic{},
  74. &model.NodeClientIp{},
  75. &model.ClientGlobalTraffic{},
  76. &model.OutboundSubscription{},
  77. }
  78. }
  79. func migrateClientTrafficLastSubFetchColumn() error {
  80. migrator := db.Migrator()
  81. if !migrator.HasTable(&xray.ClientTraffic{}) || migrator.HasColumn(&xray.ClientTraffic{}, "last_sub_fetch") {
  82. return nil
  83. }
  84. return migrator.AddColumn(&xray.ClientTraffic{}, "LastSubFetch")
  85. }
  86. func initModels() error {
  87. if err := migrateClientTrafficLastSubFetchColumn(); err != nil {
  88. return err
  89. }
  90. models := allModels()
  91. for _, mdl := range models {
  92. if IsPostgres() && postgresModelSettled(mdl) {
  93. continue
  94. }
  95. if err := db.AutoMigrate(mdl); err != nil {
  96. if isIgnorableDuplicateColumnErr(db, err, mdl) {
  97. log.Printf("Ignoring duplicate column during auto migration for %T: %v", mdl, err)
  98. continue
  99. }
  100. log.Printf("Error auto migrating model: %v", err)
  101. return err
  102. }
  103. }
  104. if err := dropLegacyInboundPortUnique(); err != nil {
  105. return err
  106. }
  107. if err := migrateHostVerifyPeerCertByNameColumn(); err != nil {
  108. return err
  109. }
  110. if err := normalizeApiTokenCreatedAtSeconds(); err != nil {
  111. return err
  112. }
  113. if err := migrateApiTokenScopeAndExpiry(); err != nil {
  114. return err
  115. }
  116. if err := dropLegacyForeignKeys(); err != nil {
  117. return err
  118. }
  119. if err := pruneOrphanedClientInbounds(); err != nil {
  120. return err
  121. }
  122. if err := pruneOrphanedHosts(); err != nil {
  123. return err
  124. }
  125. if err := normalizeInboundSubSortIndex(); err != nil {
  126. return err
  127. }
  128. if err := normalizeClientExternalLinkEnable(); err != nil {
  129. return err
  130. }
  131. if err := normalizeClientExternalLinkTimestamps(); err != nil {
  132. return err
  133. }
  134. if err := repairOverflowedTrafficCounters(); err != nil {
  135. return err
  136. }
  137. if err := dedupeInboundSettingsClients(); err != nil {
  138. return err
  139. }
  140. if err := migrateLegacySocksInboundsToMixed(); err != nil {
  141. return err
  142. }
  143. if err := migrateShadowsocksRemovedCiphers(); err != nil {
  144. return err
  145. }
  146. if err := migrateVmessRemovedSecurities(); err != nil {
  147. return err
  148. }
  149. if err := migrateTgIDIndex(); err != nil {
  150. return err
  151. }
  152. if err := migrateClientTrafficResetColumns(); err != nil {
  153. return err
  154. }
  155. if err := migrateSyncOrphanColumns(); err != nil {
  156. return err
  157. }
  158. if err := migrateClientEmailLowerIndex(); err != nil {
  159. return err
  160. }
  161. if IsPostgres() {
  162. if err := resyncPostgresSequences(db, models); err != nil {
  163. log.Printf("Error resyncing postgres sequences: %v", err)
  164. return err
  165. }
  166. }
  167. return nil
  168. }
  169. func postgresModelSettled(mdl any) bool {
  170. migrator := db.Migrator()
  171. if !migrator.HasTable(mdl) {
  172. return false
  173. }
  174. stmt := &gorm.Statement{DB: db}
  175. if err := stmt.Parse(mdl); err != nil || stmt.Schema == nil {
  176. return false
  177. }
  178. for _, dbName := range stmt.Schema.DBNames {
  179. if !migrator.HasColumn(mdl, dbName) {
  180. return false
  181. }
  182. }
  183. for _, idx := range stmt.Schema.ParseIndexes() {
  184. if !migrator.HasIndex(mdl, idx.Name) {
  185. return false
  186. }
  187. }
  188. return true
  189. }
  190. func dropLegacyForeignKeys() error {
  191. if !IsPostgres() {
  192. return nil
  193. }
  194. if err := db.Exec("ALTER TABLE client_traffics DROP CONSTRAINT IF EXISTS fk_inbounds_client_stats").Error; err != nil {
  195. log.Printf("Error dropping legacy foreign key fk_inbounds_client_stats: %v", err)
  196. return err
  197. }
  198. return nil
  199. }
  200. type sqliteIndexListRow struct {
  201. Name string `gorm:"column:name"`
  202. Unique int `gorm:"column:unique"`
  203. Origin string `gorm:"column:origin"`
  204. }
  205. func sqliteUniquePortIndexes() (autoIndexes, explicitIndexes []string, err error) {
  206. var list []sqliteIndexListRow
  207. if err = db.Raw(`PRAGMA index_list('inbounds')`).Scan(&list).Error; err != nil {
  208. return nil, nil, err
  209. }
  210. for _, idx := range list {
  211. if idx.Unique != 1 {
  212. continue
  213. }
  214. var cols []struct {
  215. Name string `gorm:"column:name"`
  216. }
  217. if err = db.Raw(`PRAGMA index_info("` + idx.Name + `")`).Scan(&cols).Error; err != nil {
  218. return nil, nil, err
  219. }
  220. if len(cols) != 1 || cols[0].Name != "port" {
  221. continue
  222. }
  223. if idx.Origin == "c" {
  224. explicitIndexes = append(explicitIndexes, idx.Name)
  225. } else {
  226. autoIndexes = append(autoIndexes, idx.Name)
  227. }
  228. }
  229. return autoIndexes, explicitIndexes, nil
  230. }
  231. // dropLegacyInboundPortUnique removes the pre-multi-node UNIQUE on inbounds.port,
  232. // which AutoMigrate never drops and which blocks cross-node port reuse on old SQLite DBs.
  233. func dropLegacyInboundPortUnique() error {
  234. if IsPostgres() {
  235. return nil
  236. }
  237. autoIndexes, explicitIndexes, err := sqliteUniquePortIndexes()
  238. if err != nil {
  239. return err
  240. }
  241. for _, name := range explicitIndexes {
  242. if err := db.Exec(`DROP INDEX IF EXISTS "` + name + `"`).Error; err != nil {
  243. return err
  244. }
  245. }
  246. if len(autoIndexes) == 0 {
  247. return nil
  248. }
  249. log.Printf("Rebuilding inbounds table to drop the legacy UNIQUE constraint on port")
  250. return rebuildInboundsWithoutInlineUniquePort()
  251. }
  252. func sqliteTableColumns(tx *gorm.DB, table string) ([]string, error) {
  253. var rows []struct {
  254. Name string `gorm:"column:name"`
  255. }
  256. if err := tx.Raw(`PRAGMA table_info("` + table + `")`).Scan(&rows).Error; err != nil {
  257. return nil, err
  258. }
  259. cols := make([]string, 0, len(rows))
  260. for _, r := range rows {
  261. cols = append(cols, r.Name)
  262. }
  263. return cols, nil
  264. }
  265. func rebuildInboundsWithoutInlineUniquePort() error {
  266. return db.Transaction(func(tx *gorm.DB) error {
  267. var list []sqliteIndexListRow
  268. if err := tx.Raw(`PRAGMA index_list('inbounds')`).Scan(&list).Error; err != nil {
  269. return err
  270. }
  271. for _, idx := range list {
  272. if idx.Origin != "c" {
  273. continue
  274. }
  275. if err := tx.Exec(`DROP INDEX IF EXISTS "` + idx.Name + `"`).Error; err != nil {
  276. return err
  277. }
  278. }
  279. if err := tx.Exec(`ALTER TABLE inbounds RENAME TO inbounds_legacy_rebuild`).Error; err != nil {
  280. return err
  281. }
  282. if err := tx.Migrator().CreateTable(&model.Inbound{}); err != nil {
  283. return err
  284. }
  285. newCols, err := sqliteTableColumns(tx, "inbounds")
  286. if err != nil {
  287. return err
  288. }
  289. oldCols, err := sqliteTableColumns(tx, "inbounds_legacy_rebuild")
  290. if err != nil {
  291. return err
  292. }
  293. oldSet := make(map[string]struct{}, len(oldCols))
  294. for _, c := range oldCols {
  295. oldSet[c] = struct{}{}
  296. }
  297. shared := make([]string, 0, len(newCols))
  298. for _, c := range newCols {
  299. if _, ok := oldSet[c]; ok {
  300. shared = append(shared, `"`+c+`"`)
  301. }
  302. }
  303. colList := strings.Join(shared, ", ")
  304. if err := tx.Exec(`INSERT INTO inbounds (` + colList + `) SELECT ` + colList + ` FROM inbounds_legacy_rebuild`).Error; err != nil {
  305. return err
  306. }
  307. return tx.Exec(`DROP TABLE inbounds_legacy_rebuild`).Error
  308. })
  309. }
  310. // AutoMigrate adds the columns; an older SQLite ALTER TABLE leaves them NULL,
  311. // and a NULL traffic_reset fails every ClientRecord scan, not just the new query.
  312. func migrateClientTrafficResetColumns() error {
  313. if db.Migrator().HasColumn(&model.ClientRecord{}, "traffic_reset") {
  314. if err := db.Exec("UPDATE clients SET traffic_reset = 'never' WHERE traffic_reset IS NULL").Error; err != nil {
  315. return err
  316. }
  317. }
  318. if db.Migrator().HasColumn(&model.ClientRecord{}, "traffic_reset_day") {
  319. if err := db.Exec("UPDATE clients SET traffic_reset_day = 1 WHERE traffic_reset_day IS NULL").Error; err != nil {
  320. return err
  321. }
  322. }
  323. return nil
  324. }
  325. // AutoMigrate adds the column; this only backfills the NULLs an older SQLite
  326. // ALTER TABLE leaves behind, so the reaper's predicate never compares to NULL.
  327. func migrateSyncOrphanColumns() error {
  328. if !db.Migrator().HasColumn(&model.ClientRecord{}, "sync_orphaned_at") {
  329. return nil
  330. }
  331. return db.Exec("UPDATE clients SET sync_orphaned_at = 0 WHERE sync_orphaned_at IS NULL").Error
  332. }
  333. // The client identity checks match emails case-insensitively; without an
  334. // expression index (which no GORM struct tag can declare) they seq-scan.
  335. func migrateClientEmailLowerIndex() error {
  336. if db.Migrator().HasIndex(&model.ClientRecord{}, "idx_clients_email_lower") {
  337. return nil
  338. }
  339. return db.Exec("CREATE INDEX IF NOT EXISTS idx_clients_email_lower ON clients (LOWER(email))").Error
  340. }
  341. func migrateHostVerifyPeerCertByNameColumn() error {
  342. if !db.Migrator().HasColumn(&model.Host{}, "verify_peer_cert_by_name") {
  343. return nil
  344. }
  345. if IsPostgres() {
  346. var dataType string
  347. if err := db.Raw(
  348. `SELECT data_type FROM information_schema.columns WHERE table_name = 'hosts' AND column_name = 'verify_peer_cert_by_name'`,
  349. ).Scan(&dataType).Error; err != nil {
  350. return err
  351. }
  352. if dataType != "boolean" {
  353. return nil
  354. }
  355. if err := db.Exec(`ALTER TABLE hosts ALTER COLUMN verify_peer_cert_by_name DROP DEFAULT`).Error; err != nil {
  356. return err
  357. }
  358. return db.Exec(`ALTER TABLE hosts ALTER COLUMN verify_peer_cert_by_name TYPE text USING ''`).Error
  359. }
  360. 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
  361. }
  362. func seedHostsFromExternalProxy() error {
  363. var history []string
  364. if err := db.Model(&model.HistoryOfSeeders{}).Pluck("seeder_name", &history).Error; err != nil {
  365. return err
  366. }
  367. if slices.Contains(history, "HostsFromExternalProxy") {
  368. return nil
  369. }
  370. var inbounds []model.Inbound
  371. if err := db.Find(&inbounds).Error; err != nil {
  372. return err
  373. }
  374. return db.Transaction(func(tx *gorm.DB) error {
  375. for _, inbound := range inbounds {
  376. if _, err := CreateHostsFromExternalProxy(tx, inbound.Id, inbound.StreamSettings); err != nil {
  377. return err
  378. }
  379. }
  380. return tx.Create(&model.HistoryOfSeeders{SeederName: "HostsFromExternalProxy"}).Error
  381. })
  382. }
  383. func seedWireguardPeersToClients() error {
  384. var history []string
  385. if err := db.Model(&model.HistoryOfSeeders{}).Pluck("seeder_name", &history).Error; err != nil {
  386. return err
  387. }
  388. if slices.Contains(history, "WireguardPeersToClients") {
  389. return nil
  390. }
  391. var inbounds []model.Inbound
  392. if err := db.Where("protocol = ?", string(model.WireGuard)).Find(&inbounds).Error; err != nil {
  393. return err
  394. }
  395. return db.Transaction(func(tx *gorm.DB) error {
  396. usedEmails := map[string]struct{}{}
  397. var existingEmails []string
  398. if err := tx.Model(&model.ClientRecord{}).Pluck("email", &existingEmails).Error; err != nil {
  399. return err
  400. }
  401. for _, e := range existingEmails {
  402. usedEmails[e] = struct{}{}
  403. }
  404. for _, inbound := range inbounds {
  405. if strings.TrimSpace(inbound.Settings) == "" {
  406. continue
  407. }
  408. var settings map[string]any
  409. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  410. log.Printf("WireguardPeersToClients: skip inbound %d (invalid settings json): %v", inbound.Id, err)
  411. continue
  412. }
  413. peers, ok := settings["peers"].([]any)
  414. if !ok || len(peers) == 0 {
  415. continue
  416. }
  417. var linkCount int64
  418. if err := tx.Model(&model.ClientInbound{}).Where("inbound_id = ?", inbound.Id).Count(&linkCount).Error; err != nil {
  419. return err
  420. }
  421. if linkCount > 0 {
  422. continue
  423. }
  424. clientObjs := make([]any, 0, len(peers))
  425. for i, raw := range peers {
  426. obj, ok := raw.(map[string]any)
  427. if !ok {
  428. continue
  429. }
  430. email := wireguardPeerEmail(inbound.Remark, obj, i, usedEmails)
  431. usedEmails[email] = struct{}{}
  432. obj["email"] = email
  433. if sub, _ := obj["subId"].(string); strings.TrimSpace(sub) == "" {
  434. obj["subId"] = random.NumLower(16)
  435. }
  436. if _, ok := obj["enable"]; !ok {
  437. obj["enable"] = true
  438. }
  439. blob, err := json.Marshal(obj)
  440. if err != nil {
  441. continue
  442. }
  443. var c model.Client
  444. if err := json.Unmarshal(blob, &c); err != nil {
  445. log.Printf("WireguardPeersToClients: skip peer in inbound %d: %v", inbound.Id, err)
  446. continue
  447. }
  448. c.Email = email
  449. incoming := c.ToRecord()
  450. var row model.ClientRecord
  451. err = tx.Where("email = ?", email).First(&row).Error
  452. if errors.Is(err, gorm.ErrRecordNotFound) {
  453. if err := tx.Create(incoming).Error; err != nil {
  454. return err
  455. }
  456. row = *incoming
  457. } else if err != nil {
  458. return err
  459. } else {
  460. model.MergeClientRecord(&row, incoming)
  461. if err := tx.Save(&row).Error; err != nil {
  462. return err
  463. }
  464. }
  465. link := model.ClientInbound{ClientId: row.Id, InboundId: inbound.Id}
  466. if err := tx.Where("client_id = ? AND inbound_id = ?", row.Id, inbound.Id).
  467. FirstOrCreate(&link).Error; err != nil {
  468. return err
  469. }
  470. clientObjs = append(clientObjs, obj)
  471. }
  472. delete(settings, "peers")
  473. settings["clients"] = clientObjs
  474. newSettings, err := json.Marshal(settings)
  475. if err != nil {
  476. return err
  477. }
  478. if err := tx.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
  479. Update("settings", string(newSettings)).Error; err != nil {
  480. return err
  481. }
  482. }
  483. return tx.Create(&model.HistoryOfSeeders{SeederName: "WireguardPeersToClients"}).Error
  484. })
  485. }
  486. func wireguardPeerEmail(remark string, peer map[string]any, index int, used map[string]struct{}) string {
  487. base := strings.TrimSpace(remark)
  488. if base == "" {
  489. base = "wg"
  490. }
  491. suffix := strconv.Itoa(index + 1)
  492. if c, ok := peer["comment"].(string); ok && strings.TrimSpace(c) != "" {
  493. suffix = strings.TrimSpace(c)
  494. }
  495. email := strings.ReplaceAll(base+"-"+suffix, " ", "-")
  496. candidate := email
  497. for n := 2; ; n++ {
  498. if _, taken := used[candidate]; !taken {
  499. return candidate
  500. }
  501. candidate = email + "-" + strconv.Itoa(n)
  502. }
  503. }
  504. // seedMtprotoSecretsToClients converts each legacy single-secret mtproto inbound
  505. // into a one-client inbound so MTProto joins the shared multi-client model: the
  506. // inbound-level secret becomes the first client's FakeTLS secret, and a
  507. // ClientRecord + client_inbounds link are created so per-client traffic, limits,
  508. // and share links work exactly like every other protocol. One-time, self-gated
  509. // on the "MtprotoSecretsToClients" seeder row. Mirrors seedWireguardPeersToClients.
  510. func seedMtprotoSecretsToClients() error {
  511. var history []string
  512. if err := db.Model(&model.HistoryOfSeeders{}).Pluck("seeder_name", &history).Error; err != nil {
  513. return err
  514. }
  515. if slices.Contains(history, "MtprotoSecretsToClients") {
  516. return nil
  517. }
  518. var inbounds []model.Inbound
  519. if err := db.Where("protocol = ?", string(model.MTProto)).Find(&inbounds).Error; err != nil {
  520. return err
  521. }
  522. return db.Transaction(func(tx *gorm.DB) error {
  523. usedEmails := map[string]struct{}{}
  524. var existingEmails []string
  525. if err := tx.Model(&model.ClientRecord{}).Pluck("email", &existingEmails).Error; err != nil {
  526. return err
  527. }
  528. for _, e := range existingEmails {
  529. usedEmails[e] = struct{}{}
  530. }
  531. for _, inbound := range inbounds {
  532. if strings.TrimSpace(inbound.Settings) == "" {
  533. continue
  534. }
  535. var settings map[string]any
  536. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  537. log.Printf("MtprotoSecretsToClients: skip inbound %d (invalid settings json): %v", inbound.Id, err)
  538. continue
  539. }
  540. if clients, ok := settings["clients"].([]any); ok && len(clients) > 0 {
  541. continue
  542. }
  543. var linkCount int64
  544. if err := tx.Model(&model.ClientInbound{}).Where("inbound_id = ?", inbound.Id).Count(&linkCount).Error; err != nil {
  545. return err
  546. }
  547. if linkCount > 0 {
  548. continue
  549. }
  550. secret, _ := settings["secret"].(string)
  551. secret = strings.TrimSpace(secret)
  552. if secret == "" {
  553. domain, _ := settings["fakeTlsDomain"].(string)
  554. secret = model.GenerateFakeTLSSecret(strings.TrimSpace(domain))
  555. }
  556. email := mtprotoInboundClientEmail(inbound.Remark, usedEmails)
  557. usedEmails[email] = struct{}{}
  558. obj := map[string]any{
  559. "email": email,
  560. "secret": secret,
  561. "enable": true,
  562. "subId": random.NumLower(16),
  563. }
  564. c := model.Client{Email: email, Secret: secret, Enable: true, SubID: obj["subId"].(string)}
  565. incoming := c.ToRecord()
  566. var row model.ClientRecord
  567. err := tx.Where("email = ?", email).First(&row).Error
  568. if errors.Is(err, gorm.ErrRecordNotFound) {
  569. if err := tx.Create(incoming).Error; err != nil {
  570. return err
  571. }
  572. row = *incoming
  573. } else if err != nil {
  574. return err
  575. } else {
  576. model.MergeClientRecord(&row, incoming)
  577. if err := tx.Save(&row).Error; err != nil {
  578. return err
  579. }
  580. }
  581. link := model.ClientInbound{ClientId: row.Id, InboundId: inbound.Id}
  582. if err := tx.Where("client_id = ? AND inbound_id = ?", row.Id, inbound.Id).
  583. FirstOrCreate(&link).Error; err != nil {
  584. return err
  585. }
  586. delete(settings, "secret")
  587. settings["clients"] = []any{obj}
  588. newSettings, err := json.Marshal(settings)
  589. if err != nil {
  590. return err
  591. }
  592. if err := tx.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
  593. Update("settings", string(newSettings)).Error; err != nil {
  594. return err
  595. }
  596. }
  597. return tx.Create(&model.HistoryOfSeeders{SeederName: "MtprotoSecretsToClients"}).Error
  598. })
  599. }
  600. // stripMtprotoInboundSecrets removes the vestigial inbound-level `secret` from
  601. // every mtproto inbound. seedMtprotoSecretsToClients already drops it while
  602. // converting legacy single-secret inbounds, but inbounds that already had clients
  603. // kept the dead field, and the old HealMtprotoSecret regenerated it on every
  604. // save. mtg and every share link read only per-client secrets, so the
  605. // inbound-level value is dead data that once leaked into stale, unusable links.
  606. // One-time, self-gated on the "StripMtprotoInboundSecrets" seeder row.
  607. func stripMtprotoInboundSecrets() error {
  608. var history []string
  609. if err := db.Model(&model.HistoryOfSeeders{}).Pluck("seeder_name", &history).Error; err != nil {
  610. return err
  611. }
  612. if slices.Contains(history, "StripMtprotoInboundSecrets") {
  613. return nil
  614. }
  615. var inbounds []model.Inbound
  616. if err := db.Where("protocol = ?", string(model.MTProto)).Find(&inbounds).Error; err != nil {
  617. return err
  618. }
  619. return db.Transaction(func(tx *gorm.DB) error {
  620. for _, inbound := range inbounds {
  621. stripped, ok := model.StripMtprotoInboundSecret(inbound.Settings)
  622. if !ok {
  623. continue
  624. }
  625. if err := tx.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
  626. Update("settings", stripped).Error; err != nil {
  627. return err
  628. }
  629. }
  630. return tx.Create(&model.HistoryOfSeeders{SeederName: "StripMtprotoInboundSecrets"}).Error
  631. })
  632. }
  633. // mtprotoInboundClientEmail derives a stable, unique client email for a migrated
  634. // mtproto inbound from its remark.
  635. func mtprotoInboundClientEmail(remark string, used map[string]struct{}) string {
  636. base := strings.TrimSpace(remark)
  637. if base == "" {
  638. base = "mtproto"
  639. }
  640. email := strings.ReplaceAll(base, " ", "-")
  641. candidate := email
  642. for n := 2; ; n++ {
  643. if _, taken := used[candidate]; !taken {
  644. return candidate
  645. }
  646. candidate = email + "-" + strconv.Itoa(n)
  647. }
  648. }
  649. // CreateHostsFromExternalProxy parses a legacy streamSettings.externalProxy array
  650. // and inserts one Host row per entry on tx, returning the number of rows created.
  651. // It is the shared core of both the one-time seedHostsFromExternalProxy startup
  652. // migration and the inbound-import path: an inbound exported from a build that
  653. // predated the hosts table carries its external proxies inline in
  654. // streamSettings.externalProxy, and the startup migration is gated off after its
  655. // first run, so a freshly imported inbound must be converted here instead. Blank
  656. // or malformed streamSettings, or one without externalProxy entries, is a no-op.
  657. func CreateHostsFromExternalProxy(tx *gorm.DB, inboundId int, streamSettings string) (int, error) {
  658. if strings.TrimSpace(streamSettings) == "" {
  659. return 0, nil
  660. }
  661. var stream map[string]any
  662. if err := json.Unmarshal([]byte(streamSettings), &stream); err != nil {
  663. return 0, nil
  664. }
  665. eps, ok := stream["externalProxy"].([]any)
  666. if !ok || len(eps) == 0 {
  667. return 0, nil
  668. }
  669. created := 0
  670. for i, raw := range eps {
  671. ep, ok := raw.(map[string]any)
  672. if !ok {
  673. continue
  674. }
  675. if err := tx.Create(externalProxyEntryToHost(inboundId, i, ep)).Error; err != nil {
  676. return created, err
  677. }
  678. created++
  679. }
  680. return created, nil
  681. }
  682. func externalProxyEntryToHost(inboundId, index int, ep map[string]any) *model.Host {
  683. security, _ := ep["forceTls"].(string)
  684. switch security {
  685. case "same", "tls", "none":
  686. default:
  687. security = "same"
  688. }
  689. dest, _ := ep["dest"].(string)
  690. port := 0
  691. if p, ok := ep["port"].(float64); ok {
  692. port = int(p)
  693. }
  694. remark, _ := ep["remark"].(string)
  695. if strings.TrimSpace(remark) == "" {
  696. remark = "imported " + strconv.Itoa(index+1)
  697. }
  698. if len(remark) > 256 {
  699. remark = remark[:256]
  700. }
  701. sni, _ := ep["sni"].(string)
  702. fingerprint, _ := ep["fingerprint"].(string)
  703. ech, _ := ep["echConfigList"].(string)
  704. return &model.Host{
  705. GroupId: random.NumLower(16),
  706. InboundId: inboundId,
  707. SortOrder: index,
  708. Remark: remark,
  709. Address: dest,
  710. Port: port,
  711. Security: security,
  712. Sni: sni,
  713. Fingerprint: fingerprint,
  714. Alpn: anyToNonEmptyStrings(ep["alpn"]),
  715. PinnedPeerCertSha256: anyToNonEmptyStrings(ep["pinnedPeerCertSha256"]),
  716. EchConfigList: ech,
  717. }
  718. }
  719. func anyToNonEmptyStrings(v any) []string {
  720. switch t := v.(type) {
  721. case []any:
  722. out := make([]string, 0, len(t))
  723. for _, e := range t {
  724. if s, ok := e.(string); ok && s != "" {
  725. out = append(out, s)
  726. }
  727. }
  728. return out
  729. case []string:
  730. out := make([]string, 0, len(t))
  731. for _, s := range t {
  732. if s != "" {
  733. out = append(out, s)
  734. }
  735. }
  736. return out
  737. default:
  738. return nil
  739. }
  740. }
  741. func pruneOrphanedHosts() error {
  742. res := db.Exec("DELETE FROM hosts WHERE inbound_id NOT IN (SELECT id FROM inbounds)")
  743. if res.Error != nil {
  744. log.Printf("Error pruning orphaned hosts rows: %v", res.Error)
  745. return res.Error
  746. }
  747. if res.RowsAffected > 0 {
  748. log.Printf("Pruned %d orphaned hosts row(s)", res.RowsAffected)
  749. }
  750. return nil
  751. }
  752. func pruneOrphanedClientInbounds() error {
  753. res := db.Exec("DELETE FROM client_inbounds WHERE inbound_id NOT IN (SELECT id FROM inbounds)")
  754. if res.Error != nil {
  755. log.Printf("Error pruning orphaned client_inbounds rows: %v", res.Error)
  756. return res.Error
  757. }
  758. if res.RowsAffected > 0 {
  759. log.Printf("Pruned %d orphaned client_inbounds row(s)", res.RowsAffected)
  760. }
  761. return nil
  762. }
  763. // migrateLegacySocksInboundsToMixed renames legacy socks inbounds to mixed.
  764. // The protocol enum dropped socks in favor of mixed (identical settings shape,
  765. // same behavior plus HTTP on the shared port), so rows predating the rename
  766. // fail model validation — most visibly when pushed to a node, where one legacy
  767. // inbound stalled the entire node's config and traffic sync (#5685).
  768. func migrateLegacySocksInboundsToMixed() error {
  769. res := db.Exec("UPDATE inbounds SET protocol = 'mixed' WHERE protocol = 'socks'")
  770. if res.Error != nil {
  771. log.Printf("Error migrating legacy socks inbounds to mixed: %v", res.Error)
  772. return res.Error
  773. }
  774. if res.RowsAffected > 0 {
  775. log.Printf("Migrated %d legacy socks inbound(s) to mixed", res.RowsAffected)
  776. }
  777. return nil
  778. }
  779. // migrateShadowsocksRemovedCiphers rewrites shadowsocks inbounds still using
  780. // the "none"/"plain" ciphers that xray-core v26.7.11 removed; one such row
  781. // makes the whole generated config unbuildable and keeps xray from starting.
  782. func migrateShadowsocksRemovedCiphers() error {
  783. var inbounds []model.Inbound
  784. if err := db.Where("protocol = ?", model.Shadowsocks).Find(&inbounds).Error; err != nil {
  785. return err
  786. }
  787. migrated := int64(0)
  788. for _, inbound := range inbounds {
  789. if strings.TrimSpace(inbound.Settings) == "" {
  790. continue
  791. }
  792. var settings map[string]any
  793. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  794. continue
  795. }
  796. changed := false
  797. if method, _ := settings["method"].(string); method != "" {
  798. if replacement, removed := model.ReplaceRemovedShadowsocksCipher(method); removed {
  799. settings["method"] = replacement
  800. changed = true
  801. }
  802. }
  803. if clients, ok := settings["clients"].([]any); ok {
  804. for i := range clients {
  805. cm, ok := clients[i].(map[string]any)
  806. if !ok {
  807. continue
  808. }
  809. method, _ := cm["method"].(string)
  810. if replacement, removed := model.ReplaceRemovedShadowsocksCipher(method); removed {
  811. cm["method"] = replacement
  812. clients[i] = cm
  813. changed = true
  814. }
  815. }
  816. }
  817. if !changed {
  818. continue
  819. }
  820. newSettings, err := json.MarshalIndent(settings, "", " ")
  821. if err != nil {
  822. log.Printf("migrateShadowsocksRemovedCiphers: skip inbound %d (marshal failed): %v", inbound.Id, err)
  823. continue
  824. }
  825. if err := db.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
  826. Update("settings", string(newSettings)).Error; err != nil {
  827. return err
  828. }
  829. migrated++
  830. }
  831. if migrated > 0 {
  832. log.Printf("Rewrote removed shadowsocks cipher on %d inbound(s)", migrated)
  833. }
  834. return nil
  835. }
  836. // migrateVmessRemovedSecurities rewrites the vmess "none"/"zero" security
  837. // values that xray-core v26.7.11 removed to "auto" (what the core now treats
  838. // them as), on both the clients column and each vmess inbound's settings.
  839. func migrateVmessRemovedSecurities() error {
  840. res := db.Exec("UPDATE clients SET security = 'auto' WHERE security IN ('none', 'zero')")
  841. if res.Error != nil {
  842. log.Printf("Error migrating removed vmess security values on clients: %v", res.Error)
  843. return res.Error
  844. }
  845. if res.RowsAffected > 0 {
  846. log.Printf("Migrated %d client(s) off removed vmess security values", res.RowsAffected)
  847. }
  848. var inbounds []model.Inbound
  849. if err := db.Where("protocol = ?", model.VMESS).Find(&inbounds).Error; err != nil {
  850. return err
  851. }
  852. migrated := int64(0)
  853. for _, inbound := range inbounds {
  854. if strings.TrimSpace(inbound.Settings) == "" {
  855. continue
  856. }
  857. var settings map[string]any
  858. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  859. continue
  860. }
  861. clients, ok := settings["clients"].([]any)
  862. if !ok {
  863. continue
  864. }
  865. changed := false
  866. for i := range clients {
  867. cm, ok := clients[i].(map[string]any)
  868. if !ok {
  869. continue
  870. }
  871. if security, _ := cm["security"].(string); security == "none" || security == "zero" {
  872. cm["security"] = "auto"
  873. clients[i] = cm
  874. changed = true
  875. }
  876. }
  877. if !changed {
  878. continue
  879. }
  880. newSettings, err := json.MarshalIndent(settings, "", " ")
  881. if err != nil {
  882. log.Printf("migrateVmessRemovedSecurities: skip inbound %d (marshal failed): %v", inbound.Id, err)
  883. continue
  884. }
  885. if err := db.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
  886. Update("settings", string(newSettings)).Error; err != nil {
  887. return err
  888. }
  889. migrated++
  890. }
  891. if migrated > 0 {
  892. log.Printf("Rewrote removed vmess security values on %d inbound(s)", migrated)
  893. }
  894. return nil
  895. }
  896. // migrateTgIDIndex creates an index on the clients.tg_id column so that
  897. // lookups by Telegram ID do not require a full table scan. The index tag
  898. // on the struct field already causes AutoMigrate to create it on new
  899. // installations; the explicit migration ensures existing databases get it.
  900. func migrateTgIDIndex() error {
  901. if db.Migrator().HasIndex(&model.ClientRecord{}, "idx_clients_tg_id") {
  902. return nil
  903. }
  904. return db.Migrator().CreateIndex(&model.ClientRecord{}, "TgID")
  905. }
  906. // normalizeInboundSubSortIndex lifts sub_sort_index values below the 1-based
  907. // minimum (rows written by builds that defaulted the column to 0, or by nodes
  908. // predating the field) so they cannot sort ahead of explicitly ranked inbounds.
  909. func normalizeInboundSubSortIndex() error {
  910. res := db.Exec("UPDATE inbounds SET sub_sort_index = 1 WHERE sub_sort_index < 1")
  911. if res.Error != nil {
  912. log.Printf("Error normalizing inbound sub_sort_index: %v", res.Error)
  913. return res.Error
  914. }
  915. if res.RowsAffected > 0 {
  916. log.Printf("Normalized sub_sort_index on %d inbound(s)", res.RowsAffected)
  917. }
  918. return nil
  919. }
  920. // normalizeClientExternalLinkEnable keeps external-link rows written before the
  921. // enable column existed enabled; disabled rows from newer builds stay false.
  922. func normalizeClientExternalLinkEnable() error {
  923. res := db.Exec("UPDATE client_external_links SET enable = ? WHERE enable IS NULL", true)
  924. if res.Error != nil {
  925. log.Printf("Error normalizing client external link enable: %v", res.Error)
  926. return res.Error
  927. }
  928. if res.RowsAffected > 0 {
  929. log.Printf("Normalized enable on %d client external link(s)", res.RowsAffected)
  930. }
  931. return nil
  932. }
  933. // normalizeClientExternalLinkTimestamps zeroes the NULLs an older build could
  934. // leave behind, so the sub-side expiry predicate never drops a legacy row.
  935. func normalizeClientExternalLinkTimestamps() error {
  936. res := db.Exec("UPDATE client_external_links SET expiry_time = 0 WHERE expiry_time IS NULL")
  937. if res.Error != nil {
  938. log.Printf("Error normalizing client external link expiry_time: %v", res.Error)
  939. return res.Error
  940. }
  941. expiryRows := res.RowsAffected
  942. res = db.Exec("UPDATE client_external_links SET last_fetch_at = 0 WHERE last_fetch_at IS NULL")
  943. if res.Error != nil {
  944. log.Printf("Error normalizing client external link last_fetch_at: %v", res.Error)
  945. return res.Error
  946. }
  947. if expiryRows+res.RowsAffected > 0 {
  948. log.Printf("Normalized timestamps on %d client external link(s)", expiryRows+res.RowsAffected)
  949. }
  950. return nil
  951. }
  952. // repairOverflowedTrafficCounters heals traffic counters that historic
  953. // compounding bugs pushed past int64: on SQLite an overflowing INTEGER is
  954. // silently promoted to REAL, after which the column no longer scans into the
  955. // Go int64 field and every reader of the table fails (#5762). REAL cells are
  956. // cast back to INTEGER (SQLite caps the cast at math.MaxInt64), then values
  957. // are clamped into [0, TrafficMax] on both backends so the next delta cannot
  958. // overflow again.
  959. func repairOverflowedTrafficCounters() error {
  960. targets := []struct {
  961. table string
  962. columns []string
  963. }{
  964. {"client_traffics", []string{"up", "down"}},
  965. {"inbounds", []string{"up", "down"}},
  966. {"outbound_traffics", []string{"up", "down", "total"}},
  967. {"node_client_traffics", []string{"up", "down"}},
  968. }
  969. for _, target := range targets {
  970. for _, col := range target.columns {
  971. statements := []string{
  972. fmt.Sprintf("UPDATE %s SET %s = %d WHERE %s > %d", target.table, col, TrafficMax, col, TrafficMax),
  973. fmt.Sprintf("UPDATE %s SET %s = 0 WHERE %s < 0", target.table, col, col),
  974. }
  975. if !IsPostgres() {
  976. statements = append([]string{
  977. fmt.Sprintf("UPDATE %s SET %s = CAST(%s AS INTEGER) WHERE typeof(%s) = 'real'", target.table, col, col, col),
  978. }, statements...)
  979. }
  980. var repaired int64
  981. for _, statement := range statements {
  982. res := db.Exec(statement)
  983. if res.Error != nil {
  984. log.Printf("Error repairing %s.%s: %v", target.table, col, res.Error)
  985. return res.Error
  986. }
  987. repaired += res.RowsAffected
  988. }
  989. if repaired > 0 {
  990. log.Printf("Repaired %d overflowed %s.%s value(s)", repaired, target.table, col)
  991. }
  992. }
  993. }
  994. return nil
  995. }
  996. // dedupeInboundSettingsClients collapses duplicate same-email entries inside
  997. // every inbound's settings.clients array, keeping the first occurrence.
  998. // Retried or raced multi-node client adds on older builds appended the same
  999. // client several times (#5770), which the client lists then rendered as
  1000. // phantom duplicates. Runs on every start (idempotent, writes only changed
  1001. // rows) because a restored backup or a not-yet-upgraded node's snapshot can
  1002. // reintroduce duplicates.
  1003. func dedupeInboundSettingsClients() error {
  1004. var inbounds []model.Inbound
  1005. if err := db.Find(&inbounds).Error; err != nil {
  1006. return err
  1007. }
  1008. repaired := int64(0)
  1009. for _, inbound := range inbounds {
  1010. if strings.TrimSpace(inbound.Settings) == "" {
  1011. continue
  1012. }
  1013. var settings map[string]any
  1014. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1015. continue
  1016. }
  1017. clients, _ := settings["clients"].([]any)
  1018. if len(clients) < 2 {
  1019. continue
  1020. }
  1021. seen := make(map[string]struct{}, len(clients))
  1022. kept := make([]any, 0, len(clients))
  1023. for _, c := range clients {
  1024. if cm, ok := c.(map[string]any); ok {
  1025. if email, _ := cm["email"].(string); email != "" {
  1026. key := strings.ToLower(email)
  1027. if _, dup := seen[key]; dup {
  1028. continue
  1029. }
  1030. seen[key] = struct{}{}
  1031. }
  1032. }
  1033. kept = append(kept, c)
  1034. }
  1035. if len(kept) == len(clients) {
  1036. continue
  1037. }
  1038. settings["clients"] = kept
  1039. newSettings, err := json.MarshalIndent(settings, "", " ")
  1040. if err != nil {
  1041. log.Printf("dedupeInboundSettingsClients: skip inbound %d (marshal failed): %v", inbound.Id, err)
  1042. continue
  1043. }
  1044. if err := db.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
  1045. Update("settings", string(newSettings)).Error; err != nil {
  1046. return err
  1047. }
  1048. repaired++
  1049. }
  1050. if repaired > 0 {
  1051. log.Printf("Removed duplicate client entries from %d inbound(s)", repaired)
  1052. }
  1053. return nil
  1054. }
  1055. func isIgnorableDuplicateColumnErr(gdb *gorm.DB, err error, mdl any) bool {
  1056. if err == nil {
  1057. return false
  1058. }
  1059. errMsg := strings.ToLower(err.Error())
  1060. const sqlitePrefix = "duplicate column name:"
  1061. if _, after, ok := strings.Cut(errMsg, sqlitePrefix); ok {
  1062. col := strings.TrimSpace(after)
  1063. col = strings.Trim(col, "`\"[]")
  1064. return col != "" && gdb != nil && gdb.Migrator().HasColumn(mdl, col)
  1065. }
  1066. if strings.Contains(errMsg, "already exists") && strings.Contains(errMsg, "column ") {
  1067. if _, after, ok := strings.Cut(errMsg, "column \""); ok {
  1068. rest := after
  1069. if e := strings.Index(rest, "\""); e > 0 {
  1070. col := rest[:e]
  1071. return col != "" && gdb != nil && gdb.Migrator().HasColumn(mdl, col)
  1072. }
  1073. }
  1074. }
  1075. return false
  1076. }
  1077. func initUser() error {
  1078. empty, err := isTableEmpty("users")
  1079. if err != nil {
  1080. log.Printf("Error checking if users table is empty: %v", err)
  1081. return err
  1082. }
  1083. if empty {
  1084. hashedPassword, err := crypto.HashPasswordAsBcrypt(defaultPassword)
  1085. if err != nil {
  1086. log.Printf("Error hashing default password: %v", err)
  1087. return err
  1088. }
  1089. user := &model.User{
  1090. Username: defaultUsername,
  1091. Password: hashedPassword,
  1092. }
  1093. return db.Create(user).Error
  1094. }
  1095. return nil
  1096. }
  1097. func runSeeders(isUsersEmpty bool) error {
  1098. empty, err := isTableEmpty("history_of_seeders")
  1099. if err != nil {
  1100. log.Printf("Error checking if users table is empty: %v", err)
  1101. return err
  1102. }
  1103. if empty && isUsersEmpty {
  1104. seeders := []string{"UserPasswordHash", "ClientsTable", "InboundClientsArrayFix", "InboundClientTgIdFix2", "InboundClientSubIdFix", "FreedomFinalRulesReverseFix", "FreedomFinalRulesPrivateEgressBlock", "InboundRealityFinalmaskTcpStrip", "ApiTokensHash", "LegacyProxySettingsCleanup", "WireguardPeersToClients", "MtprotoSecretsToClients", "NodeInboundsAdopted", "ResetIpLimitNoFail2ban"}
  1105. for _, name := range seeders {
  1106. if err := db.Create(&model.HistoryOfSeeders{SeederName: name}).Error; err != nil {
  1107. return err
  1108. }
  1109. }
  1110. return seedApiTokens()
  1111. }
  1112. var seedersHistory []string
  1113. if err := db.Model(&model.HistoryOfSeeders{}).Pluck("seeder_name", &seedersHistory).Error; err != nil {
  1114. log.Printf("Error fetching seeder history: %v", err)
  1115. return err
  1116. }
  1117. if !slices.Contains(seedersHistory, "UserPasswordHash") && !isUsersEmpty {
  1118. var users []model.User
  1119. if err := db.Find(&users).Error; err != nil {
  1120. log.Printf("Error fetching users for password migration: %v", err)
  1121. return err
  1122. }
  1123. for _, user := range users {
  1124. if crypto.IsHashed(user.Password) {
  1125. continue
  1126. }
  1127. hashedPassword, err := crypto.HashPasswordAsBcrypt(user.Password)
  1128. if err != nil {
  1129. log.Printf("Error hashing password for user '%s': %v", user.Username, err)
  1130. return err
  1131. }
  1132. if err := db.Model(&user).Update("password", hashedPassword).Error; err != nil {
  1133. log.Printf("Error updating password for user '%s': %v", user.Username, err)
  1134. return err
  1135. }
  1136. }
  1137. hashSeeder := &model.HistoryOfSeeders{
  1138. SeederName: "UserPasswordHash",
  1139. }
  1140. if err := db.Create(hashSeeder).Error; err != nil {
  1141. return err
  1142. }
  1143. }
  1144. if !slices.Contains(seedersHistory, "ApiTokensTable") {
  1145. if err := seedApiTokens(); err != nil {
  1146. return err
  1147. }
  1148. }
  1149. if !slices.Contains(seedersHistory, "ApiTokensHash") {
  1150. if err := hashExistingApiTokens(); err != nil {
  1151. return err
  1152. }
  1153. }
  1154. if !slices.Contains(seedersHistory, "ClientsTable") {
  1155. if err := seedClientsFromInboundJSON(); err != nil {
  1156. return err
  1157. }
  1158. }
  1159. if !slices.Contains(seedersHistory, "InboundClientsArrayFix") {
  1160. if err := normalizeInboundClientsArray(); err != nil {
  1161. return err
  1162. }
  1163. }
  1164. if !slices.Contains(seedersHistory, "InboundClientTgIdFix2") {
  1165. if err := normalizeInboundClientTgId(); err != nil {
  1166. return err
  1167. }
  1168. }
  1169. if !slices.Contains(seedersHistory, "InboundClientSubIdFix") {
  1170. if err := normalizeInboundClientSubId(); err != nil {
  1171. return err
  1172. }
  1173. }
  1174. if !slices.Contains(seedersHistory, "FreedomFinalRulesReverseFix") {
  1175. if err := normalizeFreedomFinalRules(); err != nil {
  1176. return err
  1177. }
  1178. }
  1179. if !slices.Contains(seedersHistory, "FreedomFinalRulesPrivateEgressBlock") {
  1180. if err := hardenFreedomFinalRules(); err != nil {
  1181. return err
  1182. }
  1183. }
  1184. if !slices.Contains(seedersHistory, "InboundRealityFinalmaskTcpStrip") {
  1185. if err := stripRealityFinalmaskTcp(); err != nil {
  1186. return err
  1187. }
  1188. }
  1189. if !slices.Contains(seedersHistory, "LegacyProxySettingsCleanup") {
  1190. if err := clearLegacyProxySettings(); err != nil {
  1191. return err
  1192. }
  1193. }
  1194. if !slices.Contains(seedersHistory, "NodeInboundsAdopted") {
  1195. if err := seedNodeInboundsAdopted(); err != nil {
  1196. return err
  1197. }
  1198. }
  1199. if err := seedHostsFromExternalProxy(); err != nil {
  1200. return err
  1201. }
  1202. if err := resetIpLimitsWithoutFail2ban(); err != nil {
  1203. return err
  1204. }
  1205. if err := seedWireguardPeersToClients(); err != nil {
  1206. return err
  1207. }
  1208. if err := backfillEmptyHostGroupIds(); err != nil {
  1209. return err
  1210. }
  1211. // Self-gated on the "MtprotoSecretsToClients" row.
  1212. if err := seedMtprotoSecretsToClients(); err != nil {
  1213. return err
  1214. }
  1215. // Self-gated on the "StripMtprotoInboundSecrets" row. Must run after the
  1216. // seeder above so legacy single-secret inbounds are first converted to a
  1217. // client (which preserves the secret) before the inbound-level copy is
  1218. // dropped from every mtproto inbound.
  1219. if err := stripMtprotoInboundSecrets(); err != nil {
  1220. return err
  1221. }
  1222. // Idempotent, not seeder-gated: bad values can re-enter via a restored
  1223. // backup, so re-check on every start.
  1224. return normalizeSettingPaths()
  1225. }
  1226. // seedNodeInboundsAdopted keeps the pre-existing reconcile behavior for nodes
  1227. // that were already syncing before the inbounds_adopted_at gate was introduced.
  1228. func seedNodeInboundsAdopted() error {
  1229. if err := db.Model(&model.Node{}).
  1230. Where("inbounds_adopted_at = 0").
  1231. Update("inbounds_adopted_at", time.Now().Unix()).Error; err != nil {
  1232. return err
  1233. }
  1234. return db.Create(&model.HistoryOfSeeders{SeederName: "NodeInboundsAdopted"}).Error
  1235. }
  1236. // backfillEmptyHostGroupIds is idempotent and not seeder-gated: builds that
  1237. // predate group ids on the inbound-import path (and restored backups) can
  1238. // re-introduce hosts rows with an empty group_id, and such rows render as a
  1239. // synthetic fallback_<id> group the update/delete API cannot address, so
  1240. // re-check on every start.
  1241. func backfillEmptyHostGroupIds() error {
  1242. var hosts []*model.Host
  1243. if err := db.Where("group_id = '' OR group_id IS NULL").Find(&hosts).Error; err != nil {
  1244. return err
  1245. }
  1246. if len(hosts) == 0 {
  1247. return nil
  1248. }
  1249. return db.Transaction(func(tx *gorm.DB) error {
  1250. for _, h := range hosts {
  1251. if err := tx.Model(h).Update("group_id", random.NumLower(16)).Error; err != nil {
  1252. return err
  1253. }
  1254. }
  1255. return nil
  1256. })
  1257. }
  1258. func resetIpLimitsWithoutFail2ban() error {
  1259. var history []string
  1260. if err := db.Model(&model.HistoryOfSeeders{}).Pluck("seeder_name", &history).Error; err != nil {
  1261. return err
  1262. }
  1263. if slices.Contains(history, "ResetIpLimitNoFail2ban") {
  1264. return nil
  1265. }
  1266. state, probeErr := fail2banEnforcementState()
  1267. if state == fail2banEnforcing {
  1268. return db.Create(&model.HistoryOfSeeders{SeederName: "ResetIpLimitNoFail2ban"}).Error
  1269. }
  1270. if state == fail2banUnknown {
  1271. log.Printf("ResetIpLimitNoFail2ban: fail2ban-client present but not runnable (%v); keeping configured IP limits, will retry next start", probeErr)
  1272. return nil
  1273. }
  1274. var inbounds []model.Inbound
  1275. if err := db.Find(&inbounds).Error; err != nil {
  1276. return err
  1277. }
  1278. return db.Transaction(func(tx *gorm.DB) error {
  1279. for _, inbound := range inbounds {
  1280. if strings.TrimSpace(inbound.Settings) == "" {
  1281. continue
  1282. }
  1283. var settings map[string]any
  1284. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1285. log.Printf("ResetIpLimitNoFail2ban: skip inbound %d (invalid settings json): %v", inbound.Id, err)
  1286. continue
  1287. }
  1288. clients, ok := settings["clients"].([]any)
  1289. if !ok {
  1290. continue
  1291. }
  1292. mutated := false
  1293. for i, raw := range clients {
  1294. obj, ok := raw.(map[string]any)
  1295. if !ok {
  1296. continue
  1297. }
  1298. v, present := obj["limitIp"]
  1299. if !present {
  1300. continue
  1301. }
  1302. if n, isNum := v.(float64); isNum && n == 0 {
  1303. continue
  1304. }
  1305. obj["limitIp"] = 0
  1306. clients[i] = obj
  1307. mutated = true
  1308. }
  1309. if !mutated {
  1310. continue
  1311. }
  1312. settings["clients"] = clients
  1313. newSettings, err := json.MarshalIndent(settings, "", " ")
  1314. if err != nil {
  1315. log.Printf("ResetIpLimitNoFail2ban: skip inbound %d (marshal failed): %v", inbound.Id, err)
  1316. continue
  1317. }
  1318. if err := tx.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
  1319. Update("settings", string(newSettings)).Error; err != nil {
  1320. return err
  1321. }
  1322. }
  1323. if err := tx.Model(&model.ClientRecord{}).Where("limit_ip <> ?", 0).
  1324. Update("limit_ip", 0).Error; err != nil {
  1325. return err
  1326. }
  1327. return tx.Create(&model.HistoryOfSeeders{SeederName: "ResetIpLimitNoFail2ban"}).Error
  1328. })
  1329. }
  1330. type fail2banState int
  1331. const (
  1332. fail2banEnforcing fail2banState = iota
  1333. fail2banAbsent
  1334. fail2banUnknown
  1335. )
  1336. // fail2banEnforcementState separates "fail2ban is not installed" from "the probe
  1337. // itself failed", so a transient failure never drives an irreversible cleanup.
  1338. func fail2banEnforcementState() (fail2banState, error) {
  1339. if v, ok := os.LookupEnv("XUI_ENABLE_FAIL2BAN"); ok && v != "true" {
  1340. return fail2banAbsent, nil
  1341. }
  1342. if runtime.GOOS == "windows" {
  1343. return fail2banAbsent, nil
  1344. }
  1345. if _, err := exec.LookPath("fail2ban-client"); err != nil {
  1346. return fail2banAbsent, nil
  1347. }
  1348. if err := exec.CommandContext(context.Background(), "fail2ban-client", "-h").Run(); err != nil {
  1349. return fail2banUnknown, err
  1350. }
  1351. return fail2banEnforcing, nil
  1352. }
  1353. func clearLegacyProxySettings() error {
  1354. return db.Transaction(func(tx *gorm.DB) error {
  1355. if err := tx.Where("key IN ?", []string{"panelProxy", "tgBotProxy"}).
  1356. Delete(&model.Setting{}).Error; err != nil {
  1357. return err
  1358. }
  1359. return tx.Create(&model.HistoryOfSeeders{SeederName: "LegacyProxySettingsCleanup"}).Error
  1360. })
  1361. }
  1362. func normalizeSettingPaths() error {
  1363. pathKeys := []string{"webBasePath", "subPath", "subJsonPath", "subClashPath"}
  1364. var rows []model.Setting
  1365. if err := db.Where("key IN ?", pathKeys).Find(&rows).Error; err != nil {
  1366. return err
  1367. }
  1368. for _, row := range rows {
  1369. fixed := row.Value
  1370. if !strings.HasPrefix(fixed, "/") {
  1371. fixed = "/" + fixed
  1372. }
  1373. if !strings.HasSuffix(fixed, "/") {
  1374. fixed += "/"
  1375. }
  1376. if fixed == row.Value {
  1377. continue
  1378. }
  1379. if err := db.Model(&model.Setting{}).Where("id = ?", row.Id).
  1380. Update("value", fixed).Error; err != nil {
  1381. return err
  1382. }
  1383. }
  1384. return nil
  1385. }
  1386. func normalizeInboundClientTgId() error {
  1387. var inbounds []model.Inbound
  1388. if err := db.Find(&inbounds).Error; err != nil {
  1389. return err
  1390. }
  1391. return db.Transaction(func(tx *gorm.DB) error {
  1392. for _, inbound := range inbounds {
  1393. if strings.TrimSpace(inbound.Settings) == "" {
  1394. continue
  1395. }
  1396. var settings map[string]any
  1397. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1398. log.Printf("InboundClientTgIdFix: skip inbound %d (invalid settings json): %v", inbound.Id, err)
  1399. continue
  1400. }
  1401. clients, ok := settings["clients"].([]any)
  1402. if !ok {
  1403. continue
  1404. }
  1405. mutated := false
  1406. for i, raw := range clients {
  1407. obj, ok := raw.(map[string]any)
  1408. if !ok {
  1409. continue
  1410. }
  1411. tgRaw, present := obj["tgId"]
  1412. if !present {
  1413. continue
  1414. }
  1415. v, isFloat := tgRaw.(float64)
  1416. if isFloat && !math.IsNaN(v) && !math.IsInf(v, 0) && v == math.Trunc(v) {
  1417. continue
  1418. }
  1419. obj["tgId"] = int64(0)
  1420. if s, isStr := tgRaw.(string); isStr {
  1421. if id, err := strconv.ParseInt(strings.ReplaceAll(strings.TrimSpace(s), " ", ""), 10, 64); err == nil {
  1422. obj["tgId"] = id
  1423. }
  1424. }
  1425. clients[i] = obj
  1426. mutated = true
  1427. }
  1428. if !mutated {
  1429. continue
  1430. }
  1431. settings["clients"] = clients
  1432. newSettings, err := json.MarshalIndent(settings, "", " ")
  1433. if err != nil {
  1434. log.Printf("InboundClientTgIdFix: skip inbound %d (marshal failed): %v", inbound.Id, err)
  1435. continue
  1436. }
  1437. if err := tx.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
  1438. Update("settings", string(newSettings)).Error; err != nil {
  1439. return err
  1440. }
  1441. }
  1442. return tx.Create(&model.HistoryOfSeeders{SeederName: "InboundClientTgIdFix2"}).Error
  1443. })
  1444. }
  1445. func normalizeInboundClientSubId() error {
  1446. var inbounds []model.Inbound
  1447. if err := db.Find(&inbounds).Error; err != nil {
  1448. return err
  1449. }
  1450. return db.Transaction(func(tx *gorm.DB) error {
  1451. for _, inbound := range inbounds {
  1452. if strings.TrimSpace(inbound.Settings) == "" {
  1453. continue
  1454. }
  1455. var settings map[string]any
  1456. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1457. log.Printf("InboundClientSubIdFix: skip inbound %d (invalid settings json): %v", inbound.Id, err)
  1458. continue
  1459. }
  1460. clients, ok := settings["clients"].([]any)
  1461. if !ok {
  1462. continue
  1463. }
  1464. mutated := false
  1465. for i, raw := range clients {
  1466. obj, ok := raw.(map[string]any)
  1467. if !ok {
  1468. continue
  1469. }
  1470. existing, _ := obj["subId"].(string)
  1471. if strings.TrimSpace(existing) != "" {
  1472. continue
  1473. }
  1474. obj["subId"] = random.NumLower(16)
  1475. clients[i] = obj
  1476. mutated = true
  1477. }
  1478. if !mutated {
  1479. continue
  1480. }
  1481. settings["clients"] = clients
  1482. newSettings, err := json.MarshalIndent(settings, "", " ")
  1483. if err != nil {
  1484. log.Printf("InboundClientSubIdFix: skip inbound %d (marshal failed): %v", inbound.Id, err)
  1485. continue
  1486. }
  1487. if err := tx.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
  1488. Update("settings", string(newSettings)).Error; err != nil {
  1489. return err
  1490. }
  1491. }
  1492. return tx.Create(&model.HistoryOfSeeders{SeederName: "InboundClientSubIdFix"}).Error
  1493. })
  1494. }
  1495. func normalizeInboundClientsArray() error {
  1496. var inbounds []model.Inbound
  1497. if err := db.Find(&inbounds).Error; err != nil {
  1498. return err
  1499. }
  1500. return db.Transaction(func(tx *gorm.DB) error {
  1501. for _, inbound := range inbounds {
  1502. if strings.TrimSpace(inbound.Settings) == "" {
  1503. continue
  1504. }
  1505. var settings map[string]any
  1506. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1507. log.Printf("InboundClientsArrayFix: skip inbound %d (invalid settings json): %v", inbound.Id, err)
  1508. continue
  1509. }
  1510. raw, exists := settings["clients"]
  1511. if !exists || raw != nil {
  1512. continue
  1513. }
  1514. settings["clients"] = []any{}
  1515. newSettings, err := json.MarshalIndent(settings, "", " ")
  1516. if err != nil {
  1517. log.Printf("InboundClientsArrayFix: skip inbound %d (marshal failed): %v", inbound.Id, err)
  1518. continue
  1519. }
  1520. if err := tx.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
  1521. Update("settings", string(newSettings)).Error; err != nil {
  1522. return err
  1523. }
  1524. }
  1525. return tx.Create(&model.HistoryOfSeeders{SeederName: "InboundClientsArrayFix"}).Error
  1526. })
  1527. }
  1528. func normalizeFreedomFinalRules() error {
  1529. var setting model.Setting
  1530. err := db.Model(model.Setting{}).Where("key = ?", "xrayTemplateConfig").First(&setting).Error
  1531. if errors.Is(err, gorm.ErrRecordNotFound) {
  1532. return db.Create(&model.HistoryOfSeeders{SeederName: "FreedomFinalRulesReverseFix"}).Error
  1533. }
  1534. if err != nil {
  1535. return err
  1536. }
  1537. updated, changed, rErr := rewriteFreedomFinalRules(setting.Value)
  1538. if rErr != nil {
  1539. log.Printf("FreedomFinalRulesReverseFix: skip (invalid xrayTemplateConfig json): %v", rErr)
  1540. return db.Create(&model.HistoryOfSeeders{SeederName: "FreedomFinalRulesReverseFix"}).Error
  1541. }
  1542. return db.Transaction(func(tx *gorm.DB) error {
  1543. if changed {
  1544. if err := tx.Model(&model.Setting{}).Where("key = ?", "xrayTemplateConfig").
  1545. Update("value", updated).Error; err != nil {
  1546. return err
  1547. }
  1548. }
  1549. return tx.Create(&model.HistoryOfSeeders{SeederName: "FreedomFinalRulesReverseFix"}).Error
  1550. })
  1551. }
  1552. func rewriteFreedomFinalRules(raw string) (string, bool, error) {
  1553. if strings.TrimSpace(raw) == "" {
  1554. return raw, false, nil
  1555. }
  1556. var cfg map[string]any
  1557. if err := json.Unmarshal([]byte(raw), &cfg); err != nil {
  1558. return raw, false, err
  1559. }
  1560. outbounds, ok := cfg["outbounds"].([]any)
  1561. if !ok {
  1562. return raw, false, nil
  1563. }
  1564. changed := false
  1565. for _, ob := range outbounds {
  1566. obj, ok := ob.(map[string]any)
  1567. if !ok {
  1568. continue
  1569. }
  1570. if proto, _ := obj["protocol"].(string); proto != "freedom" {
  1571. continue
  1572. }
  1573. settings, ok := obj["settings"].(map[string]any)
  1574. if !ok {
  1575. continue
  1576. }
  1577. if !isLegacyPrivateOnlyFinalRules(settings["finalRules"]) {
  1578. continue
  1579. }
  1580. settings["finalRules"] = []any{map[string]any{"action": "allow"}}
  1581. changed = true
  1582. }
  1583. if !changed {
  1584. return raw, false, nil
  1585. }
  1586. out, err := json.MarshalIndent(cfg, "", " ")
  1587. if err != nil {
  1588. return raw, false, err
  1589. }
  1590. return string(out), true, nil
  1591. }
  1592. func isLegacyPrivateOnlyFinalRules(v any) bool {
  1593. rules, ok := v.([]any)
  1594. if !ok || len(rules) != 1 {
  1595. return false
  1596. }
  1597. rule, ok := rules[0].(map[string]any)
  1598. if !ok {
  1599. return false
  1600. }
  1601. if action, _ := rule["action"].(string); action != "allow" {
  1602. return false
  1603. }
  1604. ips, ok := rule["ip"].([]any)
  1605. if !ok || len(ips) != 1 {
  1606. return false
  1607. }
  1608. if s, _ := ips[0].(string); s != "geoip:private" {
  1609. return false
  1610. }
  1611. for k := range rule {
  1612. if k != "action" && k != "ip" {
  1613. return false
  1614. }
  1615. }
  1616. return true
  1617. }
  1618. func isUnrestrictedFreedomFinalRules(v any, present bool) bool {
  1619. if !present || v == nil {
  1620. return true
  1621. }
  1622. rules, ok := v.([]any)
  1623. return ok && len(rules) == 0
  1624. }
  1625. func hardenFreedomFinalRules() error {
  1626. var setting model.Setting
  1627. err := db.Model(model.Setting{}).Where("key = ?", "xrayTemplateConfig").First(&setting).Error
  1628. if errors.Is(err, gorm.ErrRecordNotFound) {
  1629. return db.Create(&model.HistoryOfSeeders{SeederName: "FreedomFinalRulesPrivateEgressBlock"}).Error
  1630. }
  1631. if err != nil {
  1632. return err
  1633. }
  1634. updated, changed, rErr := rewriteFreedomFinalRulesPrivateEgress(setting.Value)
  1635. if rErr != nil {
  1636. log.Printf("FreedomFinalRulesPrivateEgressBlock: skip (invalid xrayTemplateConfig json): %v", rErr)
  1637. return db.Create(&model.HistoryOfSeeders{SeederName: "FreedomFinalRulesPrivateEgressBlock"}).Error
  1638. }
  1639. return db.Transaction(func(tx *gorm.DB) error {
  1640. if changed {
  1641. if err := tx.Model(&model.Setting{}).Where("key = ?", "xrayTemplateConfig").
  1642. Update("value", updated).Error; err != nil {
  1643. return err
  1644. }
  1645. }
  1646. return tx.Create(&model.HistoryOfSeeders{SeederName: "FreedomFinalRulesPrivateEgressBlock"}).Error
  1647. })
  1648. }
  1649. func rewriteFreedomFinalRulesPrivateEgress(raw string) (string, bool, error) {
  1650. if strings.TrimSpace(raw) == "" {
  1651. return raw, false, nil
  1652. }
  1653. var cfg map[string]any
  1654. if err := json.Unmarshal([]byte(raw), &cfg); err != nil {
  1655. return raw, false, err
  1656. }
  1657. outbounds, ok := cfg["outbounds"].([]any)
  1658. if !ok {
  1659. return raw, false, nil
  1660. }
  1661. changed := false
  1662. for _, ob := range outbounds {
  1663. obj, ok := ob.(map[string]any)
  1664. if !ok {
  1665. continue
  1666. }
  1667. if proto, _ := obj["protocol"].(string); proto != "freedom" {
  1668. continue
  1669. }
  1670. settings, ok := obj["settings"].(map[string]any)
  1671. if !ok {
  1672. continue
  1673. }
  1674. finalRules, present := settings["finalRules"]
  1675. if !isUnrestrictedFreedomFinalRules(finalRules, present) &&
  1676. !isAllowOnlyFinalRules(finalRules) &&
  1677. !isLegacyPrivateOnlyFinalRules(finalRules) {
  1678. continue
  1679. }
  1680. settings["finalRules"] = []any{
  1681. map[string]any{"action": "block", "ip": []any{"geoip:private"}},
  1682. map[string]any{"action": "allow"},
  1683. }
  1684. changed = true
  1685. }
  1686. if !changed {
  1687. return raw, false, nil
  1688. }
  1689. out, err := json.MarshalIndent(cfg, "", " ")
  1690. if err != nil {
  1691. return raw, false, err
  1692. }
  1693. return string(out), true, nil
  1694. }
  1695. func stripRealityFinalmaskTcp() error {
  1696. var inbounds []model.Inbound
  1697. if err := db.Find(&inbounds).Error; err != nil {
  1698. return err
  1699. }
  1700. return db.Transaction(func(tx *gorm.DB) error {
  1701. for i := range inbounds {
  1702. updated, changed := stripRealityFinalmaskTcpFromStream(inbounds[i].StreamSettings)
  1703. if !changed {
  1704. continue
  1705. }
  1706. if err := tx.Model(&model.Inbound{}).Where("id = ?", inbounds[i].Id).
  1707. Update("stream_settings", updated).Error; err != nil {
  1708. return err
  1709. }
  1710. log.Printf("InboundRealityFinalmaskTcpStrip: removed finalmask.tcp from REALITY inbound %d (%s)", inbounds[i].Id, inbounds[i].Tag)
  1711. }
  1712. return tx.Create(&model.HistoryOfSeeders{SeederName: "InboundRealityFinalmaskTcpStrip"}).Error
  1713. })
  1714. }
  1715. func stripRealityFinalmaskTcpFromStream(raw string) (string, bool) {
  1716. if strings.TrimSpace(raw) == "" {
  1717. return raw, false
  1718. }
  1719. var stream map[string]any
  1720. if err := json.Unmarshal([]byte(raw), &stream); err != nil {
  1721. return raw, false
  1722. }
  1723. if sec, _ := stream["security"].(string); sec != "reality" {
  1724. return raw, false
  1725. }
  1726. finalmask, ok := stream["finalmask"].(map[string]any)
  1727. if !ok {
  1728. return raw, false
  1729. }
  1730. if tcp, _ := finalmask["tcp"].([]any); len(tcp) == 0 {
  1731. return raw, false
  1732. }
  1733. delete(finalmask, "tcp")
  1734. if len(finalmask) == 0 {
  1735. delete(stream, "finalmask")
  1736. }
  1737. out, err := json.Marshal(stream)
  1738. if err != nil {
  1739. return raw, false
  1740. }
  1741. return string(out), true
  1742. }
  1743. func isAllowOnlyFinalRules(v any) bool {
  1744. rules, ok := v.([]any)
  1745. if !ok || len(rules) != 1 {
  1746. return false
  1747. }
  1748. rule, ok := rules[0].(map[string]any)
  1749. if !ok {
  1750. return false
  1751. }
  1752. if action, _ := rule["action"].(string); action != "allow" {
  1753. return false
  1754. }
  1755. for k := range rule {
  1756. if k != "action" {
  1757. return false
  1758. }
  1759. }
  1760. return true
  1761. }
  1762. func normalizeClientJSONFields(obj map[string]any) {
  1763. normalizeInt := func(key string) {
  1764. raw, exists := obj[key]
  1765. if !exists {
  1766. return
  1767. }
  1768. s, ok := raw.(string)
  1769. if !ok {
  1770. return
  1771. }
  1772. trimmed := strings.ReplaceAll(strings.TrimSpace(s), " ", "")
  1773. if trimmed == "" {
  1774. delete(obj, key)
  1775. return
  1776. }
  1777. if n, err := strconv.ParseInt(trimmed, 10, 64); err == nil {
  1778. obj[key] = n
  1779. } else {
  1780. delete(obj, key)
  1781. }
  1782. }
  1783. for _, k := range []string{"tgId", "limitIp", "totalGB", "expiryTime", "reset", "created_at", "updated_at"} {
  1784. normalizeInt(k)
  1785. }
  1786. }
  1787. func seedClientsFromInboundJSON() error {
  1788. var inbounds []model.Inbound
  1789. if err := db.Find(&inbounds).Error; err != nil {
  1790. return err
  1791. }
  1792. return db.Transaction(func(tx *gorm.DB) error {
  1793. byEmail := map[string]*model.ClientRecord{}
  1794. var existing []model.ClientRecord
  1795. if err := tx.Find(&existing).Error; err != nil {
  1796. return err
  1797. }
  1798. for i := range existing {
  1799. byEmail[existing[i].Email] = &existing[i]
  1800. }
  1801. for _, inbound := range inbounds {
  1802. if strings.TrimSpace(inbound.Settings) == "" {
  1803. continue
  1804. }
  1805. var settings map[string]any
  1806. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1807. log.Printf("ClientsTable seed: skip inbound %d (invalid settings json): %v", inbound.Id, err)
  1808. continue
  1809. }
  1810. rawList, ok := settings["clients"].([]any)
  1811. if !ok {
  1812. continue
  1813. }
  1814. for _, raw := range rawList {
  1815. obj, ok := raw.(map[string]any)
  1816. if !ok {
  1817. continue
  1818. }
  1819. normalizeClientJSONFields(obj)
  1820. blob, err := json.Marshal(obj)
  1821. if err != nil {
  1822. continue
  1823. }
  1824. var c model.Client
  1825. if err := json.Unmarshal(blob, &c); err != nil {
  1826. log.Printf("ClientsTable seed: skip client in inbound %d (unmarshal failed): %v; payload=%s",
  1827. inbound.Id, err, string(blob))
  1828. continue
  1829. }
  1830. email := strings.TrimSpace(c.Email)
  1831. if email == "" {
  1832. continue
  1833. }
  1834. incoming := c.ToRecord()
  1835. row, dup := byEmail[email]
  1836. if !dup {
  1837. if err := tx.Create(incoming).Error; err != nil {
  1838. return err
  1839. }
  1840. byEmail[email] = incoming
  1841. row = incoming
  1842. } else {
  1843. conflicts := model.MergeClientRecord(row, incoming)
  1844. for _, x := range conflicts {
  1845. log.Printf("client merge: email=%s conflict on %s old=%v new=%v kept=%v",
  1846. email, x.Field, x.Old, x.New, x.Kept)
  1847. }
  1848. if err := tx.Save(row).Error; err != nil {
  1849. return err
  1850. }
  1851. }
  1852. link := model.ClientInbound{
  1853. ClientId: row.Id,
  1854. InboundId: inbound.Id,
  1855. FlowOverride: c.Flow,
  1856. }
  1857. if err := tx.Where("client_id = ? AND inbound_id = ?", row.Id, inbound.Id).
  1858. FirstOrCreate(&link).Error; err != nil {
  1859. return err
  1860. }
  1861. }
  1862. }
  1863. return tx.Create(&model.HistoryOfSeeders{SeederName: "ClientsTable"}).Error
  1864. })
  1865. }
  1866. func seedApiTokens() error {
  1867. empty, err := isTableEmpty("api_tokens")
  1868. if err != nil {
  1869. return err
  1870. }
  1871. if empty {
  1872. var legacy model.Setting
  1873. err := db.Model(model.Setting{}).Where("key = ?", "apiToken").First(&legacy).Error
  1874. if err == nil && legacy.Value != "" {
  1875. row := &model.ApiToken{
  1876. Name: "default",
  1877. Token: legacy.Value,
  1878. Enabled: true,
  1879. }
  1880. if err := db.Create(row).Error; err != nil {
  1881. log.Printf("Error migrating legacy apiToken: %v", err)
  1882. return err
  1883. }
  1884. }
  1885. }
  1886. return db.Create(&model.HistoryOfSeeders{SeederName: "ApiTokensTable"}).Error
  1887. }
  1888. func hashExistingApiTokens() error {
  1889. var rows []*model.ApiToken
  1890. if err := db.Find(&rows).Error; err != nil {
  1891. return err
  1892. }
  1893. for _, r := range rows {
  1894. if crypto.IsSHA256Hex(r.Token) {
  1895. continue
  1896. }
  1897. hashed := crypto.HashTokenSHA256(r.Token)
  1898. if err := db.Model(model.ApiToken{}).Where("id = ?", r.Id).Update("token", hashed).Error; err != nil {
  1899. log.Printf("Error hashing api token %d: %v", r.Id, err)
  1900. return err
  1901. }
  1902. }
  1903. return db.Create(&model.HistoryOfSeeders{SeederName: "ApiTokensHash"}).Error
  1904. }
  1905. func isTableEmpty(tableName string) (bool, error) {
  1906. var count int64
  1907. err := db.Table(tableName).Count(&count).Error
  1908. return count == 0, err
  1909. }
  1910. func InitDB(dbPath string) error {
  1911. var gormLogger logger.Interface
  1912. if config.IsDebug() {
  1913. gormLogger = logger.New(
  1914. log.New(os.Stdout, "\r\n", log.LstdFlags),
  1915. logger.Config{
  1916. SlowThreshold: time.Second,
  1917. LogLevel: logger.Info,
  1918. IgnoreRecordNotFoundError: true,
  1919. Colorful: true,
  1920. },
  1921. )
  1922. } else {
  1923. gormLogger = logger.Discard
  1924. }
  1925. c := &gorm.Config{Logger: gormLogger, DisableForeignKeyConstraintWhenMigrating: true}
  1926. var err error
  1927. switch config.GetDBKind() {
  1928. case "postgres":
  1929. dsn := config.GetDBDSN()
  1930. if dsn == "" {
  1931. return errors.New("XUI_DB_TYPE=postgres but XUI_DB_DSN is empty")
  1932. }
  1933. db, err = openPostgresWithRetry(dsn, c)
  1934. if err != nil {
  1935. return err
  1936. }
  1937. default:
  1938. dir := path.Dir(dbPath)
  1939. if err = os.MkdirAll(dir, 0o755); err != nil {
  1940. return err
  1941. }
  1942. if err = cleanupSQLiteBackupDirs(filepath.Dir(dbPath)); err != nil {
  1943. log.Printf("clean SQLite backup directories: %v", err)
  1944. }
  1945. sync := sqliteSynchronous()
  1946. journal := sqliteJournalMode()
  1947. dsn := dbPath + "?_journal_mode=" + journal + "&_busy_timeout=10000&_synchronous=" + sync + "&_txlock=immediate"
  1948. db, err = gorm.Open(sqlite.Open(dsn), c)
  1949. if err != nil {
  1950. return err
  1951. }
  1952. sqlDB, err := db.DB()
  1953. if err != nil {
  1954. return err
  1955. }
  1956. pragmas := []string{
  1957. "PRAGMA journal_mode=" + journal,
  1958. "PRAGMA busy_timeout=10000",
  1959. "PRAGMA synchronous=" + sync,
  1960. fmt.Sprintf("PRAGMA cache_size=-%d", envInt("XUI_DB_CACHE_MB", 32)*1024),
  1961. fmt.Sprintf("PRAGMA mmap_size=%d", int64(envInt("XUI_DB_MMAP_MB", 256))*1024*1024),
  1962. "PRAGMA temp_store=MEMORY",
  1963. }
  1964. for _, p := range pragmas {
  1965. if _, err := sqlDB.ExecContext(context.Background(), p); err != nil {
  1966. return err
  1967. }
  1968. }
  1969. }
  1970. sqlDB, err := db.DB()
  1971. if err != nil {
  1972. return err
  1973. }
  1974. var maxOpen, maxIdle int
  1975. switch config.GetDBKind() {
  1976. case "postgres":
  1977. maxOpen = envInt("XUI_DB_MAX_OPEN_CONNS", 25)
  1978. maxIdle = envInt("XUI_DB_MAX_IDLE_CONNS", 25)
  1979. default:
  1980. maxOpen = envInt("XUI_DB_MAX_OPEN_CONNS", 8)
  1981. maxIdle = envInt("XUI_DB_MAX_IDLE_CONNS", 4)
  1982. }
  1983. sqlDB.SetMaxOpenConns(maxOpen)
  1984. sqlDB.SetMaxIdleConns(maxIdle)
  1985. sqlDB.SetConnMaxLifetime(time.Hour)
  1986. sqlDB.SetConnMaxIdleTime(30 * time.Minute)
  1987. if err := initModels(); err != nil {
  1988. return err
  1989. }
  1990. isUsersEmpty, err := isTableEmpty("users")
  1991. if err != nil {
  1992. return err
  1993. }
  1994. if err := initUser(); err != nil {
  1995. return err
  1996. }
  1997. return runSeeders(isUsersEmpty)
  1998. }
  1999. func normalizeApiTokenCreatedAtSeconds() error {
  2000. return db.Model(&model.ApiToken{}).
  2001. Where("created_at >= ?", model.ApiTokenUnixMillisecondsThreshold).
  2002. UpdateColumn("created_at", gorm.Expr("created_at / ?", 1000)).Error
  2003. }
  2004. func migrateApiTokenScopeAndExpiry() error {
  2005. m := db.Migrator()
  2006. if !m.HasColumn(&model.ApiToken{}, "Scope") {
  2007. if err := m.AddColumn(&model.ApiToken{}, "Scope"); err != nil {
  2008. return err
  2009. }
  2010. }
  2011. if !m.HasColumn(&model.ApiToken{}, "ExpiresAt") {
  2012. if err := m.AddColumn(&model.ApiToken{}, "ExpiresAt"); err != nil {
  2013. return err
  2014. }
  2015. }
  2016. return db.Model(&model.ApiToken{}).Where("scope IS NULL OR TRIM(scope) = ''").
  2017. Updates(map[string]any{"scope": model.ApiScopeAdmin, "expires_at": 0}).Error
  2018. }
  2019. // openPostgresWithRetry retries the initial PostgreSQL connection with
  2020. // backoff so a database that starts slower than the panel (or drops out
  2021. // briefly) does not immediately kill the process and trip systemd's
  2022. // restart loop. Every failed attempt logs the real driver error, which
  2023. // used to be buried behind a generic startup failure.
  2024. func openPostgresWithRetry(dsn string, c *gorm.Config) (*gorm.DB, error) {
  2025. delays := []time.Duration{0, 2 * time.Second, 5 * time.Second, 10 * time.Second, 20 * time.Second, 30 * time.Second}
  2026. var lastErr error
  2027. for i, delay := range delays {
  2028. if delay > 0 {
  2029. time.Sleep(delay)
  2030. }
  2031. conn, err := gorm.Open(postgres.Open(dsn), c)
  2032. if err == nil {
  2033. if i > 0 {
  2034. log.Printf("postgres connection established on attempt %d/%d", i+1, len(delays))
  2035. }
  2036. return conn, nil
  2037. }
  2038. lastErr = err
  2039. log.Printf("postgres connection attempt %d/%d failed: %v", i+1, len(delays), err)
  2040. }
  2041. return nil, fmt.Errorf("postgres unreachable after %d attempts: %w", len(delays), lastErr)
  2042. }
  2043. func sqliteJournalMode() string {
  2044. switch strings.ToUpper(strings.TrimSpace(os.Getenv("XUI_DB_JOURNAL_MODE"))) {
  2045. case "DELETE":
  2046. return "DELETE"
  2047. default:
  2048. return "WAL"
  2049. }
  2050. }
  2051. func backupSQLiteStepPages() int {
  2052. if sqliteJournalMode() == "DELETE" {
  2053. return 128
  2054. }
  2055. return -1
  2056. }
  2057. func cleanupSQLiteBackupDirs(dir string) error {
  2058. entries, err := os.ReadDir(dir)
  2059. if errors.Is(err, os.ErrNotExist) {
  2060. return nil
  2061. }
  2062. if err != nil {
  2063. return err
  2064. }
  2065. for _, entry := range entries {
  2066. if entry.IsDir() && strings.HasPrefix(entry.Name(), sqliteBackupDirPrefix) {
  2067. if err := os.RemoveAll(filepath.Join(dir, entry.Name())); err != nil {
  2068. return err
  2069. }
  2070. }
  2071. }
  2072. return nil
  2073. }
  2074. func sqliteSynchronous() string {
  2075. switch strings.ToUpper(strings.TrimSpace(os.Getenv("XUI_DB_SYNCHRONOUS"))) {
  2076. case "OFF":
  2077. return "OFF"
  2078. case "NORMAL":
  2079. return "NORMAL"
  2080. case "EXTRA":
  2081. return "EXTRA"
  2082. default:
  2083. return "FULL"
  2084. }
  2085. }
  2086. func envInt(key string, def int) int {
  2087. v := strings.TrimSpace(os.Getenv(key))
  2088. if v == "" {
  2089. return def
  2090. }
  2091. n, err := strconv.Atoi(v)
  2092. if err != nil || n <= 0 {
  2093. return def
  2094. }
  2095. return n
  2096. }
  2097. func CloseDB() error {
  2098. if db != nil {
  2099. sqlDB, err := db.DB()
  2100. if err != nil {
  2101. return err
  2102. }
  2103. return sqlDB.Close()
  2104. }
  2105. return nil
  2106. }
  2107. func GetDB() *gorm.DB {
  2108. return db
  2109. }
  2110. func IsNotFound(err error) bool {
  2111. return errors.Is(err, gorm.ErrRecordNotFound)
  2112. }
  2113. func IsSQLiteDB(file io.ReaderAt) (bool, error) {
  2114. signature := []byte("SQLite format 3\x00")
  2115. buf := make([]byte, len(signature))
  2116. _, err := file.ReadAt(buf, 0)
  2117. if err != nil {
  2118. return false, err
  2119. }
  2120. return bytes.Equal(buf, signature), nil
  2121. }
  2122. func BackupSQLite(dstPath string) (err error) {
  2123. if IsPostgres() {
  2124. return errors.New("sqlite backup is unavailable for PostgreSQL")
  2125. }
  2126. if db == nil {
  2127. return errors.New("database is not initialized")
  2128. }
  2129. if _, err := os.Lstat(dstPath); err == nil {
  2130. return fmt.Errorf("sqlite backup destination already exists: %s", dstPath)
  2131. } else if !errors.Is(err, os.ErrNotExist) {
  2132. return err
  2133. }
  2134. defer func() {
  2135. if err != nil {
  2136. _ = os.Remove(dstPath)
  2137. }
  2138. }()
  2139. ctx, cancel := context.WithTimeout(context.Background(), backupSQLiteTimeout)
  2140. defer cancel()
  2141. sourceDB, err := db.DB()
  2142. if err != nil {
  2143. return err
  2144. }
  2145. sourceConn, err := sourceDB.Conn(ctx)
  2146. if err != nil {
  2147. return err
  2148. }
  2149. defer sourceConn.Close()
  2150. destinationDB, err := sql.Open("sqlite3", dstPath)
  2151. if err != nil {
  2152. return err
  2153. }
  2154. defer destinationDB.Close()
  2155. destinationConn, err := destinationDB.Conn(ctx)
  2156. if err != nil {
  2157. return err
  2158. }
  2159. defer destinationConn.Close()
  2160. return sourceConn.Raw(func(sourceDriver any) error {
  2161. source, ok := sourceDriver.(*sqlite3.SQLiteConn)
  2162. if !ok {
  2163. return fmt.Errorf("unexpected SQLite source connection type %T", sourceDriver)
  2164. }
  2165. return destinationConn.Raw(func(destinationDriver any) error {
  2166. destination, ok := destinationDriver.(*sqlite3.SQLiteConn)
  2167. if !ok {
  2168. return fmt.Errorf("unexpected SQLite destination connection type %T", destinationDriver)
  2169. }
  2170. backup, err := destination.Backup("main", source, "main")
  2171. if err != nil {
  2172. return err
  2173. }
  2174. finished := false
  2175. defer func() {
  2176. if !finished {
  2177. _ = backup.Finish()
  2178. }
  2179. }()
  2180. for {
  2181. done, err := backup.Step(backupSQLiteStepPages())
  2182. if err != nil {
  2183. return err
  2184. }
  2185. if done {
  2186. finished = true
  2187. return backup.Finish()
  2188. }
  2189. select {
  2190. case <-ctx.Done():
  2191. return ctx.Err()
  2192. case <-time.After(10 * time.Millisecond):
  2193. }
  2194. }
  2195. })
  2196. })
  2197. }
  2198. func ValidateSQLiteDB(dbPath string) error {
  2199. if _, err := os.Stat(dbPath); err != nil {
  2200. return err
  2201. }
  2202. gdb, err := gorm.Open(sqlite.Open(dbPath), &gorm.Config{Logger: logger.Discard})
  2203. if err != nil {
  2204. return err
  2205. }
  2206. sqlDB, err := gdb.DB()
  2207. if err != nil {
  2208. return err
  2209. }
  2210. defer sqlDB.Close()
  2211. var res string
  2212. if err := gdb.Raw("PRAGMA integrity_check;").Scan(&res).Error; err != nil {
  2213. return err
  2214. }
  2215. if res != "ok" {
  2216. return errors.New("sqlite integrity check failed: " + res)
  2217. }
  2218. return nil
  2219. }