service.go 98 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142
  1. package sub
  2. import (
  3. "crypto/sha256"
  4. "encoding/base64"
  5. "encoding/hex"
  6. "fmt"
  7. "maps"
  8. "net"
  9. "net/url"
  10. "slices"
  11. "sort"
  12. "strconv"
  13. "strings"
  14. "sync"
  15. "time"
  16. "github.com/gin-gonic/gin"
  17. "github.com/goccy/go-json"
  18. "github.com/mhsanaei/3x-ui/v3/internal/amneziawg"
  19. "github.com/mhsanaei/3x-ui/v3/internal/database"
  20. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  21. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  22. "github.com/mhsanaei/3x-ui/v3/internal/tuic"
  23. "github.com/mhsanaei/3x-ui/v3/internal/util/common"
  24. "github.com/mhsanaei/3x-ui/v3/internal/util/random"
  25. wgutil "github.com/mhsanaei/3x-ui/v3/internal/util/wireguard"
  26. "github.com/mhsanaei/3x-ui/v3/internal/web/service"
  27. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  28. )
  29. var salamanderWarningSeen sync.Map
  30. // SubService provides business logic for generating subscription links and managing subscription data.
  31. type SubService struct {
  32. address string
  33. remarkTemplate string
  34. datepicker string
  35. // subscriptionBody is true only when rendering the actual subscription
  36. // content a client app imports (raw /sub fetch, /json, /clash). The remark
  37. // template's per-client info is emitted there (on the first link); every
  38. // other context — the sub info page, the panel's link/QR displays — renders
  39. // the name-only template, like Remnawave.
  40. subscriptionBody bool
  41. // usageShown emits info once per subscription identity, including twins.
  42. // PrepareForRequest resets this per-request state.
  43. usageShown map[string]bool
  44. showIdentityOnAllLinks bool
  45. subInfoNodeEnable bool
  46. subExpiredTemplate string
  47. subTrafficDepletedTemplate string
  48. inboundService service.InboundService
  49. settingService service.SettingService
  50. // nodesByID is populated per request from the Node table so
  51. // resolveInboundAddress can return the node's address for any
  52. // inbound whose NodeID is set. Keeps the per-link host derivation
  53. // O(1) instead of O(N) DB hits.
  54. nodesByID map[int]*model.Node
  55. // statsByEmail maps a client email to its traffic row across ALL inbounds
  56. // loaded for the request. client_traffics.email is globally unique, so this
  57. // lets statsForClient resolve usage for a client even on an inbound that
  58. // doesn't own its row (multi-inbound subscriptions). Filled in
  59. // getInboundsBySubId; reset per request in PrepareForRequest.
  60. statsByEmail map[string]xray.ClientTraffic
  61. // clientsByInbound caches clients resolved for this request keyed by
  62. // inbound id then email, so the per-protocol link generators look a client
  63. // up without re-parsing the inbound's settings JSON per link.
  64. // fullyPrimedInbounds marks inbounds whose complete client list is cached
  65. // (a miss there is authoritative). Reset per request in PrepareForRequest.
  66. clientsByInbound map[int]map[string]model.Client
  67. fullyPrimedInbounds map[int]bool
  68. // settingsByInbound caches each inbound's settings decoded once per request
  69. // with the clients array left out; generators read only inbound-level
  70. // fields (encryption, method, version, …) from it.
  71. settingsByInbound map[int]map[string]any
  72. }
  73. // NewSubService creates a new subscription service with the given configuration.
  74. func NewSubService(remarkTemplate string) *SubService {
  75. return &SubService{
  76. remarkTemplate: remarkTemplate,
  77. }
  78. }
  79. // ForRequest returns a shallow copy with request-scoped state populated.
  80. // Subscription controllers share one base SubService, so request-specific
  81. // fields such as address and nodesByID must live on a per-request copy.
  82. func (s *SubService) ForRequest(host string) *SubService {
  83. req := *s
  84. req.PrepareForRequest(host)
  85. return &req
  86. }
  87. // PrepareForRequest sets per-request state (host + nodes map) on this
  88. // SubService instance. HTTP handlers should call ForRequest instead so the
  89. // controller's shared base service is never mutated by concurrent requests.
  90. func (s *SubService) PrepareForRequest(host string) {
  91. if !isRoutableHost(host) {
  92. if d := s.configuredPublicHost(); d != "" {
  93. host = d
  94. } else if isLoopbackHost(host) {
  95. host = "localhost"
  96. }
  97. }
  98. s.address = host
  99. s.usageShown = map[string]bool{}
  100. s.statsByEmail = map[string]xray.ClientTraffic{}
  101. s.clientsByInbound = map[int]map[string]model.Client{}
  102. s.fullyPrimedInbounds = map[int]bool{}
  103. s.settingsByInbound = map[int]map[string]any{}
  104. s.loadNodes()
  105. s.loadRemarkSettings()
  106. }
  107. // primeLinkClients caches clients (first occurrence per email, matching the
  108. // old settings-JSON iteration order) so clientForLink resolves them without a
  109. // parse. complete marks the inbound's whole client list as cached.
  110. func (s *SubService) primeLinkClients(inboundId int, clients []model.Client, complete bool) {
  111. if inboundId <= 0 {
  112. return
  113. }
  114. if s.clientsByInbound == nil {
  115. s.clientsByInbound = map[int]map[string]model.Client{}
  116. }
  117. m := s.clientsByInbound[inboundId]
  118. if m == nil {
  119. m = make(map[string]model.Client, len(clients))
  120. s.clientsByInbound[inboundId] = m
  121. }
  122. for _, c := range clients {
  123. if _, exists := m[c.Email]; !exists {
  124. m[c.Email] = c
  125. }
  126. }
  127. if complete {
  128. if s.fullyPrimedInbounds == nil {
  129. s.fullyPrimedInbounds = map[int]bool{}
  130. }
  131. s.fullyPrimedInbounds[inboundId] = true
  132. }
  133. }
  134. // clientForLink resolves one client of an inbound by email for link
  135. // generation: from the per-request cache when primed, otherwise via
  136. // clientsForLinkExport (clients-table UUID identity with settings-JSON
  137. // fallback for share-link protocols; settings JSON for WireGuard/AmneziaWG
  138. // tunnel fields) and caches the list.
  139. func (s *SubService) clientForLink(inbound *model.Inbound, email string) (model.Client, bool) {
  140. if m, ok := s.clientsByInbound[inbound.Id]; ok {
  141. if c, hit := m[email]; hit {
  142. return c, true
  143. }
  144. if s.fullyPrimedInbounds[inbound.Id] {
  145. return model.Client{}, false
  146. }
  147. }
  148. clients, err := s.clientsForLinkExport(inbound)
  149. if err != nil {
  150. return model.Client{}, false
  151. }
  152. s.primeLinkClients(inbound.Id, clients, true)
  153. for i := range clients {
  154. if clients[i].Email == email {
  155. return clients[i], true
  156. }
  157. }
  158. return model.Client{}, false
  159. }
  160. // clientsForLinkExport returns the clients used to build share / QR / allLinks
  161. // exports for one inbound. UUID-bearing protocols prefer the normalized clients
  162. // table so the link matches the running Xray identity when settings JSON is
  163. // stale (#6436). When that list is empty or unavailable (settings-only inbounds,
  164. // unsynced rows, unit tests without a DB), fall back to GetClients so links
  165. // still generate from the embedded settings JSON (#6458). WireGuard and
  166. // AmneziaWG always keep the inbound's own settings JSON: private key,
  167. // AllowedIPs, and related tunnel fields are deliberately per-inbound there,
  168. // while the shared clients.wg_* columns collapse to whichever tunnel inbound
  169. // synced last (see TunnelAllowedIPsByInbound / amneziaWGClientAddresses).
  170. func (s *SubService) clientsForLinkExport(inbound *model.Inbound) ([]model.Client, error) {
  171. if inbound.Protocol == model.WireGuard || inbound.Protocol == model.AmneziaWG {
  172. return s.inboundService.GetClients(inbound)
  173. }
  174. if database.GetDB() != nil {
  175. clients, err := s.inboundService.ListClientsForInbound(inbound.Id)
  176. if err == nil && len(clients) > 0 {
  177. return clients, nil
  178. }
  179. }
  180. return s.inboundService.GetClients(inbound)
  181. }
  182. // linkSettings returns the inbound's settings decoded once per request with
  183. // the clients array left out — the link generators read only inbound-level
  184. // fields from it and resolve clients via clientForLink. The shallow
  185. // RawMessage pass skips materializing a huge clients array entirely.
  186. func (s *SubService) linkSettings(inbound *model.Inbound) map[string]any {
  187. if inbound.Id > 0 {
  188. if cached, ok := s.settingsByInbound[inbound.Id]; ok {
  189. return cached
  190. }
  191. }
  192. shallow := map[string]json.RawMessage{}
  193. _ = json.Unmarshal([]byte(inbound.Settings), &shallow)
  194. out := make(map[string]any, len(shallow))
  195. for key, raw := range shallow {
  196. if key == "clients" {
  197. continue
  198. }
  199. var value any
  200. _ = json.Unmarshal(raw, &value)
  201. out[key] = value
  202. }
  203. if inbound.Id > 0 {
  204. if s.settingsByInbound == nil {
  205. s.settingsByInbound = map[int]map[string]any{}
  206. }
  207. s.settingsByInbound[inbound.Id] = out
  208. }
  209. return out
  210. }
  211. // loadRemarkSettings populates the per-request remark formatting state so
  212. // every subscription format — raw, JSON, Clash — renders remarks the same way
  213. // (the date formatter reads datepicker). Loading it only in getSubs left
  214. // JSON/Clash with the zero value.
  215. func (s *SubService) loadRemarkSettings() {
  216. if s.datepicker == "" {
  217. s.datepicker = "gregorian"
  218. }
  219. if s.subExpiredTemplate == "" {
  220. s.subExpiredTemplate = service.DefaultSubExpiredTemplate
  221. }
  222. if s.subTrafficDepletedTemplate == "" {
  223. s.subTrafficDepletedTemplate = service.DefaultSubTrafficDepletedTemplate
  224. }
  225. if datepicker, err := s.settingService.GetDatepicker(); err == nil && datepicker != "" {
  226. s.datepicker = datepicker
  227. }
  228. if enabled, err := s.settingService.GetSubShowIdentityOnAllLinks(); err == nil && enabled {
  229. s.showIdentityOnAllLinks = enabled
  230. }
  231. if enabled, err := s.settingService.GetSubInfoNodeEnable(); err == nil && enabled {
  232. s.subInfoNodeEnable = enabled
  233. }
  234. if tmpl, err := s.settingService.GetSubExpiredTemplate(); err == nil && tmpl != "" {
  235. s.subExpiredTemplate = tmpl
  236. }
  237. if tmpl, err := s.settingService.GetSubTrafficDepletedTemplate(); err == nil && tmpl != "" {
  238. s.subTrafficDepletedTemplate = tmpl
  239. }
  240. }
  241. func (s *SubService) configuredPublicHost() string {
  242. if d, err := s.settingService.GetSubDomain(); err == nil && d != "" {
  243. return d
  244. }
  245. if d, err := s.settingService.GetWebDomain(); err == nil && d != "" {
  246. return d
  247. }
  248. return ""
  249. }
  250. func isRoutableHost(host string) bool {
  251. if host == "" {
  252. return false
  253. }
  254. if ip := net.ParseIP(strings.Trim(host, "[]")); ip != nil {
  255. return !ip.IsLoopback() && !ip.IsUnspecified()
  256. }
  257. return true
  258. }
  259. func isLoopbackHost(host string) bool {
  260. ip := net.ParseIP(strings.Trim(host, "[]"))
  261. return ip != nil && ip.IsLoopback()
  262. }
  263. // listenIsInternalOnly reports whether a bind address is reachable only from
  264. // the same host — a loopback IP or a unix-domain socket. Such an inbound can't
  265. // be dialed directly by a remote client, so when it is the child side of a
  266. // fallback its share link must be projected through the master. A public or
  267. // wildcard listen (""/0.0.0.0/::) is reachable on its own port and advertises
  268. // itself.
  269. func listenIsInternalOnly(listen string) bool {
  270. if listen == "" {
  271. return false
  272. }
  273. if listen[0] == '@' || listen[0] == '/' {
  274. return true
  275. }
  276. return isLoopbackHost(listen)
  277. }
  278. // matchingClients returns the inbound's clients whose SubID equals subId,
  279. // resolved from the normalized clients/client_inbounds tables (both filter
  280. // columns indexed) instead of parsing the settings JSON — at large client
  281. // counts that parse made every subscription fetch cost seconds. The
  282. // case-insensitive email dedupe stays as cheap insurance even though
  283. // clients.email is unique, preserving the #5134 guarantee that duplicate
  284. // settings entries never fan out into duplicate profiles. Resolved clients
  285. // are primed into the per-request cache so the link generators don't parse
  286. // settings either.
  287. func (s *SubService) matchingClients(inbound *model.Inbound, subId string) []model.Client {
  288. clients, err := s.inboundService.GetClientsBySubId(inbound.Id, subId)
  289. if err != nil {
  290. logger.Error("SubService - GetClientsBySubId: Unable to get clients from inbound")
  291. return nil
  292. }
  293. var out []model.Client
  294. seen := make(map[string]struct{}, len(clients))
  295. for _, client := range clients {
  296. key := strings.ToLower(client.Email)
  297. if _, dup := seen[key]; dup {
  298. continue
  299. }
  300. seen[key] = struct{}{}
  301. out = append(out, client)
  302. }
  303. s.primeLinkClients(inbound.Id, out, false)
  304. return out
  305. }
  306. // RecordSubscriptionFetch records a successful subscription response for all clients sharing subId.
  307. func (s *SubService) RecordSubscriptionFetch(subId string) error {
  308. if strings.TrimSpace(subId) == "" {
  309. return nil
  310. }
  311. return database.GetDB().Model(&xray.ClientTraffic{}).
  312. Where("email IN (SELECT email FROM clients WHERE sub_id = ?)", subId).
  313. Update("last_sub_fetch", time.Now().UnixMilli()).Error
  314. }
  315. // GetSubs retrieves subscription links for a given subscription ID and host.
  316. func (s *SubService) GetSubs(subId string, host string) ([]string, []string, int64, xray.ClientTraffic, error) {
  317. return s.ForRequest(host).getSubs(subId)
  318. }
  319. type infoNodeMode int
  320. const (
  321. infoNodeNone infoNodeMode = iota
  322. infoNodeActive
  323. infoNodeExpired
  324. infoNodeDepleted
  325. )
  326. func (s *SubService) resolveInfoNodeRemark(subId string, uniqueEmails []string, traffic xray.ClientTraffic, hasEntries bool) (infoNodeMode, string) {
  327. if !s.subInfoNodeEnable || !s.subscriptionBody {
  328. return infoNodeNone, ""
  329. }
  330. nowSec := time.Now().Unix()
  331. isExpired := traffic.ExpiryTime > 0 && traffic.ExpiryTime/1000 <= nowSec
  332. isDepleted := traffic.Total > 0 && (traffic.Up+traffic.Down) >= traffic.Total
  333. primaryEmail := ""
  334. if len(uniqueEmails) > 0 {
  335. primaryEmail = uniqueEmails[0]
  336. }
  337. ctx := remarkContext{
  338. client: model.Client{Email: primaryEmail, SubID: subId},
  339. stats: traffic,
  340. }
  341. if isExpired {
  342. tmpl := s.subExpiredTemplate
  343. if tmpl == "" {
  344. tmpl = service.DefaultSubExpiredTemplate
  345. }
  346. remark := expandRemarkVars(tmpl, ctx)
  347. if strings.TrimSpace(remark) == "" {
  348. remark = "Expired"
  349. }
  350. return infoNodeExpired, remark
  351. }
  352. if isDepleted {
  353. tmpl := s.subTrafficDepletedTemplate
  354. if tmpl == "" {
  355. tmpl = service.DefaultSubTrafficDepletedTemplate
  356. }
  357. remark := expandRemarkVars(tmpl, ctx)
  358. if strings.TrimSpace(remark) == "" {
  359. remark = "Traffic Depleted"
  360. }
  361. return infoNodeDepleted, remark
  362. }
  363. if hasEntries {
  364. tmpl := s.remarkTemplate
  365. if tmpl == "" {
  366. tmpl = service.DefaultRemarkTemplate
  367. }
  368. remark := expandRemarkVars(tmpl, ctx)
  369. if strings.TrimSpace(remark) != "" {
  370. return infoNodeActive, remark
  371. }
  372. }
  373. return infoNodeNone, ""
  374. }
  375. func (s *SubService) getSubs(subId string) ([]string, []string, int64, xray.ClientTraffic, error) {
  376. var result []string
  377. var emails []string
  378. var traffic xray.ClientTraffic
  379. var hasEnabledClient bool
  380. inbounds, err := s.getInboundsBySubId(subId)
  381. if err != nil {
  382. return nil, nil, 0, traffic, err
  383. }
  384. externalLinks, err := s.getClientExternalLinksBySubId(subId)
  385. if err != nil {
  386. return nil, nil, 0, traffic, err
  387. }
  388. if len(inbounds) == 0 && len(externalLinks) == 0 {
  389. return nil, nil, 0, traffic, nil
  390. }
  391. seenEmails := make(map[string]struct{})
  392. for _, inbound := range inbounds {
  393. clients := s.matchingClients(inbound, subId)
  394. if len(clients) == 0 {
  395. continue
  396. }
  397. s.projectThroughFallbackMaster(inbound)
  398. // Host overrides apply AFTER fallback projection so a host's
  399. // address/TLS wins over the projected master stream.
  400. hostEps := s.hostEndpoints(inbound, "raw")
  401. for _, client := range clients {
  402. if client.Enable {
  403. hasEnabledClient = true
  404. }
  405. var link string
  406. if len(hostEps) > 0 {
  407. link = s.linkFromHosts(inbound, client, hostEps)
  408. } else {
  409. link = s.GetLink(inbound, client.Email)
  410. }
  411. result = append(result, link)
  412. emails = append(emails, client.Email)
  413. seenEmails[client.Email] = struct{}{}
  414. }
  415. }
  416. for _, ext := range externalLinks {
  417. if ext.Enable {
  418. hasEnabledClient = true
  419. }
  420. if !ext.Active {
  421. seenEmails[ext.Email] = struct{}{}
  422. if result == nil {
  423. result = []string{}
  424. }
  425. continue
  426. }
  427. for _, el := range expandEntry(ext) {
  428. if link := applyRemarkToLink(el.Link, el.Name); link != "" {
  429. result = append(result, link)
  430. emails = append(emails, ext.Email)
  431. seenEmails[ext.Email] = struct{}{}
  432. }
  433. }
  434. }
  435. uniqueEmails := make([]string, 0, len(seenEmails))
  436. for e := range seenEmails {
  437. uniqueEmails = append(uniqueEmails, e)
  438. }
  439. slices.Sort(uniqueEmails)
  440. traffic, lastOnline := s.AggregateTrafficByEmails(uniqueEmails)
  441. traffic.Enable = hasEnabledClient
  442. if mode, remark := s.resolveInfoNodeRemark(subId, uniqueEmails, traffic, len(result) > 0); mode != infoNodeNone {
  443. dummyLink := fmt.Sprintf("socks://127.0.0.1:1080#%s", strings.ReplaceAll(url.QueryEscape(remark), "+", "%20"))
  444. if mode == infoNodeExpired || mode == infoNodeDepleted {
  445. return []string{dummyLink}, emails, lastOnline, traffic, nil
  446. }
  447. result = append([]string{dummyLink}, result...)
  448. }
  449. return result, emails, lastOnline, traffic, nil
  450. }
  451. // inboundLinks builds the share links for every distinct client of one inbound
  452. // the same way getSubs does — managed Host endpoints win over the plain link so
  453. // {{HOST}} and per-host variants render — but across all clients rather than a
  454. // single subId. Resolves clients via clientsForLinkExport so UUID-bearing
  455. // protocols match the running Xray config (#6436) while WireGuard/AmneziaWG
  456. // keep per-inbound tunnel identity from settings. Dedups by email (#5134).
  457. // Backs the panel's "Export all inbound links" and matches client/QR pages.
  458. func (s *SubService) inboundLinks(inbound *model.Inbound) []string {
  459. clients, err := s.clientsForLinkExport(inbound)
  460. if err != nil {
  461. return nil
  462. }
  463. s.primeLinkClients(inbound.Id, clients, true)
  464. s.projectThroughFallbackMaster(inbound)
  465. hostEps := s.hostEndpoints(inbound, "raw")
  466. var out []string
  467. seen := make(map[string]struct{}, len(clients))
  468. for _, client := range clients {
  469. key := strings.ToLower(client.Email)
  470. if _, dup := seen[key]; dup {
  471. continue
  472. }
  473. seen[key] = struct{}{}
  474. var link string
  475. if len(hostEps) > 0 {
  476. link = s.linkFromHosts(inbound, client, hostEps)
  477. } else {
  478. link = s.GetLink(inbound, client.Email)
  479. }
  480. out = append(out, splitLinkLines(link)...)
  481. }
  482. return out
  483. }
  484. // AggregateTrafficByEmails resolves traffic for every email in one
  485. // query and folds the rows into a single ClientTraffic + lastOnline.
  486. // xray.ClientTraffic.Email is globally unique, so a multi-inbound
  487. // client's single row is attached to exactly one inbound — iterating
  488. // per-inbound ClientStats would miss it on the others. Used by GetSubs,
  489. // SubClashService.GetClash, and SubJsonService.GetJson to keep the
  490. // sub-info header consistent across all three formats.
  491. func (s *SubService) AggregateTrafficByEmails(emails []string) (xray.ClientTraffic, int64) {
  492. var agg xray.ClientTraffic
  493. var lastOnline int64
  494. if len(emails) == 0 {
  495. return agg, 0
  496. }
  497. db := database.GetDB()
  498. var rows []xray.ClientTraffic
  499. if err := db.
  500. Model(&xray.ClientTraffic{}).
  501. Where("email IN ?", emails).
  502. Find(&rows).Error; err != nil {
  503. logger.Warning("SubService - AggregateTrafficByEmails: load by email:", err)
  504. return agg, 0
  505. }
  506. // total/expiry are configured limits owned by the clients table, not the
  507. // runtime traffic rows. In a multi-node setup the node snapshot can reset
  508. // client_traffics.total/expiry_time to 0, so fall back to the clients
  509. // table to keep the Subscription-Userinfo header in sync with the UI (#4645).
  510. limits := make(map[string][2]int64, len(emails))
  511. var records []model.ClientRecord
  512. if err := db.Model(&model.ClientRecord{}).Where("email IN ?", emails).Find(&records).Error; err != nil {
  513. logger.Warning("SubService - AggregateTrafficByEmails: load client limits:", err)
  514. } else {
  515. for _, r := range records {
  516. limits[r.Email] = [2]int64{r.TotalGB, r.ExpiryTime}
  517. }
  518. }
  519. now := time.Now().UnixMilli()
  520. first := true
  521. for _, ct := range rows {
  522. if ct.LastOnline > lastOnline {
  523. lastOnline = ct.LastOnline
  524. }
  525. total, expiry := ct.Total, ct.ExpiryTime
  526. if lim, ok := limits[ct.Email]; ok {
  527. if total == 0 {
  528. total = lim[0]
  529. }
  530. if expiry == 0 {
  531. expiry = lim[1]
  532. }
  533. }
  534. if first {
  535. agg.Up = ct.Up
  536. agg.Down = ct.Down
  537. agg.Total = total
  538. agg.ExpiryTime = subscriptionExpiryFromClient(now, expiry)
  539. first = false
  540. continue
  541. }
  542. agg.Up += ct.Up
  543. agg.Down += ct.Down
  544. if agg.Total == 0 || total == 0 {
  545. agg.Total = 0
  546. } else {
  547. agg.Total += total
  548. }
  549. normalized := subscriptionExpiryFromClient(now, expiry)
  550. if normalized != agg.ExpiryTime {
  551. agg.ExpiryTime = 0
  552. }
  553. }
  554. return agg, lastOnline
  555. }
  556. func subscriptionExpiryFromClient(nowMs, expiryTime int64) int64 {
  557. if expiryTime > 0 {
  558. return expiryTime
  559. }
  560. if expiryTime < 0 {
  561. return nowMs + (-expiryTime)
  562. }
  563. return 0
  564. }
  565. func (s *SubService) getInboundsBySubId(subId string) ([]*model.Inbound, error) {
  566. db := database.GetDB()
  567. var inbounds []*model.Inbound
  568. err := db.Model(model.Inbound{}).Where(`id in (
  569. SELECT DISTINCT inbounds.id
  570. FROM inbounds
  571. JOIN client_inbounds ON client_inbounds.inbound_id = inbounds.id
  572. JOIN clients ON clients.id = client_inbounds.client_id
  573. WHERE
  574. inbounds.protocol in ('vmess','vless','trojan','shadowsocks','hysteria','wireguard','amneziawg','mtproto','tuic')
  575. AND clients.sub_id = ? AND inbounds.enable = ?
  576. )`, subId, true).Order("sub_sort_index ASC").Order("id ASC").Find(&inbounds).Error
  577. if err != nil {
  578. return nil, err
  579. }
  580. s.indexStatsBySubId(subId)
  581. return inbounds, nil
  582. }
  583. // indexStatsBySubId loads the traffic rows for just this subscriber's clients
  584. // into statsByEmail so statsForClient can resolve a client's usage on any of
  585. // its inbounds. It replaces preloading every matched inbound's ClientStats,
  586. // which read the entire client_traffics table on every subscription fetch of
  587. // a large inbound; statsForClient's per-email DB fallback covers any miss.
  588. func (s *SubService) indexStatsBySubId(subId string) {
  589. if s.statsByEmail == nil {
  590. s.statsByEmail = map[string]xray.ClientTraffic{}
  591. }
  592. db := database.GetDB()
  593. var emails []string
  594. if err := db.Model(&model.ClientRecord{}).Where("sub_id = ?", subId).Pluck("email", &emails).Error; err != nil {
  595. logger.Error("SubService - indexStatsBySubId: load emails:", err)
  596. return
  597. }
  598. const chunk = 400
  599. for lo := 0; lo < len(emails); lo += chunk {
  600. hi := min(lo+chunk, len(emails))
  601. var rows []xray.ClientTraffic
  602. if err := db.Where("email IN ?", emails[lo:hi]).Find(&rows).Error; err != nil {
  603. logger.Error("SubService - indexStatsBySubId: load traffics:", err)
  604. return
  605. }
  606. for _, st := range rows {
  607. s.statsByEmail[st.Email] = st
  608. }
  609. }
  610. }
  611. // projectThroughFallbackMaster mutates the inbound in place so its
  612. // Listen/Port/StreamSettings reflect the externally reachable master
  613. // when applicable. Covers both fallback mechanisms:
  614. // - panel-tracked: an inbound_fallbacks row where child_id = inbound.Id
  615. // - legacy unix-socket: inbound.Listen begins with "@" and some VLESS/
  616. // Trojan inbound's settings.fallbacks references that listen address
  617. //
  618. // Returns true when a projection happened; sub services call this before
  619. // generating links so a child VLESS-WS bound to 127.0.0.1 emits the
  620. // master's :443 + TLS state instead of its own loopback endpoint.
  621. //
  622. // Projection only applies to a child that is not directly reachable on its
  623. // own listen (loopback or a unix-domain socket). An inbound on a public or
  624. // wildcard listen is reachable on its own port, so it advertises its own
  625. // port + security even when a stale fallback rule still names it as a child —
  626. // otherwise its share link would leak the master's port and Reality/TLS
  627. // settings (#4987).
  628. func (s *SubService) projectThroughFallbackMaster(inbound *model.Inbound) bool {
  629. if inbound == nil {
  630. return false
  631. }
  632. if !listenIsInternalOnly(inbound.Listen) {
  633. return false
  634. }
  635. db := database.GetDB()
  636. var master *model.Inbound
  637. var rule model.InboundFallback
  638. if err := db.Where("child_id = ?", inbound.Id).
  639. Order("sort_order ASC, id ASC").
  640. First(&rule).Error; err == nil {
  641. var m model.Inbound
  642. if err := db.Where("id = ?", rule.MasterId).First(&m).Error; err == nil {
  643. master = &m
  644. }
  645. }
  646. if master == nil && len(inbound.Listen) > 0 && inbound.Listen[0] == '@' {
  647. var m model.Inbound
  648. if err := db.Model(model.Inbound{}).
  649. Where("JSON_TYPE(settings, '$.fallbacks') = 'array'").
  650. Where("EXISTS (SELECT * FROM json_each(settings, '$.fallbacks') WHERE json_extract(value, '$.dest') = ?)", inbound.Listen).
  651. First(&m).Error; err == nil {
  652. master = &m
  653. }
  654. }
  655. if master == nil {
  656. return false
  657. }
  658. inbound.StreamSettings = mergeStreamFromMaster(inbound.StreamSettings, master.StreamSettings)
  659. inbound.Listen = master.Listen
  660. inbound.Port = master.Port
  661. return true
  662. }
  663. // mergeStreamFromMaster copies the master's security + tlsSettings +
  664. // realitySettings + externalProxy onto the child's stream so the child's
  665. // link advertises the master's TLS / Reality state. Transport (network
  666. // + ws/grpc/etc. settings) stays the child's.
  667. func mergeStreamFromMaster(childStream, masterStream string) string {
  668. var stream map[string]any
  669. _ = json.Unmarshal([]byte(childStream), &stream)
  670. if stream == nil {
  671. stream = map[string]any{}
  672. }
  673. var mst map[string]any
  674. _ = json.Unmarshal([]byte(masterStream), &mst)
  675. if mst == nil {
  676. return childStream
  677. }
  678. stream["security"] = mst["security"]
  679. if v, ok := mst["tlsSettings"]; ok {
  680. stream["tlsSettings"] = v
  681. } else {
  682. delete(stream, "tlsSettings")
  683. }
  684. if v, ok := mst["realitySettings"]; ok {
  685. stream["realitySettings"] = v
  686. } else {
  687. delete(stream, "realitySettings")
  688. }
  689. if v, ok := mst["externalProxy"]; ok {
  690. stream["externalProxy"] = v
  691. }
  692. out, err := json.MarshalIndent(stream, "", " ")
  693. if err != nil {
  694. return childStream
  695. }
  696. return string(out)
  697. }
  698. // GetLink dispatches to the protocol-specific generator for one (inbound, client)
  699. // pair. Returns "" when the inbound's protocol doesn't produce a subscription URL
  700. // (socks, http, mixed, wireguard, dokodemo, tunnel). The returned string may
  701. // contain multiple `\n`-separated URLs when the inbound has externalProxy set.
  702. func (s *SubService) GetLink(inbound *model.Inbound, email string) string {
  703. switch inbound.Protocol {
  704. case "vmess":
  705. return s.genVmessLink(inbound, email)
  706. case "vless":
  707. return s.genVlessLink(inbound, email)
  708. case "trojan":
  709. return s.genTrojanLink(inbound, email)
  710. case "shadowsocks":
  711. return s.genShadowsocksLink(inbound, email)
  712. case "hysteria":
  713. return s.genHysteriaLink(inbound, email)
  714. case "mtproto":
  715. return s.genMtprotoLink(inbound, email)
  716. case "wireguard":
  717. return s.genWireguardLink(inbound, email)
  718. case "amneziawg":
  719. return s.genAmneziaWGLink(inbound, email)
  720. case "tuic":
  721. return s.genTuicLink(inbound, email)
  722. }
  723. return ""
  724. }
  725. func (s *SubService) genTuicLink(inbound *model.Inbound, email string) string {
  726. if inbound.Protocol != model.TUIC {
  727. return ""
  728. }
  729. inst, ok := tuic.InstanceFromInbound(inbound)
  730. if !ok {
  731. return ""
  732. }
  733. var client *tuic.TuicClientSettings
  734. for _, c := range inst.Clients {
  735. if c.Email == email {
  736. client = &c
  737. break
  738. }
  739. }
  740. if client == nil && len(inst.Clients) > 0 && email == "" {
  741. client = &inst.Clients[0]
  742. }
  743. if client == nil || client.UUID == "" || client.Password == "" {
  744. return ""
  745. }
  746. params := make(map[string]string)
  747. cc := inst.CongestionControl
  748. if cc == "" {
  749. cc = "bbr"
  750. }
  751. params["congestion_control"] = cc
  752. if len(inst.ALPN) > 0 {
  753. params["alpn"] = strings.Join(inst.ALPN, ",")
  754. }
  755. if inst.SNI != "" {
  756. params["sni"] = inst.SNI
  757. }
  758. if inst.UDPRelayMode != "" {
  759. params["udp_relay_mode"] = inst.UDPRelayMode
  760. }
  761. params["allow_insecure"] = "0"
  762. stream := unmarshalStreamSettings(inbound.StreamSettings)
  763. externalProxies, _ := stream["externalProxy"].([]any)
  764. if len(externalProxies) > 0 {
  765. links := make([]string, 0, len(externalProxies))
  766. for _, externalProxy := range externalProxies {
  767. ep, ok := externalProxy.(map[string]any)
  768. if !ok {
  769. continue
  770. }
  771. dest, _ := ep["dest"].(string)
  772. portF, okPort := ep["port"].(float64)
  773. if dest == "" || !okPort {
  774. continue
  775. }
  776. epParams := cloneStringMap(params)
  777. if sni, ok := externalProxySNI(ep); ok {
  778. epParams["sni"] = sni
  779. }
  780. if alpn, ok := externalProxyALPN(ep["alpn"]); ok {
  781. epParams["alpn"] = alpn
  782. }
  783. if ai, ok := ep["allowInsecure"].(bool); ok && ai {
  784. epParams["allow_insecure"] = "1"
  785. }
  786. link := fmt.Sprintf("tuic://%s:%s@%s", encodeUserinfo(client.UUID), encodeUserinfo(client.Password), joinHostPort(dest, int(portF)))
  787. links = append(links, buildLinkWithParams(link, epParams, s.endpointRemark(inbound, email, ep, "")))
  788. }
  789. return strings.Join(links, "\n")
  790. }
  791. host := s.resolveInboundAddress(inbound)
  792. link := fmt.Sprintf("tuic://%s:%s@%s", encodeUserinfo(client.UUID), encodeUserinfo(client.Password), joinHostPort(host, inbound.Port))
  793. return buildLinkWithParams(link, params, s.genRemark(inbound, email, "", ""))
  794. }
  795. // genWireguardLink builds a per-client wireguard:// share link mirroring the
  796. // frontend genWireguardLink: the client's private key is the userinfo, the
  797. // server public key (derived from the inbound secretKey) and the client's
  798. // tunnel address ride in the query. Returns "" when the client has no key.
  799. func (s *SubService) genWireguardLink(inbound *model.Inbound, email string) string {
  800. if inbound.Protocol != model.WireGuard {
  801. return ""
  802. }
  803. settings := s.linkSettings(inbound)
  804. secretKey, _ := settings["secretKey"].(string)
  805. resolved, ok := s.clientForLink(inbound, email)
  806. if !ok || resolved.PrivateKey == "" {
  807. return ""
  808. }
  809. client := &resolved
  810. link := fmt.Sprintf("wireguard://%s@%s", encodeUserinfo(client.PrivateKey), joinHostPort(s.resolveInboundAddress(inbound), inbound.Port))
  811. params := make(map[string]string)
  812. if secretKey != "" {
  813. if pub, err := wgutil.PublicKeyFromPrivate(secretKey); err == nil {
  814. params["publickey"] = pub
  815. }
  816. }
  817. if joined := strings.Join(client.AllowedIPs, ","); joined != "" {
  818. params["address"] = joined
  819. }
  820. if mtu, ok := settings["mtu"].(float64); ok && mtu > 0 {
  821. params["mtu"] = strconv.Itoa(int(mtu))
  822. }
  823. if dns, ok := settings["dns"].(string); ok && dns != "" {
  824. params["dns"] = dns
  825. }
  826. if client.PreSharedKey != "" {
  827. params["presharedkey"] = client.PreSharedKey
  828. }
  829. if ka := client.KeepAliveSeconds(); ka > 0 {
  830. params["keepalive"] = strconv.Itoa(ka)
  831. }
  832. return buildLinkWithParams(link, params, s.genRemark(inbound, email, "", ""))
  833. }
  834. // amneziaWGHeaderOrDefault mirrors the frontend's amneziaWGHLine: AmneziaWG's
  835. // H1-H4 magic-header fields always render into the config text, falling back
  836. // to their protocol-default values (1/2/3/4) when unset rather than being
  837. // omitted, since a native AmneziaWG client needs all four to be present.
  838. func amneziaWGHeaderOrDefault(value, fallback string) string {
  839. if strings.TrimSpace(value) == "" {
  840. return fallback
  841. }
  842. return value
  843. }
  844. // amneziaWGConfigText builds the same plain AmneziaWG client .conf text the
  845. // frontend's genAmneziaWGConfig produces (same field order, same optional-field
  846. // conditionals) -- this is the payload wrapped into vpn:// links below.
  847. func amneziaWGConfigText(server *amneziawg.ServerSettings, client *model.Client, host string, port int, remark string) string {
  848. // These land unescaped in [Interface]; a newline here would inject a
  849. // config line (e.g. a rogue PostUp) into the subscriber's .conf.
  850. for _, v := range []string{client.PrivateKey, server.PrimaryDNS, server.SecondaryDNS, remark} {
  851. if strings.ContainsAny(v, "\r\n") {
  852. return ""
  853. }
  854. }
  855. var b strings.Builder
  856. b.WriteString("[Interface]\n")
  857. fmt.Fprintf(&b, "PrivateKey = %s\n", client.PrivateKey)
  858. fmt.Fprintf(&b, "Address = %s\n", strings.Join(client.AllowedIPs, ", "))
  859. var dns []string
  860. if server.PrimaryDNS != "" {
  861. dns = append(dns, server.PrimaryDNS)
  862. }
  863. if server.SecondaryDNS != "" {
  864. dns = append(dns, server.SecondaryDNS)
  865. }
  866. if len(dns) > 0 {
  867. fmt.Fprintf(&b, "DNS = %s\n", strings.Join(dns, ", "))
  868. }
  869. // Always emitted: a missing MTU line leaves the client on its own 1420
  870. // default and fragments the client-to-server direction once S4 passes 20.
  871. fmt.Fprintf(&b, "MTU = %d\n", amneziawg.EffectiveMTU(server.MTU, server.S4))
  872. fmt.Fprintf(&b, "Jc = %d\n", server.Jc)
  873. fmt.Fprintf(&b, "Jmin = %d\n", server.Jmin)
  874. fmt.Fprintf(&b, "Jmax = %d\n", server.Jmax)
  875. fmt.Fprintf(&b, "S1 = %d\n", server.S1)
  876. fmt.Fprintf(&b, "S2 = %d\n", server.S2)
  877. if server.S3 > 0 {
  878. fmt.Fprintf(&b, "S3 = %d\n", server.S3)
  879. }
  880. if server.S4 > 0 {
  881. fmt.Fprintf(&b, "S4 = %d\n", server.S4)
  882. }
  883. fmt.Fprintf(&b, "H1 = %s\n", amneziaWGHeaderOrDefault(server.H1, "1"))
  884. fmt.Fprintf(&b, "H2 = %s\n", amneziaWGHeaderOrDefault(server.H2, "2"))
  885. fmt.Fprintf(&b, "H3 = %s\n", amneziaWGHeaderOrDefault(server.H3, "3"))
  886. fmt.Fprintf(&b, "H4 = %s\n", amneziaWGHeaderOrDefault(server.H4, "4"))
  887. for i, v := range []string{server.I1, server.I2, server.I3, server.I4, server.I5} {
  888. if v != "" {
  889. fmt.Fprintf(&b, "I%d = %s\n", i+1, v)
  890. }
  891. }
  892. optional := []struct{ key, v string }{
  893. {"HeaderProtectionKey", server.HeaderProtectionKey},
  894. {"ContentPaddingAddition", server.ContentPaddingAddition},
  895. {"RekeyAfterTime", server.RekeyAfterTime},
  896. {"RekeyTimeout", server.RekeyTimeout},
  897. {"RejectAfterTime", server.RejectAfterTime},
  898. {"KeepaliveTimeout", server.KeepaliveTimeout},
  899. {"MaxHandshakeAttempts", server.MaxHandshakeAttempts},
  900. }
  901. for _, p := range optional {
  902. if p.v != "" {
  903. fmt.Fprintf(&b, "%s = %s\n", p.key, p.v)
  904. }
  905. }
  906. if server.RandomTrailers {
  907. b.WriteString("RandomTrailers = on\n")
  908. }
  909. if server.DisableCookies {
  910. b.WriteString("DisableCookies = on\n")
  911. }
  912. // Peer field order follows wg-quick(8) and the panel's other two AmneziaWG
  913. // emitters (genAmneziaWGConfig, buildAmneziaWGClientConfig); all three are
  914. // independent implementations, so any drift here is invisible until a user
  915. // compares a subscription link against a downloaded .conf.
  916. fmt.Fprintf(&b, "\n# %s\n", remark)
  917. b.WriteString("[Peer]\n")
  918. fmt.Fprintf(&b, "PublicKey = %s\n", server.PublicKey)
  919. if client.PreSharedKey != "" {
  920. fmt.Fprintf(&b, "PresharedKey = %s\n", client.PreSharedKey)
  921. }
  922. b.WriteString("AllowedIPs = 0.0.0.0/0, ::/0\n")
  923. fmt.Fprintf(&b, "Endpoint = %s:%d", host, port)
  924. if ka := client.KeepAliveSeconds(); ka > 0 {
  925. fmt.Fprintf(&b, "\nPersistentKeepalive = %d", ka)
  926. }
  927. return b.String()
  928. }
  929. // genAmneziaWGLink builds a per-client vpn://<base64url .conf text> share
  930. // link matching the real AmneziaVPN app's own share-link scheme (see the
  931. // frontend's genAmneziaWGLink for the confirmed import-path reasoning).
  932. // Returns "" when the client or server has no key.
  933. func (s *SubService) genAmneziaWGLink(inbound *model.Inbound, email string) string {
  934. if inbound.Protocol != model.AmneziaWG {
  935. return ""
  936. }
  937. var parsed amneziawg.InboundSettings
  938. if err := json.Unmarshal([]byte(inbound.Settings), &parsed); err != nil || parsed.Server == nil {
  939. return ""
  940. }
  941. server := parsed.Server
  942. resolved, ok := s.clientForLink(inbound, email)
  943. if !ok || resolved.PrivateKey == "" {
  944. return ""
  945. }
  946. client := &resolved
  947. text := amneziaWGConfigText(server, client, s.resolveInboundAddress(inbound), inbound.Port, s.genRemark(inbound, email, "", ""))
  948. if text == "" {
  949. return ""
  950. }
  951. return "vpn://" + base64.RawURLEncoding.EncodeToString([]byte(text))
  952. }
  953. // genMtprotoLink builds one Telegram link per advertised endpoint with the client's FakeTLS secret.
  954. // It omits remarks because lenient parsers fold a fragment into the last query value.
  955. func (s *SubService) genMtprotoLink(inbound *model.Inbound, email string) string {
  956. if inbound.Protocol != model.MTProto {
  957. return ""
  958. }
  959. resolved, ok := s.clientForLink(inbound, email)
  960. if !ok || resolved.Secret == "" {
  961. return ""
  962. }
  963. endpoints := []ShareEndpoint{s.inboundDefaultEndpoint(inbound)}
  964. stream := unmarshalStreamSettings(inbound.StreamSettings)
  965. if externalProxies, ok := stream["externalProxy"].([]any); ok && len(externalProxies) > 0 {
  966. overrides := make([]ShareEndpoint, 0, len(externalProxies))
  967. for _, raw := range externalProxies {
  968. if ep, ok := raw.(map[string]any); ok {
  969. overrides = append(overrides, externalProxyToEndpoint(ep))
  970. }
  971. }
  972. if len(overrides) > 0 {
  973. endpoints = overrides
  974. }
  975. }
  976. links := make([]string, 0, len(endpoints))
  977. for _, endpoint := range endpoints {
  978. links = append(links, buildLinkWithParams("tg://proxy", map[string]string{
  979. "server": endpoint.Address,
  980. "port": fmt.Sprintf("%d", endpoint.Port),
  981. "secret": resolved.Secret,
  982. }, ""))
  983. }
  984. return strings.Join(links, "\n")
  985. }
  986. // Protocol link generators are intentionally ordered as:
  987. // vmess -> vless -> trojan -> shadowsocks -> hysteria.
  988. func (s *SubService) genVmessLink(inbound *model.Inbound, email string) string {
  989. if inbound.Protocol != model.VMESS {
  990. return ""
  991. }
  992. address := s.resolveInboundAddress(inbound)
  993. obj := map[string]any{
  994. "v": "2",
  995. "add": address,
  996. "port": inbound.Port,
  997. "type": "none",
  998. }
  999. stream := unmarshalStreamSettings(inbound.StreamSettings)
  1000. network, _ := stream["network"].(string)
  1001. applyVmessNetworkParams(stream, network, obj)
  1002. if finalmask, ok := stream["finalmask"].(map[string]any); ok {
  1003. applyFinalMaskObj(finalmask, obj)
  1004. }
  1005. security, _ := stream["security"].(string)
  1006. obj["tls"] = security
  1007. if security == "tls" {
  1008. applyVmessTLSParams(stream, obj)
  1009. }
  1010. client, ok := s.clientForLink(inbound, email)
  1011. if !ok {
  1012. return ""
  1013. }
  1014. obj["id"] = client.ID
  1015. obj["scy"] = normalizeVmessSecurity(client.Security)
  1016. externalProxies, _ := stream["externalProxy"].([]any)
  1017. if len(externalProxies) > 0 {
  1018. return s.buildVmessExternalProxyLinks(externalProxies, obj, inbound, email, network)
  1019. }
  1020. obj["ps"] = s.genRemark(inbound, email, "", network)
  1021. return buildVmessLink(obj)
  1022. }
  1023. // normalizeVmessSecurity maps the vmess security values xray-core v26.7.11
  1024. // removed ("none"/"zero"), plus the legacy empty string, to "auto" so links
  1025. // and subscriptions stop advertising values the upgraded server rejects on
  1026. // the wire.
  1027. func normalizeVmessSecurity(security string) string {
  1028. switch security {
  1029. case "", "none", "zero":
  1030. return "auto"
  1031. }
  1032. return security
  1033. }
  1034. // vlessEncryptionEnabled reports whether the VLESS inbound settings enable
  1035. // VLESS-level encryption (vlessenc / ML-KEM). When on, the encryption/decryption
  1036. // fields hold a generated dotted string (e.g. "mlkem768x25519plus.native.0rtt.<key>");
  1037. // "none" or empty means off. The value is never the literal "vlessenc" — that is
  1038. // the `xray vlessenc` CLI subcommand name, not a stored value.
  1039. func vlessEncryptionEnabled(settings map[string]any) bool {
  1040. for _, key := range []string{"encryption", "decryption"} {
  1041. if v, ok := settings[key].(string); ok && v != "" && v != "none" {
  1042. return true
  1043. }
  1044. }
  1045. return false
  1046. }
  1047. // vlessFlowAllowed reports whether a client's XTLS Vision flow belongs in
  1048. // generated links/configs. Mirrors inboundCanEnableTlsFlow in
  1049. // internal/web/service: Vision runs on TCP with tls/reality (classic), and on
  1050. // XHTTP whenever VLESS encryption (vlessenc / ML-KEM) is enabled — there the
  1051. // VLESS-level encryption stands in for the transport TLS that Vision relies
  1052. // on, regardless of the stream security layer (so XHTTP+REALITY+vlessenc
  1053. // keeps its flow too).
  1054. func vlessFlowAllowed(network, security string, settings map[string]any) bool {
  1055. switch network {
  1056. case "tcp":
  1057. return security == "tls" || security == "reality"
  1058. case "xhttp":
  1059. return vlessEncryptionEnabled(settings)
  1060. }
  1061. return false
  1062. }
  1063. func (s *SubService) genVlessLink(inbound *model.Inbound, email string) string {
  1064. if inbound.Protocol != model.VLESS {
  1065. return ""
  1066. }
  1067. address := s.resolveInboundAddress(inbound)
  1068. stream := unmarshalStreamSettings(inbound.StreamSettings)
  1069. client, ok := s.clientForLink(inbound, email)
  1070. if !ok {
  1071. return ""
  1072. }
  1073. uuid := client.ID
  1074. port := inbound.Port
  1075. streamNetwork, _ := stream["network"].(string)
  1076. params := make(map[string]string)
  1077. params["type"] = streamNetwork
  1078. // Add encryption parameter for VLESS from inbound settings
  1079. settings := s.linkSettings(inbound)
  1080. if encryption, ok := settings["encryption"].(string); ok {
  1081. params["encryption"] = encryption
  1082. }
  1083. applyShareNetworkParams(stream, streamNetwork, params)
  1084. if finalmask, ok := stream["finalmask"].(map[string]any); ok {
  1085. applyFinalMaskParams(finalmask, params)
  1086. }
  1087. security, _ := stream["security"].(string)
  1088. switch security {
  1089. case "tls":
  1090. applyShareTLSParams(stream, params)
  1091. case "reality":
  1092. applyShareRealityParams(stream, params, subKey(client))
  1093. default:
  1094. params["security"] = "none"
  1095. }
  1096. if len(client.Flow) > 0 && !inbound.DisableFlow && vlessFlowAllowed(streamNetwork, security, settings) {
  1097. params["flow"] = client.Flow
  1098. }
  1099. externalProxies, _ := stream["externalProxy"].([]any)
  1100. if len(externalProxies) > 0 {
  1101. return s.buildExternalProxyURLLinks(
  1102. externalProxies,
  1103. params,
  1104. security,
  1105. func(ep map[string]any, dest string, port int) string {
  1106. return fmt.Sprintf("vless://%s@%s", applyVlessRoute(uuid, hostVlessRoute(ep)), joinHostPort(dest, port))
  1107. },
  1108. func(ep map[string]any) string {
  1109. return s.endpointRemark(inbound, email, ep, streamNetwork)
  1110. },
  1111. )
  1112. }
  1113. link := fmt.Sprintf("vless://%s@%s", uuid, joinHostPort(address, port))
  1114. return buildLinkWithParams(link, params, s.genRemark(inbound, email, "", streamNetwork))
  1115. }
  1116. func (s *SubService) genTrojanLink(inbound *model.Inbound, email string) string {
  1117. if inbound.Protocol != model.Trojan {
  1118. return ""
  1119. }
  1120. address := s.resolveInboundAddress(inbound)
  1121. stream := unmarshalStreamSettings(inbound.StreamSettings)
  1122. client, ok := s.clientForLink(inbound, email)
  1123. if !ok {
  1124. return ""
  1125. }
  1126. password := encodeUserinfo(client.Password)
  1127. port := inbound.Port
  1128. streamNetwork, _ := stream["network"].(string)
  1129. params := make(map[string]string)
  1130. params["type"] = streamNetwork
  1131. applyShareNetworkParams(stream, streamNetwork, params)
  1132. if finalmask, ok := stream["finalmask"].(map[string]any); ok {
  1133. applyFinalMaskParams(finalmask, params)
  1134. }
  1135. security, _ := stream["security"].(string)
  1136. switch security {
  1137. case "tls":
  1138. applyShareTLSParams(stream, params)
  1139. case "reality":
  1140. applyShareRealityParams(stream, params, subKey(client))
  1141. if streamNetwork == "tcp" && len(client.Flow) > 0 && !inbound.DisableFlow {
  1142. params["flow"] = client.Flow
  1143. }
  1144. default:
  1145. params["security"] = "none"
  1146. }
  1147. externalProxies, _ := stream["externalProxy"].([]any)
  1148. if len(externalProxies) > 0 {
  1149. return s.buildExternalProxyURLLinks(
  1150. externalProxies,
  1151. params,
  1152. security,
  1153. func(_ map[string]any, dest string, port int) string {
  1154. return fmt.Sprintf("trojan://%s@%s", password, joinHostPort(dest, port))
  1155. },
  1156. func(ep map[string]any) string {
  1157. return s.endpointRemark(inbound, email, ep, streamNetwork)
  1158. },
  1159. )
  1160. }
  1161. link := fmt.Sprintf("trojan://%s@%s", password, joinHostPort(address, port))
  1162. return buildLinkWithParams(link, params, s.genRemark(inbound, email, "", streamNetwork))
  1163. }
  1164. // encodeUserinfo percent-encodes a userinfo (password/auth) value so it
  1165. // can be safely embedded in a `scheme://<value>@host:port` URL. RFC 3986
  1166. // allows `=` in userinfo as a sub-delim, but several Trojan and Hysteria
  1167. // clients reject share-links where the password contains literal `/`
  1168. // or `=` (notably the common base64-with-padding shape produced by the
  1169. // panel). Encode them too — this matches encodeURIComponent() on the
  1170. // frontend and round-trips cleanly through net/url's parser.
  1171. func encodeUserinfo(s string) string {
  1172. return strings.ReplaceAll(url.QueryEscape(s), "+", "%20")
  1173. }
  1174. // joinHostPort wraps an IPv6 host in square brackets the way RFC 3986
  1175. // requires for URI authorities, while leaving IPv4 addresses and hostnames
  1176. // untouched. It also strips any brackets already present on the input so
  1177. // callers don't have to normalize upstream.
  1178. func joinHostPort(host string, port int) string {
  1179. host = strings.Trim(host, "[]")
  1180. return net.JoinHostPort(host, strconv.Itoa(port))
  1181. }
  1182. func (s *SubService) genShadowsocksLink(inbound *model.Inbound, email string) string {
  1183. if inbound.Protocol != model.Shadowsocks {
  1184. return ""
  1185. }
  1186. address := s.resolveInboundAddress(inbound)
  1187. stream := unmarshalStreamSettings(inbound.StreamSettings)
  1188. client, ok := s.clientForLink(inbound, email)
  1189. if !ok {
  1190. return ""
  1191. }
  1192. settings := s.linkSettings(inbound)
  1193. inboundPassword, _ := settings["password"].(string)
  1194. method, _ := settings["method"].(string)
  1195. streamNetwork, _ := stream["network"].(string)
  1196. params := make(map[string]string)
  1197. params["type"] = streamNetwork
  1198. applyShareNetworkParams(stream, streamNetwork, params)
  1199. if finalmask, ok := stream["finalmask"].(map[string]any); ok {
  1200. applyFinalMaskParams(finalmask, params)
  1201. }
  1202. security, _ := stream["security"].(string)
  1203. if security == "tls" {
  1204. applyShareTLSParams(stream, params)
  1205. }
  1206. // SIP002 clients (v2rayN) ignore the xray-native type/headerType/host/path
  1207. // params and only read `plugin`. Re-encode a TCP http header as obfs-local so
  1208. // they build a matching tcp/http outbound (v2rayN forces request path "/").
  1209. if streamNetwork == "tcp" && params["headerType"] == "http" {
  1210. host := params["host"]
  1211. delete(params, "type")
  1212. delete(params, "headerType")
  1213. delete(params, "host")
  1214. delete(params, "path")
  1215. params["plugin"] = "obfs-local;obfs=http;obfs-host=" + host
  1216. }
  1217. // SIP002 userinfo is base64(method:password). For SIP022 (2022-blake3-*) the
  1218. // userinfo MUST NOT be base64-encoded; method and password are percent-encoded.
  1219. var userInfo string
  1220. if strings.HasPrefix(method, "2022") {
  1221. userInfo = fmt.Sprintf("%s:%s:%s",
  1222. url.QueryEscape(method),
  1223. url.QueryEscape(inboundPassword),
  1224. url.QueryEscape(client.Password))
  1225. } else {
  1226. userInfo = base64.RawURLEncoding.EncodeToString(fmt.Appendf(nil, "%s:%s", method, client.Password))
  1227. }
  1228. externalProxies, _ := stream["externalProxy"].([]any)
  1229. if len(externalProxies) > 0 {
  1230. proxyParams := cloneStringMap(params)
  1231. proxyParams["security"] = security
  1232. return s.buildExternalProxyURLLinks(
  1233. externalProxies,
  1234. proxyParams,
  1235. security,
  1236. func(_ map[string]any, dest string, port int) string {
  1237. return fmt.Sprintf("ss://%s@%s", userInfo, joinHostPort(dest, port))
  1238. },
  1239. func(ep map[string]any) string {
  1240. return s.endpointRemark(inbound, email, ep, streamNetwork)
  1241. },
  1242. )
  1243. }
  1244. link := fmt.Sprintf("ss://%s@%s", userInfo, joinHostPort(address, inbound.Port))
  1245. return buildLinkWithParams(link, params, s.genRemark(inbound, email, "", streamNetwork))
  1246. }
  1247. func (s *SubService) genHysteriaLink(inbound *model.Inbound, email string) string {
  1248. if inbound.Protocol != model.Hysteria {
  1249. return ""
  1250. }
  1251. var stream map[string]any
  1252. _ = json.Unmarshal([]byte(inbound.StreamSettings), &stream)
  1253. client, ok := s.clientForLink(inbound, email)
  1254. if !ok {
  1255. return ""
  1256. }
  1257. auth := encodeUserinfo(client.Auth)
  1258. params := make(map[string]string)
  1259. params["security"] = "tls"
  1260. tlsSetting, _ := stream["tlsSettings"].(map[string]any)
  1261. alpns, _ := tlsSetting["alpn"].([]any)
  1262. var alpn []string
  1263. for _, a := range alpns {
  1264. if s, ok := a.(string); ok {
  1265. alpn = append(alpn, s)
  1266. }
  1267. }
  1268. if len(alpn) > 0 {
  1269. params["alpn"] = strings.Join(alpn, ",")
  1270. }
  1271. if sniValue, ok := searchKey(tlsSetting, "serverName"); ok {
  1272. params["sni"], _ = sniValue.(string)
  1273. }
  1274. tlsSettings, _ := searchKey(tlsSetting, "settings")
  1275. if tlsSetting != nil {
  1276. if fpValue, ok := searchKey(tlsSettings, "fingerprint"); ok {
  1277. params["fp"], _ = fpValue.(string)
  1278. }
  1279. if echValue, ok := searchKey(tlsSettings, "echConfigList"); ok {
  1280. if ech, _ := echValue.(string); ech != "" {
  1281. params["ech"] = ech
  1282. }
  1283. }
  1284. if vcn, ok := verifyPeerCertByNameValue(tlsSettings); ok {
  1285. params["vcn"] = vcn
  1286. }
  1287. if pins, ok := pinnedSha256List(tlsSettings); ok {
  1288. for i, p := range pins {
  1289. pins[i] = hysteriaPinHex(p)
  1290. }
  1291. params["pinSHA256"] = strings.Join(pins, ",")
  1292. }
  1293. }
  1294. // salamander obfs (Hysteria2): standard URI fields only -- an fm=<json>
  1295. // dump breaks strict clients. packetSize exports as v2rayN's gecko pair.
  1296. if finalmask, ok := stream["finalmask"].(map[string]any); ok {
  1297. if udpMasks, ok := finalmask["udp"].([]any); ok {
  1298. for _, m := range udpMasks {
  1299. mask, _ := m.(map[string]any)
  1300. if mask == nil || mask["type"] != "salamander" {
  1301. continue
  1302. }
  1303. settings, _ := mask["settings"].(map[string]any)
  1304. if pw, ok := settings["password"].(string); ok && pw != "" {
  1305. packetSize, _ := settings["packetSize"].(string)
  1306. gecko := parseHysteriaPacketSize(packetSize)
  1307. if gecko != "" {
  1308. params["obfs"] = "gecko"
  1309. params["minPacketSize"], params["maxPacketSize"] = splitHysteriaPacketSize(gecko)
  1310. }
  1311. // packetSize rides its own URI fields; anything else still
  1312. // breaks standard clients and must warn even when gecko fires.
  1313. if extra := extraSalamanderKeys(settings, gecko != ""); len(extra) > 0 {
  1314. warningKey := fmt.Sprintf("%d:%v", inbound.Id, extra)
  1315. if _, loaded := salamanderWarningSeen.LoadOrStore(warningKey, struct{}{}); !loaded {
  1316. logger.Warningf("SubService - inbound %d: salamander settings %v cannot be expressed in a hysteria2 URI; standard clients will fail the handshake", inbound.Id, extra)
  1317. }
  1318. }
  1319. if params["obfs"] == "" {
  1320. params["obfs"] = "salamander"
  1321. }
  1322. params["obfs-password"] = pw
  1323. break
  1324. }
  1325. }
  1326. }
  1327. }
  1328. settings := s.linkSettings(inbound)
  1329. version, _ := settings["version"].(float64)
  1330. protocol := "hysteria2"
  1331. if int(version) == 1 {
  1332. protocol = "hysteria"
  1333. }
  1334. // Set before the externalProxy fan-out: a Host overrides only the
  1335. // address, so every endpoint inherits the inbound's UDP hop range.
  1336. if hopPorts := hysteriaHopPorts(stream); hopPorts != "" {
  1337. params["mport"] = hopPorts
  1338. }
  1339. // Fan out one link per External Proxy entry if any. Previously this
  1340. // generator ignored `externalProxy` entirely, so the link kept the
  1341. // server's own IP/port even when the admin configured an alternate
  1342. // endpoint (e.g. a CDN hostname + port that forwards to the node).
  1343. // Matches the behaviour of genVlessLink / genTrojanLink / ….
  1344. externalProxies, _ := stream["externalProxy"].([]any)
  1345. if len(externalProxies) > 0 {
  1346. links := make([]string, 0, len(externalProxies))
  1347. for _, externalProxy := range externalProxies {
  1348. ep, ok := externalProxy.(map[string]any)
  1349. if !ok {
  1350. continue
  1351. }
  1352. dest, _ := ep["dest"].(string)
  1353. portF, okPort := ep["port"].(float64)
  1354. if dest == "" || !okPort {
  1355. continue
  1356. }
  1357. epParams := cloneStringMap(params)
  1358. applyExternalProxyHysteriaParams(ep, epParams)
  1359. link := fmt.Sprintf("%s://%s@%s", protocol, auth, joinHostPort(dest, int(portF)))
  1360. links = append(links, buildLinkWithParams(link, epParams, s.endpointRemark(inbound, email, ep, "quic")))
  1361. }
  1362. return strings.Join(links, "\n")
  1363. }
  1364. // No external proxy configured — use the inbound's resolved address so
  1365. // node-managed inbounds get the node's host instead of the central panel's.
  1366. link := fmt.Sprintf("%s://%s@%s", protocol, auth, joinHostPort(s.resolveInboundAddress(inbound), inbound.Port))
  1367. return buildLinkWithParams(link, params, s.genRemark(inbound, email, "", "quic"))
  1368. }
  1369. // hysteriaHopPorts returns the configured Hysteria2 UDP port-hopping range, or
  1370. // "" when port hopping is off. The range is emitted as the v2rayN-compatible
  1371. // `mport` query param; the URL port field stays numeric so .NET-Uri-based
  1372. // importers (v2rayN) can parse the link.
  1373. func hysteriaHopPorts(stream map[string]any) string {
  1374. finalmask, _ := stream["finalmask"].(map[string]any)
  1375. if ports := udpHopMaskPorts(finalmask); ports != "" {
  1376. return ports
  1377. }
  1378. quicParams, _ := finalmask["quicParams"].(map[string]any)
  1379. udpHop, _ := quicParams["udpHop"].(map[string]any)
  1380. ports, _ := udpHop["ports"].(string)
  1381. return strings.TrimSpace(ports)
  1382. }
  1383. // udpHopMaskPorts reads remotePorts off the first "udphop" UDP mask. xray-core
  1384. // 26.9.9 moved hopping here from finalmask.quicParams.udpHop, which it now ignores.
  1385. func udpHopMaskPorts(finalmask map[string]any) string {
  1386. masks, _ := finalmask["udp"].([]any)
  1387. for _, rawMask := range masks {
  1388. mask, _ := rawMask.(map[string]any)
  1389. if maskType, _ := mask["type"].(string); maskType != "udphop" {
  1390. continue
  1391. }
  1392. settings, _ := mask["settings"].(map[string]any)
  1393. ports, _ := settings["remotePorts"].(string)
  1394. if ports = strings.TrimSpace(ports); ports != "" {
  1395. return ports
  1396. }
  1397. }
  1398. return ""
  1399. }
  1400. // gecko packetSize bounds mirror xray-core's salamander buffer cap and the
  1401. // frontend editor, so both link generators emit identical URIs.
  1402. const (
  1403. geckoMinPacketSize = 1
  1404. geckoMaxPacketSize = 2048
  1405. )
  1406. // parseHysteriaPacketSize validates an xray-core salamander packetSize range
  1407. // ("512-1200", the Gecko obfs marker). Returns canonical "min-max" or "".
  1408. func parseHysteriaPacketSize(value string) string {
  1409. minStr, maxStr, ok := strings.Cut(value, "-")
  1410. if !ok || minStr == "" || maxStr == "" {
  1411. return ""
  1412. }
  1413. for _, c := range minStr {
  1414. if c < '0' || c > '9' {
  1415. return ""
  1416. }
  1417. }
  1418. for _, c := range maxStr {
  1419. if c < '0' || c > '9' {
  1420. return ""
  1421. }
  1422. }
  1423. minVal, err1 := strconv.Atoi(minStr)
  1424. maxVal, err2 := strconv.Atoi(maxStr)
  1425. if err1 != nil || err2 != nil ||
  1426. minVal < geckoMinPacketSize || maxVal < minVal || maxVal > geckoMaxPacketSize {
  1427. return ""
  1428. }
  1429. return fmt.Sprintf("%d-%d", minVal, maxVal)
  1430. }
  1431. func splitHysteriaPacketSize(value string) (string, string) {
  1432. minStr, maxStr, _ := strings.Cut(value, "-")
  1433. return minStr, maxStr
  1434. }
  1435. // loadNodes refreshes nodesByID from the DB. Called once per request so
  1436. // the per-inbound resolveInboundAddress lookups are pure map reads.
  1437. // We filter to address != ” so a half-configured node row doesn't
  1438. // accidentally produce a useless host like "https://:2053".
  1439. func (s *SubService) loadNodes() {
  1440. db := database.GetDB()
  1441. var nodes []*model.Node
  1442. if err := db.Model(&model.Node{}).Where("address != ''").Find(&nodes).Error; err != nil {
  1443. logger.Warning("subscription: load nodes failed:", err)
  1444. s.nodesByID = nil
  1445. return
  1446. }
  1447. m := make(map[int]*model.Node, len(nodes))
  1448. for _, n := range nodes {
  1449. m[n.Id] = n
  1450. }
  1451. s.nodesByID = m
  1452. }
  1453. // resolveInboundAddress picks the host an external client should connect to,
  1454. // honoring the inbound's share address strategy the same way the panel's
  1455. // share/QR link builder does (#5208):
  1456. // - "listen": an explicit, client-reachable bind Listen wins, backed by the
  1457. // node's address for node-managed inbounds;
  1458. // - "custom": the inbound's ShareAddr wins, then node, then listen;
  1459. // - "node" (default, and any unknown value): the node's address for
  1460. // node-managed inbounds, then a routable Listen — the pre-strategy order.
  1461. //
  1462. // Every chain ends at the admin's configured public host (Sub/Web domain) and
  1463. // then the subscriber's request host (s.address). Preferring the configured
  1464. // host over the request host for this last resort keeps a wildcard local inbound
  1465. // from advertising a bogus client IP that leaked into the request Host header
  1466. // behind NAT/proxy/CDN (#5425). A loopback/wildcard bind or a unix-domain-socket
  1467. // listen is a server-side detail and is never advertised; External Proxy still
  1468. // overrides everything upstream of this call.
  1469. func (s *SubService) resolveInboundAddress(inbound *model.Inbound) string {
  1470. var nodeAddr string
  1471. if inbound.NodeID != nil && s.nodesByID != nil {
  1472. if n, ok := s.nodesByID[*inbound.NodeID]; ok {
  1473. nodeAddr = n.Address
  1474. }
  1475. }
  1476. var listenAddr string
  1477. if listen := inbound.Listen; listen != "" && listen[0] != '@' && listen[0] != '/' && isRoutableHost(listen) {
  1478. listenAddr = listen
  1479. }
  1480. candidates := []string{nodeAddr, listenAddr}
  1481. switch inbound.ShareAddrStrategy {
  1482. case "listen":
  1483. candidates = []string{listenAddr, nodeAddr}
  1484. case "custom":
  1485. candidates = []string{strings.TrimSpace(inbound.ShareAddr), nodeAddr, listenAddr}
  1486. }
  1487. for _, c := range candidates {
  1488. if c != "" {
  1489. return c
  1490. }
  1491. }
  1492. if d := s.configuredPublicHost(); d != "" {
  1493. return d
  1494. }
  1495. return s.address
  1496. }
  1497. func findClientIndex(clients []model.Client, email string) int {
  1498. for i, client := range clients {
  1499. if client.Email == email {
  1500. return i
  1501. }
  1502. }
  1503. return -1
  1504. }
  1505. func unmarshalStreamSettings(streamSettings string) map[string]any {
  1506. var stream map[string]any
  1507. _ = json.Unmarshal([]byte(streamSettings), &stream)
  1508. return stream
  1509. }
  1510. func applyPathAndHostParams(settings map[string]any, params map[string]string) {
  1511. params["path"], _ = settings["path"].(string)
  1512. if host, ok := settings["host"].(string); ok && len(host) > 0 {
  1513. params["host"] = host
  1514. } else {
  1515. headers, _ := settings["headers"].(map[string]any)
  1516. params["host"] = searchHost(headers)
  1517. }
  1518. }
  1519. func applyPathAndHostObj(settings map[string]any, obj map[string]any) {
  1520. obj["path"], _ = settings["path"].(string)
  1521. if host, ok := settings["host"].(string); ok && len(host) > 0 {
  1522. obj["host"] = host
  1523. } else {
  1524. headers, _ := settings["headers"].(map[string]any)
  1525. obj["host"] = searchHost(headers)
  1526. }
  1527. }
  1528. func applyShareNetworkParams(stream map[string]any, streamNetwork string, params map[string]string) {
  1529. switch streamNetwork {
  1530. case "tcp":
  1531. tcp, _ := stream["tcpSettings"].(map[string]any)
  1532. header, _ := tcp["header"].(map[string]any)
  1533. typeStr, _ := header["type"].(string)
  1534. if typeStr == "http" {
  1535. request, _ := header["request"].(map[string]any)
  1536. requestPath, _ := request["path"].([]any)
  1537. if len(requestPath) > 0 {
  1538. params["path"], _ = requestPath[0].(string)
  1539. }
  1540. host := ""
  1541. if response, ok := header["response"].(map[string]any); ok {
  1542. if respHeaders, ok := response["headers"].(map[string]any); ok {
  1543. host = searchHost(respHeaders)
  1544. }
  1545. }
  1546. if host == "" {
  1547. headers, _ := request["headers"].(map[string]any)
  1548. host = searchHost(headers)
  1549. }
  1550. params["host"] = host
  1551. params["headerType"] = "http"
  1552. }
  1553. case "kcp":
  1554. applyKcpShareParams(stream, params)
  1555. case "ws":
  1556. ws, _ := stream["wsSettings"].(map[string]any)
  1557. applyPathAndHostParams(ws, params)
  1558. case "grpc":
  1559. grpc, _ := stream["grpcSettings"].(map[string]any)
  1560. params["serviceName"], _ = grpc["serviceName"].(string)
  1561. params["authority"], _ = grpc["authority"].(string)
  1562. if mm, _ := grpc["multiMode"].(bool); mm {
  1563. params["mode"] = "multi"
  1564. }
  1565. case "httpupgrade":
  1566. httpupgrade, _ := stream["httpupgradeSettings"].(map[string]any)
  1567. applyPathAndHostParams(httpupgrade, params)
  1568. case "xhttp":
  1569. xhttp, _ := stream["xhttpSettings"].(map[string]any)
  1570. applyXhttpExtraParams(xhttp, params)
  1571. }
  1572. }
  1573. // applyXhttpExtraObj copies the bidirectional xhttp settings into the
  1574. // VMess base64 JSON link object. VMess supports arbitrary keys, so we
  1575. // flatten the SplitHTTPConfig "extra" fields directly onto obj.
  1576. func applyXhttpExtraObj(xhttp map[string]any, obj map[string]any) {
  1577. if xpb, ok := xhttp["xPaddingBytes"].(string); ok && len(xpb) > 0 {
  1578. obj["x_padding_bytes"] = xpb
  1579. }
  1580. maps.Copy(obj, buildXhttpExtra(xhttp))
  1581. }
  1582. func applyVmessNetworkParams(stream map[string]any, network string, obj map[string]any) {
  1583. obj["net"] = network
  1584. switch network {
  1585. case "tcp":
  1586. tcp, _ := stream["tcpSettings"].(map[string]any)
  1587. header, _ := tcp["header"].(map[string]any)
  1588. typeStr, _ := header["type"].(string)
  1589. obj["type"] = typeStr
  1590. if typeStr == "http" {
  1591. request, _ := header["request"].(map[string]any)
  1592. requestPath, _ := request["path"].([]any)
  1593. if len(requestPath) > 0 {
  1594. obj["path"], _ = requestPath[0].(string)
  1595. }
  1596. host := ""
  1597. if response, ok := header["response"].(map[string]any); ok {
  1598. if respHeaders, ok := response["headers"].(map[string]any); ok {
  1599. host = searchHost(respHeaders)
  1600. }
  1601. }
  1602. if host == "" {
  1603. headers, _ := request["headers"].(map[string]any)
  1604. host = searchHost(headers)
  1605. }
  1606. obj["host"] = host
  1607. }
  1608. case "kcp":
  1609. applyKcpShareObj(stream, obj)
  1610. case "ws":
  1611. ws, _ := stream["wsSettings"].(map[string]any)
  1612. applyPathAndHostObj(ws, obj)
  1613. case "grpc":
  1614. grpc, _ := stream["grpcSettings"].(map[string]any)
  1615. obj["path"], _ = grpc["serviceName"].(string)
  1616. obj["authority"], _ = grpc["authority"].(string)
  1617. if mm, _ := grpc["multiMode"].(bool); mm {
  1618. obj["type"] = "multi"
  1619. }
  1620. case "httpupgrade":
  1621. httpupgrade, _ := stream["httpupgradeSettings"].(map[string]any)
  1622. applyPathAndHostObj(httpupgrade, obj)
  1623. case "xhttp":
  1624. xhttp, _ := stream["xhttpSettings"].(map[string]any)
  1625. applyPathAndHostObj(xhttp, obj)
  1626. if mode, ok := xhttp["mode"].(string); ok {
  1627. obj["mode"] = mode
  1628. }
  1629. applyXhttpExtraObj(xhttp, obj)
  1630. }
  1631. }
  1632. func applyShareTLSParams(stream map[string]any, params map[string]string) {
  1633. params["security"] = "tls"
  1634. tlsSetting, _ := stream["tlsSettings"].(map[string]any)
  1635. alpns, _ := tlsSetting["alpn"].([]any)
  1636. var alpn []string
  1637. for _, a := range alpns {
  1638. if s, ok := a.(string); ok {
  1639. alpn = append(alpn, s)
  1640. }
  1641. }
  1642. if len(alpn) > 0 {
  1643. params["alpn"] = strings.Join(alpn, ",")
  1644. }
  1645. if sniValue, ok := searchKey(tlsSetting, "serverName"); ok {
  1646. params["sni"], _ = sniValue.(string)
  1647. }
  1648. tlsSettings, _ := searchKey(tlsSetting, "settings")
  1649. if tlsSetting != nil {
  1650. if fpValue, ok := searchKey(tlsSettings, "fingerprint"); ok {
  1651. params["fp"], _ = fpValue.(string)
  1652. }
  1653. if echValue, ok := searchKey(tlsSettings, "echConfigList"); ok {
  1654. if ech, _ := echValue.(string); ech != "" {
  1655. params["ech"] = ech
  1656. }
  1657. }
  1658. if vcn, ok := verifyPeerCertByNameValue(tlsSettings); ok {
  1659. params["vcn"] = vcn
  1660. }
  1661. if pins, ok := pinnedSha256List(tlsSettings); ok {
  1662. params["pcs"] = strings.Join(pins, ",")
  1663. }
  1664. }
  1665. }
  1666. func applyVmessTLSParams(stream map[string]any, obj map[string]any) {
  1667. tlsSetting, _ := stream["tlsSettings"].(map[string]any)
  1668. alpns, _ := tlsSetting["alpn"].([]any)
  1669. if len(alpns) > 0 {
  1670. var alpn []string
  1671. for _, a := range alpns {
  1672. if s, ok := a.(string); ok {
  1673. alpn = append(alpn, s)
  1674. }
  1675. }
  1676. obj["alpn"] = strings.Join(alpn, ",")
  1677. }
  1678. if sniValue, ok := searchKey(tlsSetting, "serverName"); ok {
  1679. obj["sni"], _ = sniValue.(string)
  1680. }
  1681. tlsSettings, _ := searchKey(tlsSetting, "settings")
  1682. if tlsSetting != nil {
  1683. if fpValue, ok := searchKey(tlsSettings, "fingerprint"); ok {
  1684. obj["fp"], _ = fpValue.(string)
  1685. }
  1686. if echValue, ok := searchKey(tlsSettings, "echConfigList"); ok {
  1687. if ech, _ := echValue.(string); ech != "" {
  1688. obj["ech"] = ech
  1689. }
  1690. }
  1691. if vcn, ok := verifyPeerCertByNameValue(tlsSettings); ok {
  1692. obj["vcn"] = vcn
  1693. }
  1694. if pins, ok := pinnedSha256List(tlsSettings); ok {
  1695. obj["pcs"] = strings.Join(pins, ",")
  1696. }
  1697. }
  1698. }
  1699. // verifyPeerCertByNameValue extracts tlsSettings.settings.verifyPeerCertByName
  1700. // (the v2rayN `vcn` param) as a trimmed string. Like pinnedPeerCertSha256 it is
  1701. // panel-only and flows into share links so clients verify the server
  1702. // certificate by this name — the replacement for the removed allowInsecure.
  1703. func verifyPeerCertByNameValue(tlsClientSettings any) (string, bool) {
  1704. raw, ok := searchKey(tlsClientSettings, "verifyPeerCertByName")
  1705. if !ok {
  1706. return "", false
  1707. }
  1708. s, ok := raw.(string)
  1709. if !ok {
  1710. return "", false
  1711. }
  1712. if s = strings.TrimSpace(s); s == "" {
  1713. return "", false
  1714. }
  1715. return s, true
  1716. }
  1717. // pinnedSha256List extracts tlsSettings.settings.pinnedPeerCertSha256 as a
  1718. // []string. The field is panel-only (stripped before the run-config reaches
  1719. // xray-core via internal/web/service/xray.go) but flows into share links so clients
  1720. // can pin the server's certificate hash.
  1721. func pinnedSha256List(tlsClientSettings any) ([]string, bool) {
  1722. raw, ok := searchKey(tlsClientSettings, "pinnedPeerCertSha256")
  1723. if !ok {
  1724. return nil, false
  1725. }
  1726. arr, ok := raw.([]any)
  1727. if !ok || len(arr) == 0 {
  1728. return nil, false
  1729. }
  1730. out := make([]string, 0, len(arr))
  1731. for _, v := range arr {
  1732. s, ok := v.(string)
  1733. if !ok || s == "" {
  1734. continue
  1735. }
  1736. out = append(out, s)
  1737. }
  1738. if len(out) == 0 {
  1739. return nil, false
  1740. }
  1741. return out, true
  1742. }
  1743. // hysteriaPinHex normalises a pinnedPeerCertSha256 entry into the 64-character
  1744. // lowercase hex form that Xray-core's Hysteria2 pinSHA256 parser requires.
  1745. //
  1746. // The panel stores pins in several shapes: base64 (xray-core's native TLS
  1747. // format, used by the generate button and the JSON subscription) and hex —
  1748. // either bare or colon-separated as `openssl x509 -fingerprint -sha256` emits
  1749. // it. Hysteria2 clients hex-decode pinSHA256 and crash on a base64 value, so
  1750. // each entry is coerced to bare hex here. Anything that is neither a 32-byte
  1751. // hex nor a 32-byte base64 SHA-256 is returned unchanged so unexpected data is
  1752. // not silently dropped. Mirrors decodeCertPin in internal/web/service/node.go.
  1753. func hysteriaPinHex(pin string) string {
  1754. pin = strings.TrimSpace(pin)
  1755. if h := strings.ReplaceAll(pin, ":", ""); len(h) == hex.EncodedLen(sha256.Size) {
  1756. if _, err := hex.DecodeString(h); err == nil {
  1757. return strings.ToLower(h)
  1758. }
  1759. }
  1760. for _, enc := range []*base64.Encoding{
  1761. base64.StdEncoding,
  1762. base64.RawStdEncoding,
  1763. base64.URLEncoding,
  1764. base64.RawURLEncoding,
  1765. } {
  1766. if b, err := enc.DecodeString(pin); err == nil && len(b) == sha256.Size {
  1767. return hex.EncodeToString(b)
  1768. }
  1769. }
  1770. return pin
  1771. }
  1772. func applyShareRealityParams(stream map[string]any, params map[string]string, clientKey string) {
  1773. params["security"] = "reality"
  1774. realitySetting, _ := stream["realitySettings"].(map[string]any)
  1775. realitySettings, _ := searchKey(realitySetting, "settings")
  1776. if realitySetting != nil {
  1777. if sniValue, ok := searchKey(realitySetting, "serverNames"); ok {
  1778. if sNames, _ := sniValue.([]any); len(sNames) > 0 {
  1779. params["sni"], _ = sNames[random.Num(len(sNames))].(string)
  1780. }
  1781. }
  1782. if pbkValue, ok := searchKey(realitySettings, "publicKey"); ok {
  1783. params["pbk"], _ = pbkValue.(string)
  1784. }
  1785. if sidValue, ok := searchKey(realitySetting, "shortIds"); ok {
  1786. if shortIds, _ := sidValue.([]any); len(shortIds) > 0 {
  1787. params["sid"], _ = shortIds[random.Num(len(shortIds))].(string)
  1788. }
  1789. }
  1790. if fpValue, ok := searchKey(realitySettings, "fingerprint"); ok {
  1791. if fp, ok := fpValue.(string); ok && len(fp) > 0 {
  1792. params["fp"] = fp
  1793. }
  1794. }
  1795. if pqvValue, ok := searchKey(realitySettings, "mldsa65Verify"); ok {
  1796. if pqv, ok := pqvValue.(string); ok && len(pqv) > 0 {
  1797. params["pqv"] = pqv
  1798. }
  1799. }
  1800. seed := ""
  1801. if spxValue, ok := searchKey(realitySettings, "spiderX"); ok {
  1802. seed, _ = spxValue.(string)
  1803. }
  1804. params["spx"] = deriveSpiderX(seed, clientKey)
  1805. }
  1806. }
  1807. // subKey returns a stable per-client identity for deterministic derivations,
  1808. // preferring the subscription id and falling back to the (unique) email.
  1809. func subKey(c model.Client) string {
  1810. if c.SubID != "" {
  1811. return c.SubID
  1812. }
  1813. return c.Email
  1814. }
  1815. // deriveSpiderX maps the inbound's spiderX seed plus a stable client key to a
  1816. // deterministic per-client "/path"; frontend/src/lib/xray/spider-x.ts mirrors it.
  1817. func deriveSpiderX(seed, clientKey string) string {
  1818. if seed == "" && clientKey == "" {
  1819. return "/" + random.Seq(15)
  1820. }
  1821. sum := sha256.Sum256([]byte(seed + "|" + clientKey))
  1822. return "/" + hex.EncodeToString(sum[:])[:15]
  1823. }
  1824. func buildVmessLink(obj map[string]any) string {
  1825. jsonStr, _ := json.MarshalIndent(obj, "", " ")
  1826. return "vmess://" + base64.StdEncoding.EncodeToString(jsonStr)
  1827. }
  1828. func cloneVmessShareObj(baseObj map[string]any, newSecurity string) map[string]any {
  1829. newObj := map[string]any{}
  1830. for key, value := range baseObj {
  1831. if newSecurity != "none" || (key != "alpn" && key != "sni" && key != "fp" && key != "pcs") {
  1832. newObj[key] = value
  1833. }
  1834. }
  1835. return newObj
  1836. }
  1837. func applyExternalProxyTLSObj(ep map[string]any, obj map[string]any, security string) {
  1838. if security != "tls" {
  1839. return
  1840. }
  1841. if sni, ok := externalProxySNI(ep); ok {
  1842. obj["sni"] = sni
  1843. }
  1844. if fp, ok := ep["fingerprint"].(string); ok && fp != "" {
  1845. obj["fp"] = fp
  1846. }
  1847. if alpn, ok := externalProxyALPN(ep["alpn"]); ok {
  1848. obj["alpn"] = alpn
  1849. }
  1850. if pins, ok := externalProxyPins(ep["pinnedPeerCertSha256"]); ok {
  1851. obj["pcs"] = joinAnyStrings(pins)
  1852. }
  1853. if vcn, ok := ep["verifyPeerCertByName"].(string); ok && vcn != "" {
  1854. obj["vcn"] = vcn
  1855. }
  1856. if ech, ok := ep["echConfigList"].(string); ok && ech != "" {
  1857. obj["ech"] = ech
  1858. }
  1859. }
  1860. func applyExternalProxyTLSParams(ep map[string]any, params map[string]string, security string) {
  1861. if security != "tls" {
  1862. return
  1863. }
  1864. if sni, ok := externalProxySNI(ep); ok {
  1865. params["sni"] = sni
  1866. }
  1867. if fp, ok := ep["fingerprint"].(string); ok && fp != "" {
  1868. params["fp"] = fp
  1869. }
  1870. if alpn, ok := externalProxyALPN(ep["alpn"]); ok {
  1871. params["alpn"] = alpn
  1872. }
  1873. if pins, ok := externalProxyPins(ep["pinnedPeerCertSha256"]); ok {
  1874. params["pcs"] = joinAnyStrings(pins)
  1875. }
  1876. if vcn, ok := ep["verifyPeerCertByName"].(string); ok && vcn != "" {
  1877. params["vcn"] = vcn
  1878. }
  1879. if ech, ok := ep["echConfigList"].(string); ok && ech != "" {
  1880. params["ech"] = ech
  1881. }
  1882. }
  1883. // applyExternalProxyHysteriaParams overrides the cert pin for a single
  1884. // external-proxy entry on a Hysteria link. Hysteria carries the pin as a hex
  1885. // `pinSHA256` (not the `pcs` the URL-param protocols use), so each entry is
  1886. // coerced through hysteriaPinHex like the main pin. sni/fp/alpn are left as
  1887. // the inbound's own — Hysteria external proxies are typically alternate
  1888. // endpoints (port-hop / CDN) fronting the same certificate.
  1889. func applyExternalProxyHysteriaParams(ep map[string]any, params map[string]string) {
  1890. if pins, ok := externalProxyPins(ep["pinnedPeerCertSha256"]); ok {
  1891. hexPins := make([]string, 0, len(pins))
  1892. for _, p := range pins {
  1893. if s, ok := p.(string); ok {
  1894. hexPins = append(hexPins, hysteriaPinHex(s))
  1895. }
  1896. }
  1897. params["pinSHA256"] = strings.Join(hexPins, ",")
  1898. }
  1899. if ai, ok := ep["allowInsecure"].(bool); ok && ai {
  1900. params["insecure"] = "1"
  1901. }
  1902. }
  1903. // cloneStreamForExternalProxy returns a shallow clone of stream with
  1904. // tlsSettings (and its nested settings map) deep-copied. The external
  1905. // proxy loop mutates tlsSettings per iteration, so without isolating
  1906. // those maps each proxy's SNI/fingerprint/ALPN would leak into the next.
  1907. func cloneStreamForExternalProxy(stream map[string]any) map[string]any {
  1908. out := cloneMap(stream)
  1909. ts, ok := out["tlsSettings"].(map[string]any)
  1910. if !ok || ts == nil {
  1911. return out
  1912. }
  1913. clonedTs := cloneMap(ts)
  1914. if inner, ok := clonedTs["settings"].(map[string]any); ok && inner != nil {
  1915. clonedTs["settings"] = cloneMap(inner)
  1916. }
  1917. out["tlsSettings"] = clonedTs
  1918. return out
  1919. }
  1920. func applyExternalProxyTLSToStream(ep map[string]any, stream map[string]any, security string) {
  1921. if security != "tls" {
  1922. return
  1923. }
  1924. tlsSettings, _ := stream["tlsSettings"].(map[string]any)
  1925. if tlsSettings == nil {
  1926. tlsSettings = map[string]any{}
  1927. stream["tlsSettings"] = tlsSettings
  1928. }
  1929. if sni, ok := externalProxySNI(ep); ok {
  1930. tlsSettings["serverName"] = sni
  1931. }
  1932. if fp, ok := ep["fingerprint"].(string); ok && fp != "" {
  1933. tlsSettings["fingerprint"] = fp
  1934. }
  1935. if alpn, ok := externalProxyALPNList(ep["alpn"]); ok {
  1936. tlsSettings["alpn"] = alpn
  1937. }
  1938. if pins, ok := externalProxyPins(ep["pinnedPeerCertSha256"]); ok {
  1939. settings, _ := tlsSettings["settings"].(map[string]any)
  1940. if settings == nil {
  1941. settings = map[string]any{}
  1942. tlsSettings["settings"] = settings
  1943. }
  1944. settings["pinnedPeerCertSha256"] = pins
  1945. }
  1946. if ech, ok := ep["echConfigList"].(string); ok && ech != "" {
  1947. settings, _ := tlsSettings["settings"].(map[string]any)
  1948. if settings == nil {
  1949. settings = map[string]any{}
  1950. tlsSettings["settings"] = settings
  1951. }
  1952. settings["echConfigList"] = ech
  1953. }
  1954. if vcn, ok := ep["verifyPeerCertByName"].(string); ok && vcn != "" {
  1955. settings, _ := tlsSettings["settings"].(map[string]any)
  1956. if settings == nil {
  1957. settings = map[string]any{}
  1958. tlsSettings["settings"] = settings
  1959. }
  1960. settings["verifyPeerCertByName"] = vcn
  1961. }
  1962. if ai, ok := ep["allowInsecure"].(bool); ok && ai {
  1963. settings, _ := tlsSettings["settings"].(map[string]any)
  1964. if settings == nil {
  1965. settings = map[string]any{}
  1966. tlsSettings["settings"] = settings
  1967. }
  1968. settings["allowInsecure"] = true
  1969. }
  1970. }
  1971. func externalProxySNI(ep map[string]any) (string, bool) {
  1972. if sni, ok := ep["sni"].(string); ok && sni != "" {
  1973. return sni, true
  1974. }
  1975. return "", false
  1976. }
  1977. func externalProxyALPN(value any) (string, bool) {
  1978. switch v := value.(type) {
  1979. case string:
  1980. return v, v != ""
  1981. case []string:
  1982. if len(v) == 0 {
  1983. return "", false
  1984. }
  1985. return strings.Join(v, ","), true
  1986. case []any:
  1987. alpn := make([]string, 0, len(v))
  1988. for _, item := range v {
  1989. if s, ok := item.(string); ok && s != "" {
  1990. alpn = append(alpn, s)
  1991. }
  1992. }
  1993. if len(alpn) == 0 {
  1994. return "", false
  1995. }
  1996. return strings.Join(alpn, ","), true
  1997. default:
  1998. return "", false
  1999. }
  2000. }
  2001. func externalProxyALPNList(value any) ([]any, bool) {
  2002. switch v := value.(type) {
  2003. case string:
  2004. if v == "" {
  2005. return nil, false
  2006. }
  2007. parts := strings.Split(v, ",")
  2008. out := make([]any, 0, len(parts))
  2009. for _, part := range parts {
  2010. if part = strings.TrimSpace(part); part != "" {
  2011. out = append(out, part)
  2012. }
  2013. }
  2014. return out, len(out) > 0
  2015. case []string:
  2016. out := make([]any, 0, len(v))
  2017. for _, item := range v {
  2018. if item != "" {
  2019. out = append(out, item)
  2020. }
  2021. }
  2022. return out, len(out) > 0
  2023. case []any:
  2024. out := make([]any, 0, len(v))
  2025. for _, item := range v {
  2026. if s, ok := item.(string); ok && s != "" {
  2027. out = append(out, s)
  2028. }
  2029. }
  2030. return out, len(out) > 0
  2031. default:
  2032. return nil, false
  2033. }
  2034. }
  2035. // externalProxyPins extracts an external-proxy entry's pinnedPeerCertSha256
  2036. // as a []any of non-empty strings. The []any element type matches what the
  2037. // JSON/Clash sub builders expect when reading the value back off the cloned
  2038. // stream's tlsSettings.settings.
  2039. func externalProxyPins(value any) ([]any, bool) {
  2040. switch v := value.(type) {
  2041. case []string:
  2042. out := make([]any, 0, len(v))
  2043. for _, item := range v {
  2044. if item != "" {
  2045. out = append(out, item)
  2046. }
  2047. }
  2048. return out, len(out) > 0
  2049. case []any:
  2050. out := make([]any, 0, len(v))
  2051. for _, item := range v {
  2052. if s, ok := item.(string); ok && s != "" {
  2053. out = append(out, s)
  2054. }
  2055. }
  2056. return out, len(out) > 0
  2057. default:
  2058. return nil, false
  2059. }
  2060. }
  2061. func joinAnyStrings(items []any) string {
  2062. parts := make([]string, 0, len(items))
  2063. for _, item := range items {
  2064. if s, ok := item.(string); ok {
  2065. parts = append(parts, s)
  2066. }
  2067. }
  2068. return strings.Join(parts, ",")
  2069. }
  2070. // buildVmessExternalProxyLinks is a thin adapter: it maps the legacy
  2071. // externalProxy entries to []ShareEndpoint and renders them through the unified
  2072. // endpoint path. Kept as a thin shim over the unified endpoint builder so
  2073. // genVmessLink keeps calling one helper (now threading transport through).
  2074. func (s *SubService) buildVmessExternalProxyLinks(externalProxies []any, baseObj map[string]any, inbound *model.Inbound, email string, transport string) string {
  2075. eps := make([]ShareEndpoint, 0, len(externalProxies))
  2076. for _, externalProxy := range externalProxies {
  2077. ep, _ := externalProxy.(map[string]any)
  2078. eps = append(eps, externalProxyToEndpoint(ep))
  2079. }
  2080. return s.buildEndpointVmessLinks(eps, baseObj, inbound, email, transport)
  2081. }
  2082. // buildLinkWithParams appends ?query and #fragment to a pre-built
  2083. // scheme://userinfo@host:port string without re-parsing it. The caller
  2084. // has already escaped userinfo via encodeUserinfo (or chosen a base64
  2085. // alphabet with no reserved chars); a url.Parse + .String() round-trip
  2086. // would silently decode that escaping because Go's userinfo emitter
  2087. // leaves sub-delims (=, +, ;) literal, which breaks Trojan/Hysteria/SS
  2088. // clients that reject those chars in the password.
  2089. func buildLinkWithParams(link string, params map[string]string, fragment string) string {
  2090. return appendQueryAndFragment(link, params, fragment, "", false)
  2091. }
  2092. // buildLinkWithParamsAndSecurity is buildLinkWithParams plus an
  2093. // external-proxy override: the `security` key in params is replaced with
  2094. // the supplied value, and TLS hint fields (alpn/sni/fp/pcs) are stripped
  2095. // when the override is `none`.
  2096. func buildLinkWithParamsAndSecurity(link string, params map[string]string, fragment, security string, omitTLSFields bool) string {
  2097. return appendQueryAndFragment(link, params, fragment, security, omitTLSFields)
  2098. }
  2099. func appendQueryAndFragment(link string, params map[string]string, fragment, securityOverride string, omitTLSFields bool) string {
  2100. var sb strings.Builder
  2101. sb.WriteString(link)
  2102. if len(params) > 0 {
  2103. q := url.Values{}
  2104. for k, v := range params {
  2105. if securityOverride != "" && k == "security" {
  2106. v = securityOverride
  2107. }
  2108. if omitTLSFields && (k == "alpn" || k == "sni" || k == "fp" || k == "pcs") {
  2109. continue
  2110. }
  2111. q.Set(k, v)
  2112. }
  2113. encoded := q.Encode()
  2114. if encoded != "" {
  2115. if strings.Contains(link, "?") {
  2116. sb.WriteByte('&')
  2117. } else {
  2118. sb.WriteByte('?')
  2119. }
  2120. sb.WriteString(encoded)
  2121. }
  2122. }
  2123. if fragment != "" {
  2124. sb.WriteByte('#')
  2125. // Match the frontend's encodeURIComponent(remark): spaces become %20.
  2126. sb.WriteString(strings.ReplaceAll(url.QueryEscape(fragment), "+", "%20"))
  2127. }
  2128. return sb.String()
  2129. }
  2130. // buildExternalProxyURLLinks is a thin adapter: it maps the legacy externalProxy
  2131. // entries to []ShareEndpoint and renders them through the unified endpoint path.
  2132. // Kept so the genVless/genTrojan/genShadowsocks call sites are unchanged.
  2133. func (s *SubService) buildExternalProxyURLLinks(
  2134. externalProxies []any,
  2135. params map[string]string,
  2136. baseSecurity string,
  2137. makeLink func(ep map[string]any, dest string, port int) string,
  2138. makeRemark func(ep map[string]any) string,
  2139. ) string {
  2140. eps := make([]ShareEndpoint, 0, len(externalProxies))
  2141. for _, externalProxy := range externalProxies {
  2142. ep, _ := externalProxy.(map[string]any)
  2143. eps = append(eps, externalProxyToEndpoint(ep))
  2144. }
  2145. return s.buildEndpointLinks(eps, params, baseSecurity, func(e ShareEndpoint) string {
  2146. return makeLink(e.ep, e.Address, e.Port)
  2147. }, func(e ShareEndpoint) string {
  2148. return makeRemark(e.ep)
  2149. })
  2150. }
  2151. func cloneStringMap(source map[string]string) map[string]string {
  2152. cloned := make(map[string]string, len(source))
  2153. maps.Copy(cloned, source)
  2154. return cloned
  2155. }
  2156. // genRemark builds the remark for a non-host link (raw default / legacy
  2157. // externalProxy / synthetic JSON-Clash entry). A set remark template drives it
  2158. // in both the body and display contexts (genTemplatedRemark renders the
  2159. // name-only part on displays); with no template it falls back to the inbound
  2160. // remark, extra and email joined by "-".
  2161. func (s *SubService) genRemark(inbound *model.Inbound, email string, extra string, transport string) string {
  2162. if s.remarkTemplate != "" {
  2163. return s.genTemplatedRemark(inbound, s.lookupClient(inbound, email), extra, transport)
  2164. }
  2165. return fallbackRemark(inbound.Remark, extra, email)
  2166. }
  2167. func fallbackRemark(parts ...string) string {
  2168. out := make([]string, 0, len(parts))
  2169. for _, p := range parts {
  2170. if p != "" {
  2171. out = append(out, p)
  2172. }
  2173. }
  2174. return strings.Join(out, "-")
  2175. }
  2176. // findClientStats returns the inbound's traffic record for email, if present.
  2177. func (s *SubService) findClientStats(inbound *model.Inbound, email string) (xray.ClientTraffic, bool) {
  2178. for _, clientStat := range inbound.ClientStats {
  2179. if clientStat.Email == email {
  2180. return clientStat, true
  2181. }
  2182. }
  2183. return xray.ClientTraffic{}, false
  2184. }
  2185. // statsByEmailFromDB resolves a client's traffic row straight from the DB by its
  2186. // globally-unique email, caching the hit into statsByEmail for the rest of the
  2187. // request. It's the last-resort lookup behind statsForClient: the preloaded
  2188. // ClientStats and the statsByEmail index are both keyed by
  2189. // client_traffics.inbound_id, which is written once by AddClientStat and never
  2190. // updated. When an inbound is deleted and recreated it gets a new id, so the old
  2191. // row is orphaned from every loaded inbound and both in-memory paths miss —
  2192. // leaving {{TRAFFIC_USED}} stuck at 0 for pre-existing clients even though their
  2193. // usage is intact (#5567). Matching by email recovers it, the same way the
  2194. // sub-info header's AggregateTrafficByEmails already does.
  2195. func (s *SubService) statsByEmailFromDB(email string) (xray.ClientTraffic, bool) {
  2196. db := database.GetDB()
  2197. if db == nil {
  2198. return xray.ClientTraffic{}, false
  2199. }
  2200. var row xray.ClientTraffic
  2201. if err := db.Model(&xray.ClientTraffic{}).Where("email = ?", email).First(&row).Error; err != nil {
  2202. return xray.ClientTraffic{}, false
  2203. }
  2204. if s.statsByEmail == nil {
  2205. s.statsByEmail = map[string]xray.ClientTraffic{}
  2206. }
  2207. s.statsByEmail[email] = row
  2208. return row, true
  2209. }
  2210. func searchKey(data any, key string) (any, bool) {
  2211. switch val := data.(type) {
  2212. case map[string]any:
  2213. for k, v := range val {
  2214. if k == key {
  2215. return v, true
  2216. }
  2217. if result, ok := searchKey(v, key); ok {
  2218. return result, true
  2219. }
  2220. }
  2221. case []any:
  2222. for _, v := range val {
  2223. if result, ok := searchKey(v, key); ok {
  2224. return result, true
  2225. }
  2226. }
  2227. }
  2228. return nil, false
  2229. }
  2230. // buildXhttpExtra walks an xhttpSettings map and returns the JSON blob
  2231. // that goes into the URL's `extra` param (or, for VMess, the link
  2232. // object). Carries ONLY the bidirectional fields from xray-core's
  2233. // SplitHTTPConfig — i.e. the ones the server enforces and the client
  2234. // must match. Strictly one-sided fields are excluded:
  2235. //
  2236. // - server-only (noSSEHeader, scMaxBufferedPosts, scStreamUpServerSecs,
  2237. // serverMaxHeaderBytes) — client wouldn't read them, so emitting
  2238. // them just bloats the URL.
  2239. // - client-only values are included only when present in the inbound
  2240. // JSON. Some deployments/imported configs carry them there, and the
  2241. // subscription link is the only place clients can receive them.
  2242. //
  2243. // Truthy-only guards keep default inbounds emitting the same compact URL
  2244. // they did before this helper grew.
  2245. func buildXhttpExtra(xhttp map[string]any) map[string]any {
  2246. if xhttp == nil {
  2247. return nil
  2248. }
  2249. extra := map[string]any{}
  2250. if mode, ok := xhttp["mode"].(string); ok && len(mode) > 0 {
  2251. extra["mode"] = mode
  2252. }
  2253. if xpb, ok := xhttp["xPaddingBytes"].(string); ok && len(xpb) > 0 {
  2254. extra["xPaddingBytes"] = xpb
  2255. }
  2256. if obfs, ok := xhttp["xPaddingObfsMode"].(bool); ok && obfs {
  2257. extra["xPaddingObfsMode"] = true
  2258. for _, field := range []string{"xPaddingKey", "xPaddingHeader", "xPaddingPlacement", "xPaddingMethod"} {
  2259. if v, ok := xhttp[field].(string); ok && len(v) > 0 {
  2260. extra[field] = v
  2261. }
  2262. }
  2263. }
  2264. stringFields := []string{
  2265. "uplinkHTTPMethod",
  2266. "sessionIDPlacement", "sessionIDKey", "sessionIDTable", "sessionIDLength",
  2267. "seqPlacement", "seqKey",
  2268. "uplinkDataPlacement", "uplinkDataKey",
  2269. "scMaxEachPostBytes", "scMinPostsIntervalMs",
  2270. }
  2271. // Values matching xray-core's own defaults are redundant on the wire and
  2272. // the literal scMinPostsIntervalMs=30 is a known DPI fingerprint (#5141).
  2273. // Old panels seeded these defaults into every xhttp inbound, so filter
  2274. // them here instead of requiring every stored config to be re-saved.
  2275. coreDefaults := map[string]string{
  2276. "scMaxEachPostBytes": "1000000",
  2277. "scMinPostsIntervalMs": "30",
  2278. }
  2279. for _, field := range stringFields {
  2280. if v, ok := xhttp[field].(string); ok && len(v) > 0 && v != coreDefaults[field] {
  2281. extra[field] = v
  2282. }
  2283. }
  2284. // Legacy inbounds (pre xray-core #6258) stored sessionPlacement/sessionKey.
  2285. // Lift them onto the renamed keys so links from not-yet-resaved configs
  2286. // still carry the session settings. Mirrors the frontend migration.
  2287. for legacy, renamed := range map[string]string{
  2288. "sessionPlacement": "sessionIDPlacement",
  2289. "sessionKey": "sessionIDKey",
  2290. } {
  2291. if _, exists := extra[renamed]; !exists {
  2292. if v, ok := xhttp[legacy].(string); ok && len(v) > 0 {
  2293. extra[renamed] = v
  2294. }
  2295. }
  2296. }
  2297. // Older clients still read the pre-#6258 names from the subscription
  2298. // extra JSON. Emit aliases after lifting legacy inputs so both old and
  2299. // new clients can consume the same link.
  2300. if v, ok := extra["sessionIDPlacement"].(string); ok && len(v) > 0 {
  2301. extra["sessionPlacement"] = v
  2302. }
  2303. if v, ok := extra["sessionIDKey"].(string); ok && len(v) > 0 {
  2304. extra["sessionKey"] = v
  2305. }
  2306. for _, field := range []string{"uplinkChunkSize"} {
  2307. if v, ok := nonZeroShareValue(xhttp[field]); ok {
  2308. extra[field] = v
  2309. }
  2310. }
  2311. for _, field := range []string{"noGRPCHeader"} {
  2312. if v, ok := xhttp[field].(bool); ok && v {
  2313. extra[field] = v
  2314. }
  2315. }
  2316. for _, field := range []string{"xmux", "downloadSettings"} {
  2317. if v, ok := nonEmptyShareObject(xhttp[field]); ok {
  2318. extra[field] = v
  2319. }
  2320. }
  2321. // Headers — emitted as the {name: value} map upstream's struct
  2322. // expects. The server runtime ignores this field, but the client
  2323. // (consuming the share link) honors it. Drop any "host" entry —
  2324. // host already wins as a top-level URL param.
  2325. if rawHeaders, ok := xhttp["headers"].(map[string]any); ok && len(rawHeaders) > 0 {
  2326. out := map[string]any{}
  2327. for k, v := range rawHeaders {
  2328. if strings.EqualFold(k, "host") {
  2329. continue
  2330. }
  2331. out[k] = v
  2332. }
  2333. if len(out) > 0 {
  2334. extra["headers"] = out
  2335. }
  2336. }
  2337. if len(extra) == 0 {
  2338. return nil
  2339. }
  2340. return extra
  2341. }
  2342. func nonZeroShareValue(v any) (any, bool) {
  2343. switch value := v.(type) {
  2344. case string:
  2345. return value, value != ""
  2346. case int:
  2347. return value, value != 0
  2348. case int32:
  2349. return value, value != 0
  2350. case int64:
  2351. return value, value != 0
  2352. case float32:
  2353. return value, value != 0
  2354. case float64:
  2355. return value, value != 0
  2356. default:
  2357. return nil, false
  2358. }
  2359. }
  2360. func nonEmptyShareObject(v any) (any, bool) {
  2361. switch value := v.(type) {
  2362. case map[string]any:
  2363. return value, len(value) > 0
  2364. case map[string]string:
  2365. return value, len(value) > 0
  2366. case []any:
  2367. return value, len(value) > 0
  2368. default:
  2369. return nil, false
  2370. }
  2371. }
  2372. // applyXhttpExtraParams emits the full xhttp config into the URL query
  2373. // params of a vless:// / trojan:// / ss:// link. Sets path/host/mode at
  2374. // top level (xray's Build() always lets these win over `extra`) and packs
  2375. // everything else into a JSON `extra` param. Also writes the flat
  2376. // `x_padding_bytes` param sing-box-family clients understand.
  2377. //
  2378. // Without this, the admin's custom xPaddingBytes / sessionKey / etc. never
  2379. // reach the client and handshakes are silently rejected with
  2380. // `invalid padding (...) length: 0` — the client-visible symptom is
  2381. // "xhttp doesn't connect" on OpenWRT / sing-box.
  2382. //
  2383. // Two encodings are written so every popular client can read at least one:
  2384. //
  2385. // - x_padding_bytes=<range> — flat param, understood by sing-box and its
  2386. // derivatives (Podkop, OpenWRT sing-box, Karing, NekoBox, …).
  2387. // - extra=<url-encoded-json> — full xhttp settings blob, which is how
  2388. // xray-core clients (v2rayNG, Happ, Furious, Exclave, …) pick up the
  2389. // bidirectional fields beyond path/host/mode.
  2390. func applyXhttpExtraParams(xhttp map[string]any, params map[string]string) {
  2391. if xhttp == nil {
  2392. return
  2393. }
  2394. applyPathAndHostParams(xhttp, params)
  2395. if mode, ok := xhttp["mode"].(string); ok {
  2396. params["mode"] = mode
  2397. }
  2398. if xpb, ok := xhttp["xPaddingBytes"].(string); ok && len(xpb) > 0 {
  2399. params["x_padding_bytes"] = xpb
  2400. }
  2401. extra := buildXhttpExtra(xhttp)
  2402. if extra != nil {
  2403. if b, err := json.Marshal(extra); err == nil {
  2404. params["extra"] = string(b)
  2405. }
  2406. }
  2407. }
  2408. var kcpMaskToHeaderType = map[string]string{
  2409. "dns": "dns",
  2410. "dtls": "dtls",
  2411. "srtp": "srtp",
  2412. "utp": "utp",
  2413. "wechat": "wechat-video",
  2414. "wireguard": "wireguard",
  2415. }
  2416. var validFinalMaskUDPTypes = map[string]struct{}{
  2417. "salamander": {},
  2418. "mkcp-legacy": {},
  2419. "xdns": {},
  2420. "xicmp": {},
  2421. "noise": {},
  2422. "header-custom": {},
  2423. "realm": {},
  2424. "udphop": {},
  2425. }
  2426. var validFinalMaskTCPTypes = map[string]struct{}{
  2427. "header-custom": {},
  2428. "fragment": {},
  2429. "sudoku": {},
  2430. "xmc": {},
  2431. }
  2432. // applyKcpShareParams reconstructs legacy KCP share-link fields from either
  2433. // the historical kcpSettings.header/seed shape or the current finalmask model.
  2434. // This keeps subscription output compatible while avoiding panics when older
  2435. // keys are absent from modern inbounds.
  2436. func applyKcpShareParams(stream map[string]any, params map[string]string) {
  2437. extractKcpShareFields(stream).applyToParams(params)
  2438. }
  2439. func applyKcpShareObj(stream map[string]any, obj map[string]any) {
  2440. extractKcpShareFields(stream).applyToObj(obj)
  2441. }
  2442. type kcpShareFields struct {
  2443. headerType string
  2444. seed string
  2445. mtu int
  2446. tti int
  2447. }
  2448. func (f kcpShareFields) applyToParams(params map[string]string) {
  2449. if f.headerType != "" && f.headerType != "none" {
  2450. params["headerType"] = f.headerType
  2451. }
  2452. setStringParam(params, "seed", f.seed)
  2453. setIntParam(params, "mtu", f.mtu)
  2454. setIntParam(params, "tti", f.tti)
  2455. }
  2456. func (f kcpShareFields) applyToObj(obj map[string]any) {
  2457. if f.headerType != "" && f.headerType != "none" {
  2458. obj["type"] = f.headerType
  2459. }
  2460. setStringField(obj, "path", f.seed)
  2461. setIntField(obj, "mtu", f.mtu)
  2462. setIntField(obj, "tti", f.tti)
  2463. }
  2464. func extractKcpShareFields(stream map[string]any) kcpShareFields {
  2465. fields := kcpShareFields{headerType: "none"}
  2466. if kcp, ok := stream["kcpSettings"].(map[string]any); ok {
  2467. if header, ok := kcp["header"].(map[string]any); ok {
  2468. if value, ok := header["type"].(string); ok && value != "" {
  2469. fields.headerType = value
  2470. }
  2471. }
  2472. if value, ok := kcp["seed"].(string); ok && value != "" {
  2473. fields.seed = value
  2474. }
  2475. if value, ok := readPositiveInt(kcp["mtu"]); ok {
  2476. fields.mtu = value
  2477. }
  2478. if value, ok := readPositiveInt(kcp["tti"]); ok {
  2479. fields.tti = value
  2480. }
  2481. }
  2482. for _, rawMask := range normalizedFinalMaskUDPMasks(stream["finalmask"]) {
  2483. mask, _ := rawMask.(map[string]any)
  2484. if mask == nil {
  2485. continue
  2486. }
  2487. if maskType, _ := mask["type"].(string); maskType != "mkcp-legacy" {
  2488. continue
  2489. }
  2490. settings, _ := mask["settings"].(map[string]any)
  2491. header, _ := settings["header"].(string)
  2492. value, _ := settings["value"].(string)
  2493. if header == "" {
  2494. fields.seed = value
  2495. continue
  2496. }
  2497. if mapped, ok := kcpMaskToHeaderType[header]; ok {
  2498. fields.headerType = mapped
  2499. }
  2500. }
  2501. return fields
  2502. }
  2503. func readPositiveInt(value any) (int, bool) {
  2504. switch number := value.(type) {
  2505. case int:
  2506. return number, number > 0
  2507. case int32:
  2508. return int(number), number > 0
  2509. case int64:
  2510. return int(number), number > 0
  2511. case float32:
  2512. parsed := int(number)
  2513. return parsed, parsed > 0
  2514. case float64:
  2515. parsed := int(number)
  2516. return parsed, parsed > 0
  2517. default:
  2518. return 0, false
  2519. }
  2520. }
  2521. func setStringParam(params map[string]string, key, value string) {
  2522. if value == "" {
  2523. delete(params, key)
  2524. return
  2525. }
  2526. params[key] = value
  2527. }
  2528. func setIntParam(params map[string]string, key string, value int) {
  2529. if value <= 0 {
  2530. delete(params, key)
  2531. return
  2532. }
  2533. params[key] = fmt.Sprintf("%d", value)
  2534. }
  2535. func setStringField(obj map[string]any, key, value string) {
  2536. if value == "" {
  2537. delete(obj, key)
  2538. return
  2539. }
  2540. obj[key] = value
  2541. }
  2542. func setIntField(obj map[string]any, key string, value int) {
  2543. if value <= 0 {
  2544. delete(obj, key)
  2545. return
  2546. }
  2547. obj[key] = value
  2548. }
  2549. // applyFinalMaskParams exports the finalmask payload as the compact
  2550. // `fm=<json>` share-link field used by v2rayN-compatible clients.
  2551. func applyFinalMaskParams(finalmask map[string]any, params map[string]string) {
  2552. if fm, ok := marshalFinalMask(finalmask); ok {
  2553. params["fm"] = fm
  2554. }
  2555. }
  2556. func applyFinalMaskObj(finalmask map[string]any, obj map[string]any) {
  2557. if fm, ok := marshalFinalMask(finalmask); ok {
  2558. obj["fm"] = fm
  2559. }
  2560. }
  2561. func marshalFinalMask(finalmask map[string]any) (string, bool) {
  2562. normalized := normalizeFinalMask(finalmask)
  2563. if !hasFinalMaskContent(normalized) {
  2564. return "", false
  2565. }
  2566. b, err := json.Marshal(normalized)
  2567. if err != nil || len(b) == 0 || string(b) == "null" {
  2568. return "", false
  2569. }
  2570. return string(b), true
  2571. }
  2572. func normalizeFinalMask(finalmask map[string]any) map[string]any {
  2573. tcpMasks := normalizedFinalMaskTCPMasks(finalmask)
  2574. udpMasks := normalizedFinalMaskUDPMasks(finalmask)
  2575. quicParams, hasQuicParams := finalmask["quicParams"].(map[string]any)
  2576. if len(tcpMasks) == 0 && len(udpMasks) == 0 && !hasQuicParams {
  2577. return nil
  2578. }
  2579. result := map[string]any{}
  2580. if len(tcpMasks) > 0 {
  2581. result["tcp"] = tcpMasks
  2582. }
  2583. if len(udpMasks) > 0 {
  2584. result["udp"] = udpMasks
  2585. }
  2586. if hasQuicParams && len(quicParams) > 0 {
  2587. result["quicParams"] = quicParams
  2588. }
  2589. return result
  2590. }
  2591. func normalizedFinalMaskTCPMasks(value any) []any {
  2592. finalmask, _ := value.(map[string]any)
  2593. if finalmask == nil {
  2594. return nil
  2595. }
  2596. rawMasks, _ := finalmask["tcp"].([]any)
  2597. if len(rawMasks) == 0 {
  2598. return nil
  2599. }
  2600. normalized := make([]any, 0, len(rawMasks))
  2601. for _, rawMask := range rawMasks {
  2602. mask, _ := rawMask.(map[string]any)
  2603. if mask == nil {
  2604. continue
  2605. }
  2606. maskType, _ := mask["type"].(string)
  2607. if _, ok := validFinalMaskTCPTypes[maskType]; !ok || maskType == "" {
  2608. continue
  2609. }
  2610. normalizedMask := map[string]any{"type": maskType}
  2611. if settings, ok := mask["settings"].(map[string]any); ok && len(settings) > 0 {
  2612. normalizedMask["settings"] = settings
  2613. }
  2614. normalized = append(normalized, normalizedMask)
  2615. }
  2616. if len(normalized) == 0 {
  2617. return nil
  2618. }
  2619. return normalized
  2620. }
  2621. func normalizedFinalMaskUDPMasks(value any) []any {
  2622. finalmask, _ := value.(map[string]any)
  2623. if finalmask == nil {
  2624. return nil
  2625. }
  2626. rawMasks, _ := finalmask["udp"].([]any)
  2627. if len(rawMasks) == 0 {
  2628. return nil
  2629. }
  2630. normalized := make([]any, 0, len(rawMasks))
  2631. for _, rawMask := range rawMasks {
  2632. mask, _ := rawMask.(map[string]any)
  2633. if mask == nil {
  2634. continue
  2635. }
  2636. maskType, _ := mask["type"].(string)
  2637. if _, ok := validFinalMaskUDPTypes[maskType]; !ok || maskType == "" {
  2638. continue
  2639. }
  2640. normalizedMask := map[string]any{"type": maskType}
  2641. if settings, ok := mask["settings"].(map[string]any); ok && len(settings) > 0 {
  2642. normalizedMask["settings"] = settings
  2643. }
  2644. normalized = append(normalized, normalizedMask)
  2645. }
  2646. if len(normalized) == 0 {
  2647. return nil
  2648. }
  2649. return normalized
  2650. }
  2651. func hasFinalMaskContent(value any) bool {
  2652. switch v := value.(type) {
  2653. case nil:
  2654. return false
  2655. case string:
  2656. return len(v) > 0
  2657. case map[string]any:
  2658. for _, item := range v {
  2659. if hasFinalMaskContent(item) {
  2660. return true
  2661. }
  2662. }
  2663. return false
  2664. case []any:
  2665. return slices.ContainsFunc(v, hasFinalMaskContent)
  2666. default:
  2667. return true
  2668. }
  2669. }
  2670. func searchHost(headers any) string {
  2671. data, _ := headers.(map[string]any)
  2672. for k, v := range data {
  2673. if strings.EqualFold(k, "host") {
  2674. switch v.(type) {
  2675. case []any:
  2676. hosts, _ := v.([]any)
  2677. if len(hosts) > 0 {
  2678. h, _ := hosts[0].(string)
  2679. return h
  2680. }
  2681. return ""
  2682. case any:
  2683. h, _ := v.(string)
  2684. return h
  2685. }
  2686. }
  2687. }
  2688. return ""
  2689. }
  2690. // PageData is a view model for subpage.html
  2691. // PageData contains data for rendering the subscription information page.
  2692. type PageData struct {
  2693. Host string
  2694. BasePath string
  2695. SId string
  2696. Enabled bool
  2697. IsOnline bool
  2698. Download string
  2699. Upload string
  2700. Total string
  2701. Used string
  2702. Remained string
  2703. Expire int64
  2704. LastOnline int64
  2705. Datepicker string
  2706. DownloadByte int64
  2707. UploadByte int64
  2708. TotalByte int64
  2709. SubUrl string
  2710. SubJsonUrl string
  2711. SubClashUrl string
  2712. SubTitle string
  2713. SubSupportUrl string
  2714. SubAnnounce string
  2715. Result []string
  2716. Emails []string
  2717. }
  2718. // ResolveRequest extracts scheme and host info from request/headers consistently.
  2719. // ResolveRequest extracts scheme, host, and header information from an HTTP request.
  2720. func (s *SubService) ResolveRequest(c *gin.Context) (scheme string, host string, hostWithPort string, hostHeader string) {
  2721. trusted := s.forwardedHeadersTrusted(c)
  2722. if !trusted {
  2723. warnSuppressedForwardedHeaders(c)
  2724. }
  2725. forwarded := func(name string) string {
  2726. if !trusted {
  2727. return ""
  2728. }
  2729. return c.GetHeader(name)
  2730. }
  2731. // scheme
  2732. scheme = "http"
  2733. if c.Request.TLS != nil || strings.EqualFold(forwarded("X-Forwarded-Proto"), "https") {
  2734. scheme = "https"
  2735. }
  2736. // base host (no port)
  2737. if h, err := getHostFromXFH(forwarded("X-Forwarded-Host")); err == nil && h != "" {
  2738. host = h
  2739. }
  2740. if host == "" {
  2741. host = forwarded("X-Real-IP")
  2742. }
  2743. if host == "" {
  2744. var err error
  2745. host, _, err = net.SplitHostPort(c.Request.Host)
  2746. if err != nil {
  2747. host = c.Request.Host
  2748. }
  2749. }
  2750. // host:port for URLs
  2751. hostWithPort = forwarded("X-Forwarded-Host")
  2752. if hostWithPort == "" {
  2753. hostWithPort = c.Request.Host
  2754. }
  2755. if hostWithPort == "" {
  2756. hostWithPort = host
  2757. }
  2758. // header display host
  2759. hostHeader = forwarded("X-Forwarded-Host")
  2760. if hostHeader == "" {
  2761. hostHeader = forwarded("X-Real-IP")
  2762. }
  2763. if hostHeader == "" {
  2764. hostHeader = host
  2765. }
  2766. return
  2767. }
  2768. // BuildURLs constructs absolute subscription and JSON subscription URLs for a given subscription ID.
  2769. // It prioritizes configured URIs, then individual settings, and finally falls back to request-derived components.
  2770. func (s *SubService) BuildURLs(subPath, subJsonPath, subClashPath, subId string) (subURL, subJsonURL, subClashURL string) {
  2771. if subId == "" {
  2772. return "", "", ""
  2773. }
  2774. configuredSubURI, _ := s.settingService.GetSubURI()
  2775. configuredSubJsonURI, _ := s.settingService.GetSubJsonURI()
  2776. configuredSubClashURI, _ := s.settingService.GetSubClashURI()
  2777. // Same base as the panel's Client Information page; s.address is the
  2778. // subscriber's host already normalized away from any loopback/bind IP.
  2779. base := s.settingService.BuildSubURIBase(s.address)
  2780. subURL = s.buildSingleURL(configuredSubURI, base, subPath, subId)
  2781. // When subURI is explicitly configured (reverse-proxy setup), use its
  2782. // scheme+host as the base for JSON and Clash URLs so they match the
  2783. // reverse-proxy endpoint instead of the raw sub-server port. Fall back
  2784. // to the request-derived base if subURI is empty or can't be parsed
  2785. // into a scheme+host (e.g. a malformed value with no scheme).
  2786. jsonClashBase := base
  2787. if configuredSubURI != "" {
  2788. if derived := s.extractBaseFromURI(configuredSubURI); derived != "" {
  2789. jsonClashBase = derived
  2790. }
  2791. }
  2792. subJsonURL = s.buildSingleURL(configuredSubJsonURI, jsonClashBase, subJsonPath, subId)
  2793. subClashURL = s.buildSingleURL(configuredSubClashURI, jsonClashBase, subClashPath, subId)
  2794. return subURL, subJsonURL, subClashURL
  2795. }
  2796. // extractBaseFromURI extracts scheme://host from a configured URI.
  2797. // e.g., "https://example.com/sub-xxx/" → "https://example.com".
  2798. // Returns "" when the URI is empty or lacks a scheme/host, so callers can
  2799. // fall back to the request-derived base instead of emitting a broken value.
  2800. func (s *SubService) extractBaseFromURI(uri string) string {
  2801. u, err := url.Parse(uri)
  2802. if err != nil || u.Scheme == "" || u.Host == "" {
  2803. return ""
  2804. }
  2805. return fmt.Sprintf("%s://%s", u.Scheme, u.Host)
  2806. }
  2807. // buildSingleURL constructs a single URL using configured URI or base components
  2808. func (s *SubService) buildSingleURL(configuredURI, base, basePath, subId string) string {
  2809. if configuredURI != "" {
  2810. return s.joinPathWithID(configuredURI, subId)
  2811. }
  2812. return s.joinPathWithID(base+basePath, subId)
  2813. }
  2814. // joinPathWithID safely joins a base path with a subscription ID
  2815. func (s *SubService) joinPathWithID(basePath, subId string) string {
  2816. if strings.HasSuffix(basePath, "/") {
  2817. return basePath + subId
  2818. }
  2819. return basePath + "/" + subId
  2820. }
  2821. // BuildPageData parses header and prepares the template view model.
  2822. // BuildPageData constructs page data for rendering the subscription information page.
  2823. func (s *SubService) BuildPageData(subId string, hostHeader string, traffic xray.ClientTraffic, lastOnline int64, subs []string, emails []string, subURL, subJsonURL, subClashURL string, basePath string, subTitle string, subSupportUrl string) PageData {
  2824. download := common.FormatTraffic(traffic.Down)
  2825. upload := common.FormatTraffic(traffic.Up)
  2826. total := "∞"
  2827. used := common.FormatTraffic(traffic.Up + traffic.Down)
  2828. remained := ""
  2829. if traffic.Total > 0 {
  2830. total = common.FormatTraffic(traffic.Total)
  2831. left := max(traffic.Total-(traffic.Up+traffic.Down), 0)
  2832. remained = common.FormatTraffic(left)
  2833. }
  2834. datepicker := s.datepicker
  2835. if datepicker == "" {
  2836. datepicker = "gregorian"
  2837. }
  2838. pageLinks := make([]string, 0, len(subs))
  2839. pageEmails := make([]string, 0, len(subs))
  2840. for i, sub := range subs {
  2841. email := ""
  2842. if i < len(emails) {
  2843. email = emails[i]
  2844. }
  2845. for _, link := range splitLinkLines(sub) {
  2846. pageLinks = append(pageLinks, link)
  2847. pageEmails = append(pageEmails, email)
  2848. }
  2849. }
  2850. return PageData{
  2851. Host: hostHeader,
  2852. BasePath: basePath,
  2853. SId: subId,
  2854. Enabled: traffic.Enable,
  2855. IsOnline: subIsOnline(emails, s.inboundService.GetOnlineClients()),
  2856. Download: download,
  2857. Upload: upload,
  2858. Total: total,
  2859. Used: used,
  2860. Remained: remained,
  2861. Expire: traffic.ExpiryTime / 1000,
  2862. LastOnline: lastOnline,
  2863. Datepicker: datepicker,
  2864. DownloadByte: traffic.Down,
  2865. UploadByte: traffic.Up,
  2866. TotalByte: traffic.Total,
  2867. SubUrl: subURL,
  2868. SubJsonUrl: subJsonURL,
  2869. SubClashUrl: subClashURL,
  2870. SubTitle: subTitle,
  2871. SubSupportUrl: subSupportUrl,
  2872. Result: pageLinks,
  2873. Emails: pageEmails,
  2874. }
  2875. }
  2876. func subIsOnline(subEmails, onlineEmails []string) bool {
  2877. if len(subEmails) == 0 || len(onlineEmails) == 0 {
  2878. return false
  2879. }
  2880. onlineSet := make(map[string]struct{}, len(onlineEmails))
  2881. for _, email := range onlineEmails {
  2882. onlineSet[email] = struct{}{}
  2883. }
  2884. for _, email := range subEmails {
  2885. if _, online := onlineSet[email]; online {
  2886. return true
  2887. }
  2888. }
  2889. return false
  2890. }
  2891. func getHostFromXFH(s string) (string, error) {
  2892. if strings.Contains(s, ":") {
  2893. realHost, _, err := net.SplitHostPort(s)
  2894. if err != nil {
  2895. return "", err
  2896. }
  2897. return realHost, nil
  2898. }
  2899. return s, nil
  2900. }
  2901. // extraSalamanderKeys lists salamander settings unexpressible in hysteria2 URI;
  2902. // a server using any reported key rejects clients built from the link.
  2903. func extraSalamanderKeys(settings map[string]any, expressedPacketSize bool) []string {
  2904. var extra []string
  2905. for k := range settings {
  2906. if k == "password" || (k == "packetSize" && expressedPacketSize) {
  2907. continue
  2908. }
  2909. extra = append(extra, k)
  2910. }
  2911. sort.Strings(extra)
  2912. return extra
  2913. }