1
0

service.go 82 KB

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