service.go 89 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854
  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. // Fan out one link per External Proxy entry if any. Previously this
  1126. // generator ignored `externalProxy` entirely, so the link kept the
  1127. // server's own IP/port even when the admin configured an alternate
  1128. // endpoint (e.g. a CDN hostname + port that forwards to the node).
  1129. // Matches the behaviour of genVlessLink / genTrojanLink / ….
  1130. externalProxies, _ := stream["externalProxy"].([]any)
  1131. if len(externalProxies) > 0 {
  1132. links := make([]string, 0, len(externalProxies))
  1133. for _, externalProxy := range externalProxies {
  1134. ep, ok := externalProxy.(map[string]any)
  1135. if !ok {
  1136. continue
  1137. }
  1138. dest, _ := ep["dest"].(string)
  1139. portF, okPort := ep["port"].(float64)
  1140. if dest == "" || !okPort {
  1141. continue
  1142. }
  1143. epParams := cloneStringMap(params)
  1144. applyExternalProxyHysteriaParams(ep, epParams)
  1145. link := fmt.Sprintf("%s://%s@%s", protocol, auth, joinHostPort(dest, int(portF)))
  1146. links = append(links, buildLinkWithParams(link, epParams, s.endpointRemark(inbound, email, ep, "quic")))
  1147. }
  1148. return strings.Join(links, "\n")
  1149. }
  1150. // No external proxy configured — use the inbound's resolved address so
  1151. // node-managed inbounds get the node's host instead of the central panel's.
  1152. if hopPorts := hysteriaHopPorts(stream); hopPorts != "" {
  1153. params["mport"] = hopPorts
  1154. }
  1155. link := fmt.Sprintf("%s://%s@%s", protocol, auth, joinHostPort(s.resolveInboundAddress(inbound), inbound.Port))
  1156. return buildLinkWithParams(link, params, s.genRemark(inbound, email, "", "quic"))
  1157. }
  1158. // hysteriaHopPorts returns the configured Hysteria2 UDP port-hopping range
  1159. // (finalmask.quicParams.udpHop.ports), or "" when port hopping is off. The
  1160. // range is emitted as the v2rayN-compatible `mport` query param; the URL port
  1161. // field stays numeric so .NET-Uri-based importers (v2rayN) can parse the link.
  1162. func hysteriaHopPorts(stream map[string]any) string {
  1163. finalmask, _ := stream["finalmask"].(map[string]any)
  1164. quicParams, _ := finalmask["quicParams"].(map[string]any)
  1165. udpHop, _ := quicParams["udpHop"].(map[string]any)
  1166. ports, _ := udpHop["ports"].(string)
  1167. return strings.TrimSpace(ports)
  1168. }
  1169. // loadNodes refreshes nodesByID from the DB. Called once per request so
  1170. // the per-inbound resolveInboundAddress lookups are pure map reads.
  1171. // We filter to address != ” so a half-configured node row doesn't
  1172. // accidentally produce a useless host like "https://:2053".
  1173. func (s *SubService) loadNodes() {
  1174. db := database.GetDB()
  1175. var nodes []*model.Node
  1176. if err := db.Model(&model.Node{}).Where("address != ''").Find(&nodes).Error; err != nil {
  1177. logger.Warning("subscription: load nodes failed:", err)
  1178. s.nodesByID = nil
  1179. return
  1180. }
  1181. m := make(map[int]*model.Node, len(nodes))
  1182. for _, n := range nodes {
  1183. m[n.Id] = n
  1184. }
  1185. s.nodesByID = m
  1186. }
  1187. // resolveInboundAddress picks the host an external client should connect to,
  1188. // honoring the inbound's share address strategy the same way the panel's
  1189. // share/QR link builder does (#5208):
  1190. // - "listen": an explicit, client-reachable bind Listen wins, backed by the
  1191. // node's address for node-managed inbounds;
  1192. // - "custom": the inbound's ShareAddr wins, then node, then listen;
  1193. // - "node" (default, and any unknown value): the node's address for
  1194. // node-managed inbounds, then a routable Listen — the pre-strategy order.
  1195. //
  1196. // Every chain ends at the admin's configured public host (Sub/Web domain) and
  1197. // then the subscriber's request host (s.address). Preferring the configured
  1198. // host over the request host for this last resort keeps a wildcard local inbound
  1199. // from advertising a bogus client IP that leaked into the request Host header
  1200. // behind NAT/proxy/CDN (#5425). A loopback/wildcard bind or a unix-domain-socket
  1201. // listen is a server-side detail and is never advertised; External Proxy still
  1202. // overrides everything upstream of this call.
  1203. func (s *SubService) resolveInboundAddress(inbound *model.Inbound) string {
  1204. var nodeAddr string
  1205. if inbound.NodeID != nil && s.nodesByID != nil {
  1206. if n, ok := s.nodesByID[*inbound.NodeID]; ok {
  1207. nodeAddr = n.Address
  1208. }
  1209. }
  1210. var listenAddr string
  1211. if listen := inbound.Listen; listen != "" && listen[0] != '@' && listen[0] != '/' && isRoutableHost(listen) {
  1212. listenAddr = listen
  1213. }
  1214. candidates := []string{nodeAddr, listenAddr}
  1215. switch inbound.ShareAddrStrategy {
  1216. case "listen":
  1217. candidates = []string{listenAddr, nodeAddr}
  1218. case "custom":
  1219. candidates = []string{strings.TrimSpace(inbound.ShareAddr), nodeAddr, listenAddr}
  1220. }
  1221. for _, c := range candidates {
  1222. if c != "" {
  1223. return c
  1224. }
  1225. }
  1226. if d := s.configuredPublicHost(); d != "" {
  1227. return d
  1228. }
  1229. return s.address
  1230. }
  1231. func findClientIndex(clients []model.Client, email string) int {
  1232. for i, client := range clients {
  1233. if client.Email == email {
  1234. return i
  1235. }
  1236. }
  1237. return -1
  1238. }
  1239. func unmarshalStreamSettings(streamSettings string) map[string]any {
  1240. var stream map[string]any
  1241. _ = json.Unmarshal([]byte(streamSettings), &stream)
  1242. return stream
  1243. }
  1244. func applyPathAndHostParams(settings map[string]any, params map[string]string) {
  1245. params["path"], _ = settings["path"].(string)
  1246. if host, ok := settings["host"].(string); ok && len(host) > 0 {
  1247. params["host"] = host
  1248. } else {
  1249. headers, _ := settings["headers"].(map[string]any)
  1250. params["host"] = searchHost(headers)
  1251. }
  1252. }
  1253. func applyPathAndHostObj(settings map[string]any, obj map[string]any) {
  1254. obj["path"], _ = settings["path"].(string)
  1255. if host, ok := settings["host"].(string); ok && len(host) > 0 {
  1256. obj["host"] = host
  1257. } else {
  1258. headers, _ := settings["headers"].(map[string]any)
  1259. obj["host"] = searchHost(headers)
  1260. }
  1261. }
  1262. func applyShareNetworkParams(stream map[string]any, streamNetwork string, params map[string]string) {
  1263. switch streamNetwork {
  1264. case "tcp":
  1265. tcp, _ := stream["tcpSettings"].(map[string]any)
  1266. header, _ := tcp["header"].(map[string]any)
  1267. typeStr, _ := header["type"].(string)
  1268. if typeStr == "http" {
  1269. request, _ := header["request"].(map[string]any)
  1270. requestPath, _ := request["path"].([]any)
  1271. if len(requestPath) > 0 {
  1272. params["path"], _ = requestPath[0].(string)
  1273. }
  1274. host := ""
  1275. if response, ok := header["response"].(map[string]any); ok {
  1276. if respHeaders, ok := response["headers"].(map[string]any); ok {
  1277. host = searchHost(respHeaders)
  1278. }
  1279. }
  1280. if host == "" {
  1281. headers, _ := request["headers"].(map[string]any)
  1282. host = searchHost(headers)
  1283. }
  1284. params["host"] = host
  1285. params["headerType"] = "http"
  1286. }
  1287. case "kcp":
  1288. applyKcpShareParams(stream, params)
  1289. case "ws":
  1290. ws, _ := stream["wsSettings"].(map[string]any)
  1291. applyPathAndHostParams(ws, params)
  1292. case "grpc":
  1293. grpc, _ := stream["grpcSettings"].(map[string]any)
  1294. params["serviceName"], _ = grpc["serviceName"].(string)
  1295. params["authority"], _ = grpc["authority"].(string)
  1296. if mm, _ := grpc["multiMode"].(bool); mm {
  1297. params["mode"] = "multi"
  1298. }
  1299. case "httpupgrade":
  1300. httpupgrade, _ := stream["httpupgradeSettings"].(map[string]any)
  1301. applyPathAndHostParams(httpupgrade, params)
  1302. case "xhttp":
  1303. xhttp, _ := stream["xhttpSettings"].(map[string]any)
  1304. applyXhttpExtraParams(xhttp, params)
  1305. }
  1306. }
  1307. // applyXhttpExtraObj copies the bidirectional xhttp settings into the
  1308. // VMess base64 JSON link object. VMess supports arbitrary keys, so we
  1309. // flatten the SplitHTTPConfig "extra" fields directly onto obj.
  1310. func applyXhttpExtraObj(xhttp map[string]any, obj map[string]any) {
  1311. if xpb, ok := xhttp["xPaddingBytes"].(string); ok && len(xpb) > 0 {
  1312. obj["x_padding_bytes"] = xpb
  1313. }
  1314. maps.Copy(obj, buildXhttpExtra(xhttp))
  1315. }
  1316. func applyVmessNetworkParams(stream map[string]any, network string, obj map[string]any) {
  1317. obj["net"] = network
  1318. switch network {
  1319. case "tcp":
  1320. tcp, _ := stream["tcpSettings"].(map[string]any)
  1321. header, _ := tcp["header"].(map[string]any)
  1322. typeStr, _ := header["type"].(string)
  1323. obj["type"] = typeStr
  1324. if typeStr == "http" {
  1325. request, _ := header["request"].(map[string]any)
  1326. requestPath, _ := request["path"].([]any)
  1327. if len(requestPath) > 0 {
  1328. obj["path"], _ = requestPath[0].(string)
  1329. }
  1330. host := ""
  1331. if response, ok := header["response"].(map[string]any); ok {
  1332. if respHeaders, ok := response["headers"].(map[string]any); ok {
  1333. host = searchHost(respHeaders)
  1334. }
  1335. }
  1336. if host == "" {
  1337. headers, _ := request["headers"].(map[string]any)
  1338. host = searchHost(headers)
  1339. }
  1340. obj["host"] = host
  1341. }
  1342. case "kcp":
  1343. applyKcpShareObj(stream, obj)
  1344. case "ws":
  1345. ws, _ := stream["wsSettings"].(map[string]any)
  1346. applyPathAndHostObj(ws, obj)
  1347. case "grpc":
  1348. grpc, _ := stream["grpcSettings"].(map[string]any)
  1349. obj["path"], _ = grpc["serviceName"].(string)
  1350. obj["authority"], _ = grpc["authority"].(string)
  1351. if mm, _ := grpc["multiMode"].(bool); mm {
  1352. obj["type"] = "multi"
  1353. }
  1354. case "httpupgrade":
  1355. httpupgrade, _ := stream["httpupgradeSettings"].(map[string]any)
  1356. applyPathAndHostObj(httpupgrade, obj)
  1357. case "xhttp":
  1358. xhttp, _ := stream["xhttpSettings"].(map[string]any)
  1359. applyPathAndHostObj(xhttp, obj)
  1360. if mode, ok := xhttp["mode"].(string); ok {
  1361. obj["mode"] = mode
  1362. }
  1363. applyXhttpExtraObj(xhttp, obj)
  1364. }
  1365. }
  1366. func applyShareTLSParams(stream map[string]any, params map[string]string) {
  1367. params["security"] = "tls"
  1368. tlsSetting, _ := stream["tlsSettings"].(map[string]any)
  1369. alpns, _ := tlsSetting["alpn"].([]any)
  1370. var alpn []string
  1371. for _, a := range alpns {
  1372. if s, ok := a.(string); ok {
  1373. alpn = append(alpn, s)
  1374. }
  1375. }
  1376. if len(alpn) > 0 {
  1377. params["alpn"] = strings.Join(alpn, ",")
  1378. }
  1379. if sniValue, ok := searchKey(tlsSetting, "serverName"); ok {
  1380. params["sni"], _ = sniValue.(string)
  1381. }
  1382. tlsSettings, _ := searchKey(tlsSetting, "settings")
  1383. if tlsSetting != nil {
  1384. if fpValue, ok := searchKey(tlsSettings, "fingerprint"); ok {
  1385. params["fp"], _ = fpValue.(string)
  1386. }
  1387. if echValue, ok := searchKey(tlsSettings, "echConfigList"); ok {
  1388. if ech, _ := echValue.(string); ech != "" {
  1389. params["ech"] = ech
  1390. }
  1391. }
  1392. if vcn, ok := verifyPeerCertByNameValue(tlsSettings); ok {
  1393. params["vcn"] = vcn
  1394. }
  1395. if pins, ok := pinnedSha256List(tlsSettings); ok {
  1396. params["pcs"] = strings.Join(pins, ",")
  1397. }
  1398. }
  1399. }
  1400. func applyVmessTLSParams(stream map[string]any, obj map[string]any) {
  1401. tlsSetting, _ := stream["tlsSettings"].(map[string]any)
  1402. alpns, _ := tlsSetting["alpn"].([]any)
  1403. if len(alpns) > 0 {
  1404. var alpn []string
  1405. for _, a := range alpns {
  1406. if s, ok := a.(string); ok {
  1407. alpn = append(alpn, s)
  1408. }
  1409. }
  1410. obj["alpn"] = strings.Join(alpn, ",")
  1411. }
  1412. if sniValue, ok := searchKey(tlsSetting, "serverName"); ok {
  1413. obj["sni"], _ = sniValue.(string)
  1414. }
  1415. tlsSettings, _ := searchKey(tlsSetting, "settings")
  1416. if tlsSetting != nil {
  1417. if fpValue, ok := searchKey(tlsSettings, "fingerprint"); ok {
  1418. obj["fp"], _ = fpValue.(string)
  1419. }
  1420. if echValue, ok := searchKey(tlsSettings, "echConfigList"); ok {
  1421. if ech, _ := echValue.(string); ech != "" {
  1422. obj["ech"] = ech
  1423. }
  1424. }
  1425. if vcn, ok := verifyPeerCertByNameValue(tlsSettings); ok {
  1426. obj["vcn"] = vcn
  1427. }
  1428. if pins, ok := pinnedSha256List(tlsSettings); ok {
  1429. obj["pcs"] = strings.Join(pins, ",")
  1430. }
  1431. }
  1432. }
  1433. // verifyPeerCertByNameValue extracts tlsSettings.settings.verifyPeerCertByName
  1434. // (the v2rayN `vcn` param) as a trimmed string. Like pinnedPeerCertSha256 it is
  1435. // panel-only and flows into share links so clients verify the server
  1436. // certificate by this name — the replacement for the removed allowInsecure.
  1437. func verifyPeerCertByNameValue(tlsClientSettings any) (string, bool) {
  1438. raw, ok := searchKey(tlsClientSettings, "verifyPeerCertByName")
  1439. if !ok {
  1440. return "", false
  1441. }
  1442. s, ok := raw.(string)
  1443. if !ok {
  1444. return "", false
  1445. }
  1446. if s = strings.TrimSpace(s); s == "" {
  1447. return "", false
  1448. }
  1449. return s, true
  1450. }
  1451. // pinnedSha256List extracts tlsSettings.settings.pinnedPeerCertSha256 as a
  1452. // []string. The field is panel-only (stripped before the run-config reaches
  1453. // xray-core via internal/web/service/xray.go) but flows into share links so clients
  1454. // can pin the server's certificate hash.
  1455. func pinnedSha256List(tlsClientSettings any) ([]string, bool) {
  1456. raw, ok := searchKey(tlsClientSettings, "pinnedPeerCertSha256")
  1457. if !ok {
  1458. return nil, false
  1459. }
  1460. arr, ok := raw.([]any)
  1461. if !ok || len(arr) == 0 {
  1462. return nil, false
  1463. }
  1464. out := make([]string, 0, len(arr))
  1465. for _, v := range arr {
  1466. s, ok := v.(string)
  1467. if !ok || s == "" {
  1468. continue
  1469. }
  1470. out = append(out, s)
  1471. }
  1472. if len(out) == 0 {
  1473. return nil, false
  1474. }
  1475. return out, true
  1476. }
  1477. // hysteriaPinHex normalises a pinnedPeerCertSha256 entry into the 64-character
  1478. // lowercase hex form that Xray-core's Hysteria2 pinSHA256 parser requires.
  1479. //
  1480. // The panel stores pins in several shapes: base64 (xray-core's native TLS
  1481. // format, used by the generate button and the JSON subscription) and hex —
  1482. // either bare or colon-separated as `openssl x509 -fingerprint -sha256` emits
  1483. // it. Hysteria2 clients hex-decode pinSHA256 and crash on a base64 value, so
  1484. // each entry is coerced to bare hex here. Anything that is neither a 32-byte
  1485. // hex nor a 32-byte base64 SHA-256 is returned unchanged so unexpected data is
  1486. // not silently dropped. Mirrors decodeCertPin in internal/web/service/node.go.
  1487. func hysteriaPinHex(pin string) string {
  1488. pin = strings.TrimSpace(pin)
  1489. if h := strings.ReplaceAll(pin, ":", ""); len(h) == hex.EncodedLen(sha256.Size) {
  1490. if _, err := hex.DecodeString(h); err == nil {
  1491. return strings.ToLower(h)
  1492. }
  1493. }
  1494. for _, enc := range []*base64.Encoding{
  1495. base64.StdEncoding,
  1496. base64.RawStdEncoding,
  1497. base64.URLEncoding,
  1498. base64.RawURLEncoding,
  1499. } {
  1500. if b, err := enc.DecodeString(pin); err == nil && len(b) == sha256.Size {
  1501. return hex.EncodeToString(b)
  1502. }
  1503. }
  1504. return pin
  1505. }
  1506. func applyShareRealityParams(stream map[string]any, params map[string]string, clientKey string) {
  1507. params["security"] = "reality"
  1508. realitySetting, _ := stream["realitySettings"].(map[string]any)
  1509. realitySettings, _ := searchKey(realitySetting, "settings")
  1510. if realitySetting != nil {
  1511. if sniValue, ok := searchKey(realitySetting, "serverNames"); ok {
  1512. if sNames, _ := sniValue.([]any); len(sNames) > 0 {
  1513. params["sni"], _ = sNames[random.Num(len(sNames))].(string)
  1514. }
  1515. }
  1516. if pbkValue, ok := searchKey(realitySettings, "publicKey"); ok {
  1517. params["pbk"], _ = pbkValue.(string)
  1518. }
  1519. if sidValue, ok := searchKey(realitySetting, "shortIds"); ok {
  1520. if shortIds, _ := sidValue.([]any); len(shortIds) > 0 {
  1521. params["sid"], _ = shortIds[random.Num(len(shortIds))].(string)
  1522. }
  1523. }
  1524. if fpValue, ok := searchKey(realitySettings, "fingerprint"); ok {
  1525. if fp, ok := fpValue.(string); ok && len(fp) > 0 {
  1526. params["fp"] = fp
  1527. }
  1528. }
  1529. if pqvValue, ok := searchKey(realitySettings, "mldsa65Verify"); ok {
  1530. if pqv, ok := pqvValue.(string); ok && len(pqv) > 0 {
  1531. params["pqv"] = pqv
  1532. }
  1533. }
  1534. seed := ""
  1535. if spxValue, ok := searchKey(realitySettings, "spiderX"); ok {
  1536. seed, _ = spxValue.(string)
  1537. }
  1538. params["spx"] = deriveSpiderX(seed, clientKey)
  1539. }
  1540. }
  1541. // subKey returns a stable per-client identity for deterministic derivations,
  1542. // preferring the subscription id and falling back to the (unique) email.
  1543. func subKey(c model.Client) string {
  1544. if c.SubID != "" {
  1545. return c.SubID
  1546. }
  1547. return c.Email
  1548. }
  1549. // deriveSpiderX maps the inbound's spiderX seed plus a stable client key to a
  1550. // deterministic per-client "/path"; frontend/src/lib/xray/spider-x.ts mirrors it.
  1551. func deriveSpiderX(seed, clientKey string) string {
  1552. if seed == "" && clientKey == "" {
  1553. return "/" + random.Seq(15)
  1554. }
  1555. sum := sha256.Sum256([]byte(seed + "|" + clientKey))
  1556. return "/" + hex.EncodeToString(sum[:])[:15]
  1557. }
  1558. func buildVmessLink(obj map[string]any) string {
  1559. jsonStr, _ := json.MarshalIndent(obj, "", " ")
  1560. return "vmess://" + base64.StdEncoding.EncodeToString(jsonStr)
  1561. }
  1562. func cloneVmessShareObj(baseObj map[string]any, newSecurity string) map[string]any {
  1563. newObj := map[string]any{}
  1564. for key, value := range baseObj {
  1565. if newSecurity != "none" || (key != "alpn" && key != "sni" && key != "fp" && key != "pcs") {
  1566. newObj[key] = value
  1567. }
  1568. }
  1569. return newObj
  1570. }
  1571. func applyExternalProxyTLSObj(ep map[string]any, obj map[string]any, security string) {
  1572. if security != "tls" {
  1573. return
  1574. }
  1575. if sni, ok := externalProxySNI(ep); ok {
  1576. obj["sni"] = sni
  1577. }
  1578. if fp, ok := ep["fingerprint"].(string); ok && fp != "" {
  1579. obj["fp"] = fp
  1580. }
  1581. if alpn, ok := externalProxyALPN(ep["alpn"]); ok {
  1582. obj["alpn"] = alpn
  1583. }
  1584. if pins, ok := externalProxyPins(ep["pinnedPeerCertSha256"]); ok {
  1585. obj["pcs"] = joinAnyStrings(pins)
  1586. }
  1587. if vcn, ok := ep["verifyPeerCertByName"].(string); ok && vcn != "" {
  1588. obj["vcn"] = vcn
  1589. }
  1590. if ech, ok := ep["echConfigList"].(string); ok && ech != "" {
  1591. obj["ech"] = ech
  1592. }
  1593. }
  1594. func applyExternalProxyTLSParams(ep map[string]any, params map[string]string, security string) {
  1595. if security != "tls" {
  1596. return
  1597. }
  1598. if sni, ok := externalProxySNI(ep); ok {
  1599. params["sni"] = sni
  1600. }
  1601. if fp, ok := ep["fingerprint"].(string); ok && fp != "" {
  1602. params["fp"] = fp
  1603. }
  1604. if alpn, ok := externalProxyALPN(ep["alpn"]); ok {
  1605. params["alpn"] = alpn
  1606. }
  1607. if pins, ok := externalProxyPins(ep["pinnedPeerCertSha256"]); ok {
  1608. params["pcs"] = joinAnyStrings(pins)
  1609. }
  1610. if vcn, ok := ep["verifyPeerCertByName"].(string); ok && vcn != "" {
  1611. params["vcn"] = vcn
  1612. }
  1613. if ech, ok := ep["echConfigList"].(string); ok && ech != "" {
  1614. params["ech"] = ech
  1615. }
  1616. }
  1617. // applyExternalProxyHysteriaParams overrides the cert pin for a single
  1618. // external-proxy entry on a Hysteria link. Hysteria carries the pin as a hex
  1619. // `pinSHA256` (not the `pcs` the URL-param protocols use), so each entry is
  1620. // coerced through hysteriaPinHex like the main pin. sni/fp/alpn are left as
  1621. // the inbound's own — Hysteria external proxies are typically alternate
  1622. // endpoints (port-hop / CDN) fronting the same certificate.
  1623. func applyExternalProxyHysteriaParams(ep map[string]any, params map[string]string) {
  1624. if pins, ok := externalProxyPins(ep["pinnedPeerCertSha256"]); ok {
  1625. hexPins := make([]string, 0, len(pins))
  1626. for _, p := range pins {
  1627. if s, ok := p.(string); ok {
  1628. hexPins = append(hexPins, hysteriaPinHex(s))
  1629. }
  1630. }
  1631. params["pinSHA256"] = strings.Join(hexPins, ",")
  1632. }
  1633. if ai, ok := ep["allowInsecure"].(bool); ok && ai {
  1634. params["insecure"] = "1"
  1635. }
  1636. }
  1637. // cloneStreamForExternalProxy returns a shallow clone of stream with
  1638. // tlsSettings (and its nested settings map) deep-copied. The external
  1639. // proxy loop mutates tlsSettings per iteration, so without isolating
  1640. // those maps each proxy's SNI/fingerprint/ALPN would leak into the next.
  1641. func cloneStreamForExternalProxy(stream map[string]any) map[string]any {
  1642. out := cloneMap(stream)
  1643. ts, ok := out["tlsSettings"].(map[string]any)
  1644. if !ok || ts == nil {
  1645. return out
  1646. }
  1647. clonedTs := cloneMap(ts)
  1648. if inner, ok := clonedTs["settings"].(map[string]any); ok && inner != nil {
  1649. clonedTs["settings"] = cloneMap(inner)
  1650. }
  1651. out["tlsSettings"] = clonedTs
  1652. return out
  1653. }
  1654. func applyExternalProxyTLSToStream(ep map[string]any, stream map[string]any, security string) {
  1655. if security != "tls" {
  1656. return
  1657. }
  1658. tlsSettings, _ := stream["tlsSettings"].(map[string]any)
  1659. if tlsSettings == nil {
  1660. tlsSettings = map[string]any{}
  1661. stream["tlsSettings"] = tlsSettings
  1662. }
  1663. if sni, ok := externalProxySNI(ep); ok {
  1664. tlsSettings["serverName"] = sni
  1665. }
  1666. if fp, ok := ep["fingerprint"].(string); ok && fp != "" {
  1667. tlsSettings["fingerprint"] = fp
  1668. }
  1669. if alpn, ok := externalProxyALPNList(ep["alpn"]); ok {
  1670. tlsSettings["alpn"] = alpn
  1671. }
  1672. if pins, ok := externalProxyPins(ep["pinnedPeerCertSha256"]); ok {
  1673. settings, _ := tlsSettings["settings"].(map[string]any)
  1674. if settings == nil {
  1675. settings = map[string]any{}
  1676. tlsSettings["settings"] = settings
  1677. }
  1678. settings["pinnedPeerCertSha256"] = pins
  1679. }
  1680. if ech, ok := ep["echConfigList"].(string); ok && ech != "" {
  1681. settings, _ := tlsSettings["settings"].(map[string]any)
  1682. if settings == nil {
  1683. settings = map[string]any{}
  1684. tlsSettings["settings"] = settings
  1685. }
  1686. settings["echConfigList"] = ech
  1687. }
  1688. if vcn, ok := ep["verifyPeerCertByName"].(string); ok && vcn != "" {
  1689. settings, _ := tlsSettings["settings"].(map[string]any)
  1690. if settings == nil {
  1691. settings = map[string]any{}
  1692. tlsSettings["settings"] = settings
  1693. }
  1694. settings["verifyPeerCertByName"] = vcn
  1695. }
  1696. if ai, ok := ep["allowInsecure"].(bool); ok && ai {
  1697. settings, _ := tlsSettings["settings"].(map[string]any)
  1698. if settings == nil {
  1699. settings = map[string]any{}
  1700. tlsSettings["settings"] = settings
  1701. }
  1702. settings["allowInsecure"] = true
  1703. }
  1704. }
  1705. func externalProxySNI(ep map[string]any) (string, bool) {
  1706. if sni, ok := ep["sni"].(string); ok && sni != "" {
  1707. return sni, true
  1708. }
  1709. return "", false
  1710. }
  1711. func externalProxyALPN(value any) (string, bool) {
  1712. switch v := value.(type) {
  1713. case string:
  1714. return v, v != ""
  1715. case []string:
  1716. if len(v) == 0 {
  1717. return "", false
  1718. }
  1719. return strings.Join(v, ","), true
  1720. case []any:
  1721. alpn := make([]string, 0, len(v))
  1722. for _, item := range v {
  1723. if s, ok := item.(string); ok && s != "" {
  1724. alpn = append(alpn, s)
  1725. }
  1726. }
  1727. if len(alpn) == 0 {
  1728. return "", false
  1729. }
  1730. return strings.Join(alpn, ","), true
  1731. default:
  1732. return "", false
  1733. }
  1734. }
  1735. func externalProxyALPNList(value any) ([]any, bool) {
  1736. switch v := value.(type) {
  1737. case string:
  1738. if v == "" {
  1739. return nil, false
  1740. }
  1741. parts := strings.Split(v, ",")
  1742. out := make([]any, 0, len(parts))
  1743. for _, part := range parts {
  1744. if part = strings.TrimSpace(part); part != "" {
  1745. out = append(out, part)
  1746. }
  1747. }
  1748. return out, len(out) > 0
  1749. case []string:
  1750. out := make([]any, 0, len(v))
  1751. for _, item := range v {
  1752. if item != "" {
  1753. out = append(out, item)
  1754. }
  1755. }
  1756. return out, len(out) > 0
  1757. case []any:
  1758. out := make([]any, 0, len(v))
  1759. for _, item := range v {
  1760. if s, ok := item.(string); ok && s != "" {
  1761. out = append(out, s)
  1762. }
  1763. }
  1764. return out, len(out) > 0
  1765. default:
  1766. return nil, false
  1767. }
  1768. }
  1769. // externalProxyPins extracts an external-proxy entry's pinnedPeerCertSha256
  1770. // as a []any of non-empty strings. The []any element type matches what the
  1771. // JSON/Clash sub builders expect when reading the value back off the cloned
  1772. // stream's tlsSettings.settings.
  1773. func externalProxyPins(value any) ([]any, bool) {
  1774. switch v := value.(type) {
  1775. case []string:
  1776. out := make([]any, 0, len(v))
  1777. for _, item := range v {
  1778. if item != "" {
  1779. out = append(out, item)
  1780. }
  1781. }
  1782. return out, len(out) > 0
  1783. case []any:
  1784. out := make([]any, 0, len(v))
  1785. for _, item := range v {
  1786. if s, ok := item.(string); ok && s != "" {
  1787. out = append(out, s)
  1788. }
  1789. }
  1790. return out, len(out) > 0
  1791. default:
  1792. return nil, false
  1793. }
  1794. }
  1795. func joinAnyStrings(items []any) string {
  1796. parts := make([]string, 0, len(items))
  1797. for _, item := range items {
  1798. if s, ok := item.(string); ok {
  1799. parts = append(parts, s)
  1800. }
  1801. }
  1802. return strings.Join(parts, ",")
  1803. }
  1804. // buildVmessExternalProxyLinks is a thin adapter: it maps the legacy
  1805. // externalProxy entries to []ShareEndpoint and renders them through the unified
  1806. // endpoint path. Kept as a thin shim over the unified endpoint builder so
  1807. // genVmessLink keeps calling one helper (now threading transport through).
  1808. func (s *SubService) buildVmessExternalProxyLinks(externalProxies []any, baseObj map[string]any, inbound *model.Inbound, email string, transport string) string {
  1809. eps := make([]ShareEndpoint, 0, len(externalProxies))
  1810. for _, externalProxy := range externalProxies {
  1811. ep, _ := externalProxy.(map[string]any)
  1812. eps = append(eps, externalProxyToEndpoint(ep))
  1813. }
  1814. return s.buildEndpointVmessLinks(eps, baseObj, inbound, email, transport)
  1815. }
  1816. // buildLinkWithParams appends ?query and #fragment to a pre-built
  1817. // scheme://userinfo@host:port string without re-parsing it. The caller
  1818. // has already escaped userinfo via encodeUserinfo (or chosen a base64
  1819. // alphabet with no reserved chars); a url.Parse + .String() round-trip
  1820. // would silently decode that escaping because Go's userinfo emitter
  1821. // leaves sub-delims (=, +, ;) literal, which breaks Trojan/Hysteria/SS
  1822. // clients that reject those chars in the password.
  1823. func buildLinkWithParams(link string, params map[string]string, fragment string) string {
  1824. return appendQueryAndFragment(link, params, fragment, "", false)
  1825. }
  1826. // buildLinkWithParamsAndSecurity is buildLinkWithParams plus an
  1827. // external-proxy override: the `security` key in params is replaced with
  1828. // the supplied value, and TLS hint fields (alpn/sni/fp/pcs) are stripped
  1829. // when the override is `none`.
  1830. func buildLinkWithParamsAndSecurity(link string, params map[string]string, fragment, security string, omitTLSFields bool) string {
  1831. return appendQueryAndFragment(link, params, fragment, security, omitTLSFields)
  1832. }
  1833. func appendQueryAndFragment(link string, params map[string]string, fragment, securityOverride string, omitTLSFields bool) string {
  1834. var sb strings.Builder
  1835. sb.WriteString(link)
  1836. if len(params) > 0 {
  1837. q := url.Values{}
  1838. for k, v := range params {
  1839. if securityOverride != "" && k == "security" {
  1840. v = securityOverride
  1841. }
  1842. if omitTLSFields && (k == "alpn" || k == "sni" || k == "fp" || k == "pcs") {
  1843. continue
  1844. }
  1845. q.Set(k, v)
  1846. }
  1847. encoded := q.Encode()
  1848. if encoded != "" {
  1849. if strings.Contains(link, "?") {
  1850. sb.WriteByte('&')
  1851. } else {
  1852. sb.WriteByte('?')
  1853. }
  1854. sb.WriteString(encoded)
  1855. }
  1856. }
  1857. if fragment != "" {
  1858. sb.WriteByte('#')
  1859. // Match the frontend's encodeURIComponent(remark): spaces become
  1860. // %20 (not + as in query strings).
  1861. sb.WriteString(strings.ReplaceAll(url.QueryEscape(fragment), "+", "%20"))
  1862. }
  1863. return sb.String()
  1864. }
  1865. // buildExternalProxyURLLinks is a thin adapter: it maps the legacy externalProxy
  1866. // entries to []ShareEndpoint and renders them through the unified endpoint path.
  1867. // Kept so the genVless/genTrojan/genShadowsocks call sites are unchanged.
  1868. func (s *SubService) buildExternalProxyURLLinks(
  1869. externalProxies []any,
  1870. params map[string]string,
  1871. baseSecurity string,
  1872. makeLink func(ep map[string]any, dest string, port int) string,
  1873. makeRemark func(ep map[string]any) string,
  1874. ) string {
  1875. eps := make([]ShareEndpoint, 0, len(externalProxies))
  1876. for _, externalProxy := range externalProxies {
  1877. ep, _ := externalProxy.(map[string]any)
  1878. eps = append(eps, externalProxyToEndpoint(ep))
  1879. }
  1880. return s.buildEndpointLinks(eps, params, baseSecurity, func(e ShareEndpoint) string {
  1881. return makeLink(e.ep, e.Address, e.Port)
  1882. }, func(e ShareEndpoint) string {
  1883. return makeRemark(e.ep)
  1884. })
  1885. }
  1886. func cloneStringMap(source map[string]string) map[string]string {
  1887. cloned := make(map[string]string, len(source))
  1888. maps.Copy(cloned, source)
  1889. return cloned
  1890. }
  1891. // genRemark builds the remark for a non-host link (raw default / legacy
  1892. // externalProxy / synthetic JSON-Clash entry). A set remark template drives it
  1893. // in both the body and display contexts (genTemplatedRemark renders the
  1894. // name-only part on displays); with no template it falls back to the inbound
  1895. // remark, extra and email joined by "-".
  1896. func (s *SubService) genRemark(inbound *model.Inbound, email string, extra string, transport string) string {
  1897. if s.remarkTemplate != "" {
  1898. return s.genTemplatedRemark(inbound, s.lookupClient(inbound, email), extra, transport)
  1899. }
  1900. return fallbackRemark(inbound.Remark, extra, email)
  1901. }
  1902. func fallbackRemark(parts ...string) string {
  1903. out := make([]string, 0, len(parts))
  1904. for _, p := range parts {
  1905. if p != "" {
  1906. out = append(out, p)
  1907. }
  1908. }
  1909. return strings.Join(out, "-")
  1910. }
  1911. // findClientStats returns the inbound's traffic record for email, if present.
  1912. func (s *SubService) findClientStats(inbound *model.Inbound, email string) (xray.ClientTraffic, bool) {
  1913. for _, clientStat := range inbound.ClientStats {
  1914. if clientStat.Email == email {
  1915. return clientStat, true
  1916. }
  1917. }
  1918. return xray.ClientTraffic{}, false
  1919. }
  1920. // statsByEmailFromDB resolves a client's traffic row straight from the DB by its
  1921. // globally-unique email, caching the hit into statsByEmail for the rest of the
  1922. // request. It's the last-resort lookup behind statsForClient: the preloaded
  1923. // ClientStats and the statsByEmail index are both keyed by
  1924. // client_traffics.inbound_id, which is written once by AddClientStat and never
  1925. // updated. When an inbound is deleted and recreated it gets a new id, so the old
  1926. // row is orphaned from every loaded inbound and both in-memory paths miss —
  1927. // leaving {{TRAFFIC_USED}} stuck at 0 for pre-existing clients even though their
  1928. // usage is intact (#5567). Matching by email recovers it, the same way the
  1929. // sub-info header's AggregateTrafficByEmails already does.
  1930. func (s *SubService) statsByEmailFromDB(email string) (xray.ClientTraffic, bool) {
  1931. db := database.GetDB()
  1932. if db == nil {
  1933. return xray.ClientTraffic{}, false
  1934. }
  1935. var row xray.ClientTraffic
  1936. if err := db.Model(&xray.ClientTraffic{}).Where("email = ?", email).First(&row).Error; err != nil {
  1937. return xray.ClientTraffic{}, false
  1938. }
  1939. if s.statsByEmail == nil {
  1940. s.statsByEmail = map[string]xray.ClientTraffic{}
  1941. }
  1942. s.statsByEmail[email] = row
  1943. return row, true
  1944. }
  1945. func searchKey(data any, key string) (any, bool) {
  1946. switch val := data.(type) {
  1947. case map[string]any:
  1948. for k, v := range val {
  1949. if k == key {
  1950. return v, true
  1951. }
  1952. if result, ok := searchKey(v, key); ok {
  1953. return result, true
  1954. }
  1955. }
  1956. case []any:
  1957. for _, v := range val {
  1958. if result, ok := searchKey(v, key); ok {
  1959. return result, true
  1960. }
  1961. }
  1962. }
  1963. return nil, false
  1964. }
  1965. // buildXhttpExtra walks an xhttpSettings map and returns the JSON blob
  1966. // that goes into the URL's `extra` param (or, for VMess, the link
  1967. // object). Carries ONLY the bidirectional fields from xray-core's
  1968. // SplitHTTPConfig — i.e. the ones the server enforces and the client
  1969. // must match. Strictly one-sided fields are excluded:
  1970. //
  1971. // - server-only (noSSEHeader, scMaxBufferedPosts, scStreamUpServerSecs,
  1972. // serverMaxHeaderBytes) — client wouldn't read them, so emitting
  1973. // them just bloats the URL.
  1974. // - client-only values are included only when present in the inbound
  1975. // JSON. Some deployments/imported configs carry them there, and the
  1976. // subscription link is the only place clients can receive them.
  1977. //
  1978. // Truthy-only guards keep default inbounds emitting the same compact URL
  1979. // they did before this helper grew.
  1980. func buildXhttpExtra(xhttp map[string]any) map[string]any {
  1981. if xhttp == nil {
  1982. return nil
  1983. }
  1984. extra := map[string]any{}
  1985. if mode, ok := xhttp["mode"].(string); ok && len(mode) > 0 {
  1986. extra["mode"] = mode
  1987. }
  1988. if xpb, ok := xhttp["xPaddingBytes"].(string); ok && len(xpb) > 0 {
  1989. extra["xPaddingBytes"] = xpb
  1990. }
  1991. if obfs, ok := xhttp["xPaddingObfsMode"].(bool); ok && obfs {
  1992. extra["xPaddingObfsMode"] = true
  1993. for _, field := range []string{"xPaddingKey", "xPaddingHeader", "xPaddingPlacement", "xPaddingMethod"} {
  1994. if v, ok := xhttp[field].(string); ok && len(v) > 0 {
  1995. extra[field] = v
  1996. }
  1997. }
  1998. }
  1999. stringFields := []string{
  2000. "uplinkHTTPMethod",
  2001. "sessionIDPlacement", "sessionIDKey", "sessionIDTable", "sessionIDLength",
  2002. "seqPlacement", "seqKey",
  2003. "uplinkDataPlacement", "uplinkDataKey",
  2004. "scMaxEachPostBytes", "scMinPostsIntervalMs",
  2005. }
  2006. // Values matching xray-core's own defaults are redundant on the wire and
  2007. // the literal scMinPostsIntervalMs=30 is a known DPI fingerprint (#5141).
  2008. // Old panels seeded these defaults into every xhttp inbound, so filter
  2009. // them here instead of requiring every stored config to be re-saved.
  2010. coreDefaults := map[string]string{
  2011. "scMaxEachPostBytes": "1000000",
  2012. "scMinPostsIntervalMs": "30",
  2013. }
  2014. for _, field := range stringFields {
  2015. if v, ok := xhttp[field].(string); ok && len(v) > 0 && v != coreDefaults[field] {
  2016. extra[field] = v
  2017. }
  2018. }
  2019. // Legacy inbounds (pre xray-core #6258) stored sessionPlacement/sessionKey.
  2020. // Lift them onto the renamed keys so links from not-yet-resaved configs
  2021. // still carry the session settings. Mirrors the frontend migration.
  2022. for legacy, renamed := range map[string]string{
  2023. "sessionPlacement": "sessionIDPlacement",
  2024. "sessionKey": "sessionIDKey",
  2025. } {
  2026. if _, exists := extra[renamed]; !exists {
  2027. if v, ok := xhttp[legacy].(string); ok && len(v) > 0 {
  2028. extra[renamed] = v
  2029. }
  2030. }
  2031. }
  2032. // Older clients still read the pre-#6258 names from the subscription
  2033. // extra JSON. Emit aliases after lifting legacy inputs so both old and
  2034. // new clients can consume the same link.
  2035. if v, ok := extra["sessionIDPlacement"].(string); ok && len(v) > 0 {
  2036. extra["sessionPlacement"] = v
  2037. }
  2038. if v, ok := extra["sessionIDKey"].(string); ok && len(v) > 0 {
  2039. extra["sessionKey"] = v
  2040. }
  2041. for _, field := range []string{"uplinkChunkSize"} {
  2042. if v, ok := nonZeroShareValue(xhttp[field]); ok {
  2043. extra[field] = v
  2044. }
  2045. }
  2046. for _, field := range []string{"noGRPCHeader"} {
  2047. if v, ok := xhttp[field].(bool); ok && v {
  2048. extra[field] = v
  2049. }
  2050. }
  2051. for _, field := range []string{"xmux", "downloadSettings"} {
  2052. if v, ok := nonEmptyShareObject(xhttp[field]); ok {
  2053. extra[field] = v
  2054. }
  2055. }
  2056. // Headers — emitted as the {name: value} map upstream's struct
  2057. // expects. The server runtime ignores this field, but the client
  2058. // (consuming the share link) honors it. Drop any "host" entry —
  2059. // host already wins as a top-level URL param.
  2060. if rawHeaders, ok := xhttp["headers"].(map[string]any); ok && len(rawHeaders) > 0 {
  2061. out := map[string]any{}
  2062. for k, v := range rawHeaders {
  2063. if strings.EqualFold(k, "host") {
  2064. continue
  2065. }
  2066. out[k] = v
  2067. }
  2068. if len(out) > 0 {
  2069. extra["headers"] = out
  2070. }
  2071. }
  2072. if len(extra) == 0 {
  2073. return nil
  2074. }
  2075. return extra
  2076. }
  2077. func nonZeroShareValue(v any) (any, bool) {
  2078. switch value := v.(type) {
  2079. case string:
  2080. return value, value != ""
  2081. case int:
  2082. return value, value != 0
  2083. case int32:
  2084. return value, value != 0
  2085. case int64:
  2086. return value, value != 0
  2087. case float32:
  2088. return value, value != 0
  2089. case float64:
  2090. return value, value != 0
  2091. default:
  2092. return nil, false
  2093. }
  2094. }
  2095. func nonEmptyShareObject(v any) (any, bool) {
  2096. switch value := v.(type) {
  2097. case map[string]any:
  2098. return value, len(value) > 0
  2099. case map[string]string:
  2100. return value, len(value) > 0
  2101. case []any:
  2102. return value, len(value) > 0
  2103. default:
  2104. return nil, false
  2105. }
  2106. }
  2107. // applyXhttpExtraParams emits the full xhttp config into the URL query
  2108. // params of a vless:// / trojan:// / ss:// link. Sets path/host/mode at
  2109. // top level (xray's Build() always lets these win over `extra`) and packs
  2110. // everything else into a JSON `extra` param. Also writes the flat
  2111. // `x_padding_bytes` param sing-box-family clients understand.
  2112. //
  2113. // Without this, the admin's custom xPaddingBytes / sessionKey / etc. never
  2114. // reach the client and handshakes are silently rejected with
  2115. // `invalid padding (...) length: 0` — the client-visible symptom is
  2116. // "xhttp doesn't connect" on OpenWRT / sing-box.
  2117. //
  2118. // Two encodings are written so every popular client can read at least one:
  2119. //
  2120. // - x_padding_bytes=<range> — flat param, understood by sing-box and its
  2121. // derivatives (Podkop, OpenWRT sing-box, Karing, NekoBox, …).
  2122. // - extra=<url-encoded-json> — full xhttp settings blob, which is how
  2123. // xray-core clients (v2rayNG, Happ, Furious, Exclave, …) pick up the
  2124. // bidirectional fields beyond path/host/mode.
  2125. func applyXhttpExtraParams(xhttp map[string]any, params map[string]string) {
  2126. if xhttp == nil {
  2127. return
  2128. }
  2129. applyPathAndHostParams(xhttp, params)
  2130. if mode, ok := xhttp["mode"].(string); ok {
  2131. params["mode"] = mode
  2132. }
  2133. if xpb, ok := xhttp["xPaddingBytes"].(string); ok && len(xpb) > 0 {
  2134. params["x_padding_bytes"] = xpb
  2135. }
  2136. extra := buildXhttpExtra(xhttp)
  2137. if extra != nil {
  2138. if b, err := json.Marshal(extra); err == nil {
  2139. params["extra"] = string(b)
  2140. }
  2141. }
  2142. }
  2143. var kcpMaskToHeaderType = map[string]string{
  2144. "dns": "dns",
  2145. "dtls": "dtls",
  2146. "srtp": "srtp",
  2147. "utp": "utp",
  2148. "wechat": "wechat-video",
  2149. "wireguard": "wireguard",
  2150. }
  2151. var validFinalMaskUDPTypes = map[string]struct{}{
  2152. "salamander": {},
  2153. "mkcp-legacy": {},
  2154. "xdns": {},
  2155. "xicmp": {},
  2156. "noise": {},
  2157. "header-custom": {},
  2158. "realm": {},
  2159. }
  2160. var validFinalMaskTCPTypes = map[string]struct{}{
  2161. "header-custom": {},
  2162. "fragment": {},
  2163. "sudoku": {},
  2164. "xmc": {},
  2165. }
  2166. // applyKcpShareParams reconstructs legacy KCP share-link fields from either
  2167. // the historical kcpSettings.header/seed shape or the current finalmask model.
  2168. // This keeps subscription output compatible while avoiding panics when older
  2169. // keys are absent from modern inbounds.
  2170. func applyKcpShareParams(stream map[string]any, params map[string]string) {
  2171. extractKcpShareFields(stream).applyToParams(params)
  2172. }
  2173. func applyKcpShareObj(stream map[string]any, obj map[string]any) {
  2174. extractKcpShareFields(stream).applyToObj(obj)
  2175. }
  2176. type kcpShareFields struct {
  2177. headerType string
  2178. seed string
  2179. mtu int
  2180. tti int
  2181. }
  2182. func (f kcpShareFields) applyToParams(params map[string]string) {
  2183. if f.headerType != "" && f.headerType != "none" {
  2184. params["headerType"] = f.headerType
  2185. }
  2186. setStringParam(params, "seed", f.seed)
  2187. setIntParam(params, "mtu", f.mtu)
  2188. setIntParam(params, "tti", f.tti)
  2189. }
  2190. func (f kcpShareFields) applyToObj(obj map[string]any) {
  2191. if f.headerType != "" && f.headerType != "none" {
  2192. obj["type"] = f.headerType
  2193. }
  2194. setStringField(obj, "path", f.seed)
  2195. setIntField(obj, "mtu", f.mtu)
  2196. setIntField(obj, "tti", f.tti)
  2197. }
  2198. func extractKcpShareFields(stream map[string]any) kcpShareFields {
  2199. fields := kcpShareFields{headerType: "none"}
  2200. if kcp, ok := stream["kcpSettings"].(map[string]any); ok {
  2201. if header, ok := kcp["header"].(map[string]any); ok {
  2202. if value, ok := header["type"].(string); ok && value != "" {
  2203. fields.headerType = value
  2204. }
  2205. }
  2206. if value, ok := kcp["seed"].(string); ok && value != "" {
  2207. fields.seed = value
  2208. }
  2209. if value, ok := readPositiveInt(kcp["mtu"]); ok {
  2210. fields.mtu = value
  2211. }
  2212. if value, ok := readPositiveInt(kcp["tti"]); ok {
  2213. fields.tti = value
  2214. }
  2215. }
  2216. for _, rawMask := range normalizedFinalMaskUDPMasks(stream["finalmask"]) {
  2217. mask, _ := rawMask.(map[string]any)
  2218. if mask == nil {
  2219. continue
  2220. }
  2221. if maskType, _ := mask["type"].(string); maskType != "mkcp-legacy" {
  2222. continue
  2223. }
  2224. settings, _ := mask["settings"].(map[string]any)
  2225. header, _ := settings["header"].(string)
  2226. value, _ := settings["value"].(string)
  2227. if header == "" {
  2228. fields.seed = value
  2229. continue
  2230. }
  2231. if mapped, ok := kcpMaskToHeaderType[header]; ok {
  2232. fields.headerType = mapped
  2233. }
  2234. }
  2235. return fields
  2236. }
  2237. func readPositiveInt(value any) (int, bool) {
  2238. switch number := value.(type) {
  2239. case int:
  2240. return number, number > 0
  2241. case int32:
  2242. return int(number), number > 0
  2243. case int64:
  2244. return int(number), number > 0
  2245. case float32:
  2246. parsed := int(number)
  2247. return parsed, parsed > 0
  2248. case float64:
  2249. parsed := int(number)
  2250. return parsed, parsed > 0
  2251. default:
  2252. return 0, false
  2253. }
  2254. }
  2255. func setStringParam(params map[string]string, key, value string) {
  2256. if value == "" {
  2257. delete(params, key)
  2258. return
  2259. }
  2260. params[key] = value
  2261. }
  2262. func setIntParam(params map[string]string, key string, value int) {
  2263. if value <= 0 {
  2264. delete(params, key)
  2265. return
  2266. }
  2267. params[key] = fmt.Sprintf("%d", value)
  2268. }
  2269. func setStringField(obj map[string]any, key, value string) {
  2270. if value == "" {
  2271. delete(obj, key)
  2272. return
  2273. }
  2274. obj[key] = value
  2275. }
  2276. func setIntField(obj map[string]any, key string, value int) {
  2277. if value <= 0 {
  2278. delete(obj, key)
  2279. return
  2280. }
  2281. obj[key] = value
  2282. }
  2283. // applyFinalMaskParams exports the finalmask payload as the compact
  2284. // `fm=<json>` share-link field used by v2rayN-compatible clients.
  2285. func applyFinalMaskParams(finalmask map[string]any, params map[string]string) {
  2286. if fm, ok := marshalFinalMask(finalmask); ok {
  2287. params["fm"] = fm
  2288. }
  2289. }
  2290. func applyFinalMaskObj(finalmask map[string]any, obj map[string]any) {
  2291. if fm, ok := marshalFinalMask(finalmask); ok {
  2292. obj["fm"] = fm
  2293. }
  2294. }
  2295. func marshalFinalMask(finalmask map[string]any) (string, bool) {
  2296. normalized := normalizeFinalMask(finalmask)
  2297. if !hasFinalMaskContent(normalized) {
  2298. return "", false
  2299. }
  2300. b, err := json.Marshal(normalized)
  2301. if err != nil || len(b) == 0 || string(b) == "null" {
  2302. return "", false
  2303. }
  2304. return string(b), true
  2305. }
  2306. func normalizeFinalMask(finalmask map[string]any) map[string]any {
  2307. tcpMasks := normalizedFinalMaskTCPMasks(finalmask)
  2308. udpMasks := normalizedFinalMaskUDPMasks(finalmask)
  2309. quicParams, hasQuicParams := finalmask["quicParams"].(map[string]any)
  2310. if len(tcpMasks) == 0 && len(udpMasks) == 0 && !hasQuicParams {
  2311. return nil
  2312. }
  2313. result := map[string]any{}
  2314. if len(tcpMasks) > 0 {
  2315. result["tcp"] = tcpMasks
  2316. }
  2317. if len(udpMasks) > 0 {
  2318. result["udp"] = udpMasks
  2319. }
  2320. if hasQuicParams && len(quicParams) > 0 {
  2321. result["quicParams"] = quicParams
  2322. }
  2323. return result
  2324. }
  2325. func normalizedFinalMaskTCPMasks(value any) []any {
  2326. finalmask, _ := value.(map[string]any)
  2327. if finalmask == nil {
  2328. return nil
  2329. }
  2330. rawMasks, _ := finalmask["tcp"].([]any)
  2331. if len(rawMasks) == 0 {
  2332. return nil
  2333. }
  2334. normalized := make([]any, 0, len(rawMasks))
  2335. for _, rawMask := range rawMasks {
  2336. mask, _ := rawMask.(map[string]any)
  2337. if mask == nil {
  2338. continue
  2339. }
  2340. maskType, _ := mask["type"].(string)
  2341. if _, ok := validFinalMaskTCPTypes[maskType]; !ok || maskType == "" {
  2342. continue
  2343. }
  2344. normalizedMask := map[string]any{"type": maskType}
  2345. if settings, ok := mask["settings"].(map[string]any); ok && len(settings) > 0 {
  2346. normalizedMask["settings"] = settings
  2347. }
  2348. normalized = append(normalized, normalizedMask)
  2349. }
  2350. if len(normalized) == 0 {
  2351. return nil
  2352. }
  2353. return normalized
  2354. }
  2355. func normalizedFinalMaskUDPMasks(value any) []any {
  2356. finalmask, _ := value.(map[string]any)
  2357. if finalmask == nil {
  2358. return nil
  2359. }
  2360. rawMasks, _ := finalmask["udp"].([]any)
  2361. if len(rawMasks) == 0 {
  2362. return nil
  2363. }
  2364. normalized := make([]any, 0, len(rawMasks))
  2365. for _, rawMask := range rawMasks {
  2366. mask, _ := rawMask.(map[string]any)
  2367. if mask == nil {
  2368. continue
  2369. }
  2370. maskType, _ := mask["type"].(string)
  2371. if _, ok := validFinalMaskUDPTypes[maskType]; !ok || maskType == "" {
  2372. continue
  2373. }
  2374. normalizedMask := map[string]any{"type": maskType}
  2375. if settings, ok := mask["settings"].(map[string]any); ok && len(settings) > 0 {
  2376. normalizedMask["settings"] = settings
  2377. }
  2378. normalized = append(normalized, normalizedMask)
  2379. }
  2380. if len(normalized) == 0 {
  2381. return nil
  2382. }
  2383. return normalized
  2384. }
  2385. func hasFinalMaskContent(value any) bool {
  2386. switch v := value.(type) {
  2387. case nil:
  2388. return false
  2389. case string:
  2390. return len(v) > 0
  2391. case map[string]any:
  2392. for _, item := range v {
  2393. if hasFinalMaskContent(item) {
  2394. return true
  2395. }
  2396. }
  2397. return false
  2398. case []any:
  2399. return slices.ContainsFunc(v, hasFinalMaskContent)
  2400. default:
  2401. return true
  2402. }
  2403. }
  2404. func searchHost(headers any) string {
  2405. data, _ := headers.(map[string]any)
  2406. for k, v := range data {
  2407. if strings.EqualFold(k, "host") {
  2408. switch v.(type) {
  2409. case []any:
  2410. hosts, _ := v.([]any)
  2411. if len(hosts) > 0 {
  2412. h, _ := hosts[0].(string)
  2413. return h
  2414. }
  2415. return ""
  2416. case any:
  2417. h, _ := v.(string)
  2418. return h
  2419. }
  2420. }
  2421. }
  2422. return ""
  2423. }
  2424. // PageData is a view model for subpage.html
  2425. // PageData contains data for rendering the subscription information page.
  2426. type PageData struct {
  2427. Host string
  2428. BasePath string
  2429. SId string
  2430. Enabled bool
  2431. IsOnline bool
  2432. Download string
  2433. Upload string
  2434. Total string
  2435. Used string
  2436. Remained string
  2437. Expire int64
  2438. LastOnline int64
  2439. Datepicker string
  2440. DownloadByte int64
  2441. UploadByte int64
  2442. TotalByte int64
  2443. SubUrl string
  2444. SubJsonUrl string
  2445. SubClashUrl string
  2446. SubTitle string
  2447. SubSupportUrl string
  2448. SubAnnounce string
  2449. Result []string
  2450. Emails []string
  2451. }
  2452. // ResolveRequest extracts scheme and host info from request/headers consistently.
  2453. // ResolveRequest extracts scheme, host, and header information from an HTTP request.
  2454. func (s *SubService) ResolveRequest(c *gin.Context) (scheme string, host string, hostWithPort string, hostHeader string) {
  2455. trusted := s.forwardedHeadersTrusted(c)
  2456. if !trusted {
  2457. warnSuppressedForwardedHeaders(c)
  2458. }
  2459. forwarded := func(name string) string {
  2460. if !trusted {
  2461. return ""
  2462. }
  2463. return c.GetHeader(name)
  2464. }
  2465. // scheme
  2466. scheme = "http"
  2467. if c.Request.TLS != nil || strings.EqualFold(forwarded("X-Forwarded-Proto"), "https") {
  2468. scheme = "https"
  2469. }
  2470. // base host (no port)
  2471. if h, err := getHostFromXFH(forwarded("X-Forwarded-Host")); err == nil && h != "" {
  2472. host = h
  2473. }
  2474. if host == "" {
  2475. host = forwarded("X-Real-IP")
  2476. }
  2477. if host == "" {
  2478. var err error
  2479. host, _, err = net.SplitHostPort(c.Request.Host)
  2480. if err != nil {
  2481. host = c.Request.Host
  2482. }
  2483. }
  2484. // host:port for URLs
  2485. hostWithPort = forwarded("X-Forwarded-Host")
  2486. if hostWithPort == "" {
  2487. hostWithPort = c.Request.Host
  2488. }
  2489. if hostWithPort == "" {
  2490. hostWithPort = host
  2491. }
  2492. // header display host
  2493. hostHeader = forwarded("X-Forwarded-Host")
  2494. if hostHeader == "" {
  2495. hostHeader = forwarded("X-Real-IP")
  2496. }
  2497. if hostHeader == "" {
  2498. hostHeader = host
  2499. }
  2500. return
  2501. }
  2502. // BuildURLs constructs absolute subscription and JSON subscription URLs for a given subscription ID.
  2503. // It prioritizes configured URIs, then individual settings, and finally falls back to request-derived components.
  2504. func (s *SubService) BuildURLs(subPath, subJsonPath, subClashPath, subId string) (subURL, subJsonURL, subClashURL string) {
  2505. if subId == "" {
  2506. return "", "", ""
  2507. }
  2508. configuredSubURI, _ := s.settingService.GetSubURI()
  2509. configuredSubJsonURI, _ := s.settingService.GetSubJsonURI()
  2510. configuredSubClashURI, _ := s.settingService.GetSubClashURI()
  2511. // Same base as the panel's Client Information page; s.address is the
  2512. // subscriber's host already normalized away from any loopback/bind IP.
  2513. base := s.settingService.BuildSubURIBase(s.address)
  2514. subURL = s.buildSingleURL(configuredSubURI, base, subPath, subId)
  2515. // When subURI is explicitly configured (reverse-proxy setup), use its
  2516. // scheme+host as the base for JSON and Clash URLs so they match the
  2517. // reverse-proxy endpoint instead of the raw sub-server port. Fall back
  2518. // to the request-derived base if subURI is empty or can't be parsed
  2519. // into a scheme+host (e.g. a malformed value with no scheme).
  2520. jsonClashBase := base
  2521. if configuredSubURI != "" {
  2522. if derived := s.extractBaseFromURI(configuredSubURI); derived != "" {
  2523. jsonClashBase = derived
  2524. }
  2525. }
  2526. subJsonURL = s.buildSingleURL(configuredSubJsonURI, jsonClashBase, subJsonPath, subId)
  2527. subClashURL = s.buildSingleURL(configuredSubClashURI, jsonClashBase, subClashPath, subId)
  2528. return subURL, subJsonURL, subClashURL
  2529. }
  2530. // extractBaseFromURI extracts scheme://host from a configured URI.
  2531. // e.g., "https://example.com/sub-xxx/" → "https://example.com".
  2532. // Returns "" when the URI is empty or lacks a scheme/host, so callers can
  2533. // fall back to the request-derived base instead of emitting a broken value.
  2534. func (s *SubService) extractBaseFromURI(uri string) string {
  2535. u, err := url.Parse(uri)
  2536. if err != nil || u.Scheme == "" || u.Host == "" {
  2537. return ""
  2538. }
  2539. return fmt.Sprintf("%s://%s", u.Scheme, u.Host)
  2540. }
  2541. // buildSingleURL constructs a single URL using configured URI or base components
  2542. func (s *SubService) buildSingleURL(configuredURI, base, basePath, subId string) string {
  2543. if configuredURI != "" {
  2544. return s.joinPathWithID(configuredURI, subId)
  2545. }
  2546. return s.joinPathWithID(base+basePath, subId)
  2547. }
  2548. // joinPathWithID safely joins a base path with a subscription ID
  2549. func (s *SubService) joinPathWithID(basePath, subId string) string {
  2550. if strings.HasSuffix(basePath, "/") {
  2551. return basePath + subId
  2552. }
  2553. return basePath + "/" + subId
  2554. }
  2555. // BuildPageData parses header and prepares the template view model.
  2556. // BuildPageData constructs page data for rendering the subscription information page.
  2557. 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 {
  2558. download := common.FormatTraffic(traffic.Down)
  2559. upload := common.FormatTraffic(traffic.Up)
  2560. total := "∞"
  2561. used := common.FormatTraffic(traffic.Up + traffic.Down)
  2562. remained := ""
  2563. if traffic.Total > 0 {
  2564. total = common.FormatTraffic(traffic.Total)
  2565. left := max(traffic.Total-(traffic.Up+traffic.Down), 0)
  2566. remained = common.FormatTraffic(left)
  2567. }
  2568. datepicker := s.datepicker
  2569. if datepicker == "" {
  2570. datepicker = "gregorian"
  2571. }
  2572. pageLinks := make([]string, 0, len(subs))
  2573. pageEmails := make([]string, 0, len(subs))
  2574. for i, sub := range subs {
  2575. email := ""
  2576. if i < len(emails) {
  2577. email = emails[i]
  2578. }
  2579. for _, link := range splitLinkLines(sub) {
  2580. pageLinks = append(pageLinks, link)
  2581. pageEmails = append(pageEmails, email)
  2582. }
  2583. }
  2584. return PageData{
  2585. Host: hostHeader,
  2586. BasePath: basePath,
  2587. SId: subId,
  2588. Enabled: traffic.Enable,
  2589. IsOnline: subIsOnline(emails, s.inboundService.GetOnlineClients()),
  2590. Download: download,
  2591. Upload: upload,
  2592. Total: total,
  2593. Used: used,
  2594. Remained: remained,
  2595. Expire: traffic.ExpiryTime / 1000,
  2596. LastOnline: lastOnline,
  2597. Datepicker: datepicker,
  2598. DownloadByte: traffic.Down,
  2599. UploadByte: traffic.Up,
  2600. TotalByte: traffic.Total,
  2601. SubUrl: subURL,
  2602. SubJsonUrl: subJsonURL,
  2603. SubClashUrl: subClashURL,
  2604. SubTitle: subTitle,
  2605. SubSupportUrl: subSupportUrl,
  2606. Result: pageLinks,
  2607. Emails: pageEmails,
  2608. }
  2609. }
  2610. func subIsOnline(subEmails, onlineEmails []string) bool {
  2611. if len(subEmails) == 0 || len(onlineEmails) == 0 {
  2612. return false
  2613. }
  2614. onlineSet := make(map[string]struct{}, len(onlineEmails))
  2615. for _, email := range onlineEmails {
  2616. onlineSet[email] = struct{}{}
  2617. }
  2618. for _, email := range subEmails {
  2619. if _, online := onlineSet[email]; online {
  2620. return true
  2621. }
  2622. }
  2623. return false
  2624. }
  2625. func getHostFromXFH(s string) (string, error) {
  2626. if strings.Contains(s, ":") {
  2627. realHost, _, err := net.SplitHostPort(s)
  2628. if err != nil {
  2629. return "", err
  2630. }
  2631. return realHost, nil
  2632. }
  2633. return s, nil
  2634. }
  2635. // extraSalamanderKeys lists salamander settings the hysteria2 URI cannot carry.
  2636. // A server using them rejects every client built from the emitted link.
  2637. func extraSalamanderKeys(settings map[string]any) []string {
  2638. var extra []string
  2639. for k := range settings {
  2640. if k != "password" {
  2641. extra = append(extra, k)
  2642. }
  2643. }
  2644. sort.Strings(extra)
  2645. return extra
  2646. }