service.go 99 KB

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