service.go 84 KB

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