1
0

db.go 82 KB

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