service.go 101 KB

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