1
0

service.go 101 KB

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