1
0

service.go 91 KB

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