service.go 101 KB

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