service.go 91 KB

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