service.go 89 KB

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