service.go 103 KB

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