1
0

service.go 101 KB

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