1
0

service.go 103 KB

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