1
0

service.go 101 KB

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