service.go 97 KB

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