1
0

service.go 95 KB

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