service.go 81 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628
  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')
  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 Telegram proxy deep link for an mtproto inbound:
  628. func (s *SubService) genMtprotoLink(inbound *model.Inbound, _ string) string {
  629. if inbound.Protocol != model.MTProto {
  630. return ""
  631. }
  632. settings := map[string]any{}
  633. _ = json.Unmarshal([]byte(inbound.Settings), &settings)
  634. secret, _ := settings["secret"].(string)
  635. if secret == "" {
  636. if healed, ok := model.HealMtprotoSecret(inbound.Settings); ok {
  637. _ = json.Unmarshal([]byte(healed), &settings)
  638. secret, _ = settings["secret"].(string)
  639. }
  640. }
  641. if secret == "" {
  642. return ""
  643. }
  644. params := map[string]string{
  645. "server": s.resolveInboundAddress(inbound),
  646. "port": fmt.Sprintf("%d", inbound.Port),
  647. "secret": secret,
  648. }
  649. return buildLinkWithParams("tg://proxy", params, "")
  650. }
  651. // Protocol link generators are intentionally ordered as:
  652. // vmess -> vless -> trojan -> shadowsocks -> hysteria.
  653. func (s *SubService) genVmessLink(inbound *model.Inbound, email string) string {
  654. if inbound.Protocol != model.VMESS {
  655. return ""
  656. }
  657. address := s.resolveInboundAddress(inbound)
  658. obj := map[string]any{
  659. "v": "2",
  660. "add": address,
  661. "port": inbound.Port,
  662. "type": "none",
  663. }
  664. stream := unmarshalStreamSettings(inbound.StreamSettings)
  665. network, _ := stream["network"].(string)
  666. applyVmessNetworkParams(stream, network, obj)
  667. if finalmask, ok := stream["finalmask"].(map[string]any); ok {
  668. applyFinalMaskObj(finalmask, obj)
  669. }
  670. security, _ := stream["security"].(string)
  671. obj["tls"] = security
  672. if security == "tls" {
  673. applyVmessTLSParams(stream, obj)
  674. }
  675. client, ok := s.clientForLink(inbound, email)
  676. if !ok {
  677. return ""
  678. }
  679. obj["id"] = client.ID
  680. obj["scy"] = client.Security
  681. externalProxies, _ := stream["externalProxy"].([]any)
  682. if len(externalProxies) > 0 {
  683. return s.buildVmessExternalProxyLinks(externalProxies, obj, inbound, email, network)
  684. }
  685. obj["ps"] = s.genRemark(inbound, email, "", network)
  686. return buildVmessLink(obj)
  687. }
  688. // vlessEncryptionEnabled reports whether the VLESS inbound settings enable
  689. // VLESS-level encryption (vlessenc / ML-KEM). When on, the encryption/decryption
  690. // fields hold a generated dotted string (e.g. "mlkem768x25519plus.native.0rtt.<key>");
  691. // "none" or empty means off. The value is never the literal "vlessenc" — that is
  692. // the `xray vlessenc` CLI subcommand name, not a stored value.
  693. func vlessEncryptionEnabled(settings map[string]any) bool {
  694. for _, key := range []string{"encryption", "decryption"} {
  695. if v, ok := settings[key].(string); ok && v != "" && v != "none" {
  696. return true
  697. }
  698. }
  699. return false
  700. }
  701. // vlessFlowAllowed reports whether a client's XTLS Vision flow belongs in
  702. // generated links/configs. Mirrors inboundCanEnableTlsFlow in
  703. // internal/web/service: Vision runs on TCP with tls/reality (classic), and on
  704. // XHTTP whenever VLESS encryption (vlessenc / ML-KEM) is enabled — there the
  705. // VLESS-level encryption stands in for the transport TLS that Vision relies
  706. // on, regardless of the stream security layer (so XHTTP+REALITY+vlessenc
  707. // keeps its flow too).
  708. func vlessFlowAllowed(network, security string, settings map[string]any) bool {
  709. switch network {
  710. case "tcp":
  711. return security == "tls" || security == "reality"
  712. case "xhttp":
  713. return vlessEncryptionEnabled(settings)
  714. }
  715. return false
  716. }
  717. func (s *SubService) genVlessLink(inbound *model.Inbound, email string) string {
  718. if inbound.Protocol != model.VLESS {
  719. return ""
  720. }
  721. address := s.resolveInboundAddress(inbound)
  722. stream := unmarshalStreamSettings(inbound.StreamSettings)
  723. client, ok := s.clientForLink(inbound, email)
  724. if !ok {
  725. return ""
  726. }
  727. uuid := client.ID
  728. port := inbound.Port
  729. streamNetwork := stream["network"].(string)
  730. params := make(map[string]string)
  731. params["type"] = streamNetwork
  732. // Add encryption parameter for VLESS from inbound settings
  733. settings := s.linkSettings(inbound)
  734. if encryption, ok := settings["encryption"].(string); ok {
  735. params["encryption"] = encryption
  736. }
  737. applyShareNetworkParams(stream, streamNetwork, params)
  738. if finalmask, ok := stream["finalmask"].(map[string]any); ok {
  739. applyFinalMaskParams(finalmask, params)
  740. }
  741. security, _ := stream["security"].(string)
  742. switch security {
  743. case "tls":
  744. applyShareTLSParams(stream, params)
  745. case "reality":
  746. applyShareRealityParams(stream, params, subKey(client))
  747. default:
  748. params["security"] = "none"
  749. }
  750. if len(client.Flow) > 0 && vlessFlowAllowed(streamNetwork, security, settings) {
  751. params["flow"] = client.Flow
  752. }
  753. externalProxies, _ := stream["externalProxy"].([]any)
  754. if len(externalProxies) > 0 {
  755. return s.buildExternalProxyURLLinks(
  756. externalProxies,
  757. params,
  758. security,
  759. func(ep map[string]any, dest string, port int) string {
  760. return fmt.Sprintf("vless://%s@%s", applyVlessRoute(uuid, hostVlessRoute(ep)), joinHostPort(dest, port))
  761. },
  762. func(ep map[string]any) string {
  763. return s.endpointRemark(inbound, email, ep, streamNetwork)
  764. },
  765. )
  766. }
  767. link := fmt.Sprintf("vless://%s@%s", uuid, joinHostPort(address, port))
  768. return buildLinkWithParams(link, params, s.genRemark(inbound, email, "", streamNetwork))
  769. }
  770. func (s *SubService) genTrojanLink(inbound *model.Inbound, email string) string {
  771. if inbound.Protocol != model.Trojan {
  772. return ""
  773. }
  774. address := s.resolveInboundAddress(inbound)
  775. stream := unmarshalStreamSettings(inbound.StreamSettings)
  776. client, ok := s.clientForLink(inbound, email)
  777. if !ok {
  778. return ""
  779. }
  780. password := encodeUserinfo(client.Password)
  781. port := inbound.Port
  782. streamNetwork := stream["network"].(string)
  783. params := make(map[string]string)
  784. params["type"] = streamNetwork
  785. applyShareNetworkParams(stream, streamNetwork, params)
  786. if finalmask, ok := stream["finalmask"].(map[string]any); ok {
  787. applyFinalMaskParams(finalmask, params)
  788. }
  789. security, _ := stream["security"].(string)
  790. switch security {
  791. case "tls":
  792. applyShareTLSParams(stream, params)
  793. case "reality":
  794. applyShareRealityParams(stream, params, subKey(client))
  795. if streamNetwork == "tcp" && len(client.Flow) > 0 {
  796. params["flow"] = client.Flow
  797. }
  798. default:
  799. params["security"] = "none"
  800. }
  801. externalProxies, _ := stream["externalProxy"].([]any)
  802. if len(externalProxies) > 0 {
  803. return s.buildExternalProxyURLLinks(
  804. externalProxies,
  805. params,
  806. security,
  807. func(_ map[string]any, dest string, port int) string {
  808. return fmt.Sprintf("trojan://%s@%s", password, joinHostPort(dest, port))
  809. },
  810. func(ep map[string]any) string {
  811. return s.endpointRemark(inbound, email, ep, streamNetwork)
  812. },
  813. )
  814. }
  815. link := fmt.Sprintf("trojan://%s@%s", password, joinHostPort(address, port))
  816. return buildLinkWithParams(link, params, s.genRemark(inbound, email, "", streamNetwork))
  817. }
  818. // encodeUserinfo percent-encodes a userinfo (password/auth) value so it
  819. // can be safely embedded in a `scheme://<value>@host:port` URL. RFC 3986
  820. // allows `=` in userinfo as a sub-delim, but several Trojan and Hysteria
  821. // clients reject share-links where the password contains literal `/`
  822. // or `=` (notably the common base64-with-padding shape produced by the
  823. // panel). Encode them too — this matches encodeURIComponent() on the
  824. // frontend and round-trips cleanly through net/url's parser.
  825. func encodeUserinfo(s string) string {
  826. return strings.ReplaceAll(url.QueryEscape(s), "+", "%20")
  827. }
  828. // joinHostPort wraps an IPv6 host in square brackets the way RFC 3986
  829. // requires for URI authorities, while leaving IPv4 addresses and hostnames
  830. // untouched. It also strips any brackets already present on the input so
  831. // callers don't have to normalize upstream.
  832. func joinHostPort(host string, port int) string {
  833. host = strings.Trim(host, "[]")
  834. return net.JoinHostPort(host, strconv.Itoa(port))
  835. }
  836. func (s *SubService) genShadowsocksLink(inbound *model.Inbound, email string) string {
  837. if inbound.Protocol != model.Shadowsocks {
  838. return ""
  839. }
  840. address := s.resolveInboundAddress(inbound)
  841. stream := unmarshalStreamSettings(inbound.StreamSettings)
  842. client, ok := s.clientForLink(inbound, email)
  843. if !ok {
  844. return ""
  845. }
  846. settings := s.linkSettings(inbound)
  847. inboundPassword := settings["password"].(string)
  848. method := settings["method"].(string)
  849. streamNetwork := stream["network"].(string)
  850. params := make(map[string]string)
  851. params["type"] = streamNetwork
  852. applyShareNetworkParams(stream, streamNetwork, params)
  853. if finalmask, ok := stream["finalmask"].(map[string]any); ok {
  854. applyFinalMaskParams(finalmask, params)
  855. }
  856. security, _ := stream["security"].(string)
  857. if security == "tls" {
  858. applyShareTLSParams(stream, params)
  859. }
  860. // SIP002 clients (v2rayN) ignore the xray-native type/headerType/host/path
  861. // params and only read `plugin`. Re-encode a TCP http header as obfs-local so
  862. // they build a matching tcp/http outbound (v2rayN forces request path "/").
  863. if streamNetwork == "tcp" && params["headerType"] == "http" {
  864. host := params["host"]
  865. delete(params, "type")
  866. delete(params, "headerType")
  867. delete(params, "host")
  868. delete(params, "path")
  869. params["plugin"] = "obfs-local;obfs=http;obfs-host=" + host
  870. }
  871. // SIP002 userinfo is base64(method:password). For SIP022 (2022-blake3-*) the
  872. // userinfo MUST NOT be base64-encoded; method and password are percent-encoded.
  873. var userInfo string
  874. if strings.HasPrefix(method, "2022") {
  875. userInfo = fmt.Sprintf("%s:%s:%s",
  876. url.QueryEscape(method),
  877. url.QueryEscape(inboundPassword),
  878. url.QueryEscape(client.Password))
  879. } else {
  880. userInfo = base64.RawURLEncoding.EncodeToString(fmt.Appendf(nil, "%s:%s", method, client.Password))
  881. }
  882. externalProxies, _ := stream["externalProxy"].([]any)
  883. if len(externalProxies) > 0 {
  884. proxyParams := cloneStringMap(params)
  885. proxyParams["security"] = security
  886. return s.buildExternalProxyURLLinks(
  887. externalProxies,
  888. proxyParams,
  889. security,
  890. func(_ map[string]any, dest string, port int) string {
  891. return fmt.Sprintf("ss://%s@%s", userInfo, joinHostPort(dest, port))
  892. },
  893. func(ep map[string]any) string {
  894. return s.endpointRemark(inbound, email, ep, streamNetwork)
  895. },
  896. )
  897. }
  898. link := fmt.Sprintf("ss://%s@%s", userInfo, joinHostPort(address, inbound.Port))
  899. return buildLinkWithParams(link, params, s.genRemark(inbound, email, "", streamNetwork))
  900. }
  901. func (s *SubService) genHysteriaLink(inbound *model.Inbound, email string) string {
  902. if inbound.Protocol != model.Hysteria {
  903. return ""
  904. }
  905. var stream map[string]any
  906. _ = json.Unmarshal([]byte(inbound.StreamSettings), &stream)
  907. client, ok := s.clientForLink(inbound, email)
  908. if !ok {
  909. return ""
  910. }
  911. auth := encodeUserinfo(client.Auth)
  912. params := make(map[string]string)
  913. params["security"] = "tls"
  914. tlsSetting, _ := stream["tlsSettings"].(map[string]any)
  915. alpns, _ := tlsSetting["alpn"].([]any)
  916. var alpn []string
  917. for _, a := range alpns {
  918. alpn = append(alpn, a.(string))
  919. }
  920. if len(alpn) > 0 {
  921. params["alpn"] = strings.Join(alpn, ",")
  922. }
  923. if sniValue, ok := searchKey(tlsSetting, "serverName"); ok {
  924. params["sni"], _ = sniValue.(string)
  925. }
  926. tlsSettings, _ := searchKey(tlsSetting, "settings")
  927. if tlsSetting != nil {
  928. if fpValue, ok := searchKey(tlsSettings, "fingerprint"); ok {
  929. params["fp"], _ = fpValue.(string)
  930. }
  931. if echValue, ok := searchKey(tlsSettings, "echConfigList"); ok {
  932. if ech, _ := echValue.(string); ech != "" {
  933. params["ech"] = ech
  934. }
  935. }
  936. if vcn, ok := verifyPeerCertByNameValue(tlsSettings); ok {
  937. params["vcn"] = vcn
  938. }
  939. if pins, ok := pinnedSha256List(tlsSettings); ok {
  940. for i, p := range pins {
  941. pins[i] = hysteriaPinHex(p)
  942. }
  943. params["pinSHA256"] = strings.Join(pins, ",")
  944. }
  945. }
  946. // salamander obfs (Hysteria2). The panel-side link generator already
  947. // emits these; keep the subscription output in sync so a client has
  948. // the obfs password to match the server.
  949. if finalmask, ok := stream["finalmask"].(map[string]any); ok {
  950. applyFinalMaskParams(finalmask, params)
  951. if udpMasks, ok := finalmask["udp"].([]any); ok {
  952. for _, m := range udpMasks {
  953. mask, _ := m.(map[string]any)
  954. if mask == nil || mask["type"] != "salamander" {
  955. continue
  956. }
  957. settings, _ := mask["settings"].(map[string]any)
  958. if pw, ok := settings["password"].(string); ok && pw != "" {
  959. params["obfs"] = "salamander"
  960. params["obfs-password"] = pw
  961. break
  962. }
  963. }
  964. }
  965. }
  966. settings := s.linkSettings(inbound)
  967. version, _ := settings["version"].(float64)
  968. protocol := "hysteria2"
  969. if int(version) == 1 {
  970. protocol = "hysteria"
  971. }
  972. // Fan out one link per External Proxy entry if any. Previously this
  973. // generator ignored `externalProxy` entirely, so the link kept the
  974. // server's own IP/port even when the admin configured an alternate
  975. // endpoint (e.g. a CDN hostname + port that forwards to the node).
  976. // Matches the behaviour of genVlessLink / genTrojanLink / ….
  977. externalProxies, _ := stream["externalProxy"].([]any)
  978. if len(externalProxies) > 0 {
  979. links := make([]string, 0, len(externalProxies))
  980. for _, externalProxy := range externalProxies {
  981. ep, ok := externalProxy.(map[string]any)
  982. if !ok {
  983. continue
  984. }
  985. dest, _ := ep["dest"].(string)
  986. portF, okPort := ep["port"].(float64)
  987. if dest == "" || !okPort {
  988. continue
  989. }
  990. epParams := cloneStringMap(params)
  991. applyExternalProxyHysteriaParams(ep, epParams)
  992. link := fmt.Sprintf("%s://%s@%s", protocol, auth, joinHostPort(dest, int(portF)))
  993. links = append(links, buildLinkWithParams(link, epParams, s.endpointRemark(inbound, email, ep, "quic")))
  994. }
  995. return strings.Join(links, "\n")
  996. }
  997. // No external proxy configured — use the inbound's resolved address so
  998. // node-managed inbounds get the node's host instead of the central panel's.
  999. if hopPorts := hysteriaHopPorts(stream); hopPorts != "" {
  1000. params["mport"] = hopPorts
  1001. }
  1002. link := fmt.Sprintf("%s://%s@%s", protocol, auth, joinHostPort(s.resolveInboundAddress(inbound), inbound.Port))
  1003. return buildLinkWithParams(link, params, s.genRemark(inbound, email, "", "quic"))
  1004. }
  1005. // hysteriaHopPorts returns the configured Hysteria2 UDP port-hopping range
  1006. // (finalmask.quicParams.udpHop.ports), or "" when port hopping is off. The
  1007. // range is emitted as the v2rayN-compatible `mport` query param; the URL port
  1008. // field stays numeric so .NET-Uri-based importers (v2rayN) can parse the link.
  1009. func hysteriaHopPorts(stream map[string]any) string {
  1010. finalmask, _ := stream["finalmask"].(map[string]any)
  1011. quicParams, _ := finalmask["quicParams"].(map[string]any)
  1012. udpHop, _ := quicParams["udpHop"].(map[string]any)
  1013. ports, _ := udpHop["ports"].(string)
  1014. return strings.TrimSpace(ports)
  1015. }
  1016. // loadNodes refreshes nodesByID from the DB. Called once per request so
  1017. // the per-inbound resolveInboundAddress lookups are pure map reads.
  1018. // We filter to address != ” so a half-configured node row doesn't
  1019. // accidentally produce a useless host like "https://:2053".
  1020. func (s *SubService) loadNodes() {
  1021. db := database.GetDB()
  1022. var nodes []*model.Node
  1023. if err := db.Model(&model.Node{}).Where("address != ''").Find(&nodes).Error; err != nil {
  1024. logger.Warning("subscription: load nodes failed:", err)
  1025. s.nodesByID = nil
  1026. return
  1027. }
  1028. m := make(map[int]*model.Node, len(nodes))
  1029. for _, n := range nodes {
  1030. m[n.Id] = n
  1031. }
  1032. s.nodesByID = m
  1033. }
  1034. // resolveInboundAddress picks the host an external client should connect to,
  1035. // honoring the inbound's share address strategy the same way the panel's
  1036. // share/QR link builder does (#5208):
  1037. // - "listen": an explicit, client-reachable bind Listen wins, backed by the
  1038. // node's address for node-managed inbounds;
  1039. // - "custom": the inbound's ShareAddr wins, then node, then listen;
  1040. // - "node" (default, and any unknown value): the node's address for
  1041. // node-managed inbounds, then a routable Listen — the pre-strategy order.
  1042. //
  1043. // Every chain ends at the admin's configured public host (Sub/Web domain) and
  1044. // then the subscriber's request host (s.address). Preferring the configured
  1045. // host over the request host for this last resort keeps a wildcard local inbound
  1046. // from advertising a bogus client IP that leaked into the request Host header
  1047. // behind NAT/proxy/CDN (#5425). A loopback/wildcard bind or a unix-domain-socket
  1048. // listen is a server-side detail and is never advertised; External Proxy still
  1049. // overrides everything upstream of this call.
  1050. func (s *SubService) resolveInboundAddress(inbound *model.Inbound) string {
  1051. var nodeAddr string
  1052. if inbound.NodeID != nil && s.nodesByID != nil {
  1053. if n, ok := s.nodesByID[*inbound.NodeID]; ok {
  1054. nodeAddr = n.Address
  1055. }
  1056. }
  1057. var listenAddr string
  1058. if listen := inbound.Listen; listen != "" && listen[0] != '@' && listen[0] != '/' && isRoutableHost(listen) {
  1059. listenAddr = listen
  1060. }
  1061. candidates := []string{nodeAddr, listenAddr}
  1062. switch inbound.ShareAddrStrategy {
  1063. case "listen":
  1064. candidates = []string{listenAddr, nodeAddr}
  1065. case "custom":
  1066. candidates = []string{strings.TrimSpace(inbound.ShareAddr), nodeAddr, listenAddr}
  1067. }
  1068. for _, c := range candidates {
  1069. if c != "" {
  1070. return c
  1071. }
  1072. }
  1073. if d := s.configuredPublicHost(); d != "" {
  1074. return d
  1075. }
  1076. return s.address
  1077. }
  1078. func findClientIndex(clients []model.Client, email string) int {
  1079. for i, client := range clients {
  1080. if client.Email == email {
  1081. return i
  1082. }
  1083. }
  1084. return -1
  1085. }
  1086. func unmarshalStreamSettings(streamSettings string) map[string]any {
  1087. var stream map[string]any
  1088. _ = json.Unmarshal([]byte(streamSettings), &stream)
  1089. return stream
  1090. }
  1091. func applyPathAndHostParams(settings map[string]any, params map[string]string) {
  1092. params["path"] = settings["path"].(string)
  1093. if host, ok := settings["host"].(string); ok && len(host) > 0 {
  1094. params["host"] = host
  1095. } else {
  1096. headers, _ := settings["headers"].(map[string]any)
  1097. params["host"] = searchHost(headers)
  1098. }
  1099. }
  1100. func applyPathAndHostObj(settings map[string]any, obj map[string]any) {
  1101. obj["path"] = settings["path"].(string)
  1102. if host, ok := settings["host"].(string); ok && len(host) > 0 {
  1103. obj["host"] = host
  1104. } else {
  1105. headers, _ := settings["headers"].(map[string]any)
  1106. obj["host"] = searchHost(headers)
  1107. }
  1108. }
  1109. func applyShareNetworkParams(stream map[string]any, streamNetwork string, params map[string]string) {
  1110. switch streamNetwork {
  1111. case "tcp":
  1112. tcp, _ := stream["tcpSettings"].(map[string]any)
  1113. header, _ := tcp["header"].(map[string]any)
  1114. typeStr, _ := header["type"].(string)
  1115. if typeStr == "http" {
  1116. request := header["request"].(map[string]any)
  1117. requestPath, _ := request["path"].([]any)
  1118. params["path"] = requestPath[0].(string)
  1119. host := ""
  1120. if response, ok := header["response"].(map[string]any); ok {
  1121. if respHeaders, ok := response["headers"].(map[string]any); ok {
  1122. host = searchHost(respHeaders)
  1123. }
  1124. }
  1125. if host == "" {
  1126. headers, _ := request["headers"].(map[string]any)
  1127. host = searchHost(headers)
  1128. }
  1129. params["host"] = host
  1130. params["headerType"] = "http"
  1131. }
  1132. case "kcp":
  1133. applyKcpShareParams(stream, params)
  1134. case "ws":
  1135. ws, _ := stream["wsSettings"].(map[string]any)
  1136. applyPathAndHostParams(ws, params)
  1137. case "grpc":
  1138. grpc, _ := stream["grpcSettings"].(map[string]any)
  1139. params["serviceName"] = grpc["serviceName"].(string)
  1140. params["authority"], _ = grpc["authority"].(string)
  1141. if grpc["multiMode"].(bool) {
  1142. params["mode"] = "multi"
  1143. }
  1144. case "httpupgrade":
  1145. httpupgrade, _ := stream["httpupgradeSettings"].(map[string]any)
  1146. applyPathAndHostParams(httpupgrade, params)
  1147. case "xhttp":
  1148. xhttp, _ := stream["xhttpSettings"].(map[string]any)
  1149. applyXhttpExtraParams(xhttp, params)
  1150. }
  1151. }
  1152. // applyXhttpExtraObj copies the bidirectional xhttp settings into the
  1153. // VMess base64 JSON link object. VMess supports arbitrary keys, so we
  1154. // flatten the SplitHTTPConfig "extra" fields directly onto obj.
  1155. func applyXhttpExtraObj(xhttp map[string]any, obj map[string]any) {
  1156. if xpb, ok := xhttp["xPaddingBytes"].(string); ok && len(xpb) > 0 {
  1157. obj["x_padding_bytes"] = xpb
  1158. }
  1159. maps.Copy(obj, buildXhttpExtra(xhttp))
  1160. }
  1161. func applyVmessNetworkParams(stream map[string]any, network string, obj map[string]any) {
  1162. obj["net"] = network
  1163. switch network {
  1164. case "tcp":
  1165. tcp, _ := stream["tcpSettings"].(map[string]any)
  1166. header, _ := tcp["header"].(map[string]any)
  1167. typeStr, _ := header["type"].(string)
  1168. obj["type"] = typeStr
  1169. if typeStr == "http" {
  1170. request := header["request"].(map[string]any)
  1171. requestPath, _ := request["path"].([]any)
  1172. obj["path"] = requestPath[0].(string)
  1173. host := ""
  1174. if response, ok := header["response"].(map[string]any); ok {
  1175. if respHeaders, ok := response["headers"].(map[string]any); ok {
  1176. host = searchHost(respHeaders)
  1177. }
  1178. }
  1179. if host == "" {
  1180. headers, _ := request["headers"].(map[string]any)
  1181. host = searchHost(headers)
  1182. }
  1183. obj["host"] = host
  1184. }
  1185. case "kcp":
  1186. applyKcpShareObj(stream, obj)
  1187. case "ws":
  1188. ws, _ := stream["wsSettings"].(map[string]any)
  1189. applyPathAndHostObj(ws, obj)
  1190. case "grpc":
  1191. grpc, _ := stream["grpcSettings"].(map[string]any)
  1192. obj["path"] = grpc["serviceName"].(string)
  1193. obj["authority"] = grpc["authority"].(string)
  1194. if grpc["multiMode"].(bool) {
  1195. obj["type"] = "multi"
  1196. }
  1197. case "httpupgrade":
  1198. httpupgrade, _ := stream["httpupgradeSettings"].(map[string]any)
  1199. applyPathAndHostObj(httpupgrade, obj)
  1200. case "xhttp":
  1201. xhttp, _ := stream["xhttpSettings"].(map[string]any)
  1202. applyPathAndHostObj(xhttp, obj)
  1203. if mode, ok := xhttp["mode"].(string); ok {
  1204. obj["mode"] = mode
  1205. }
  1206. applyXhttpExtraObj(xhttp, obj)
  1207. }
  1208. }
  1209. func applyShareTLSParams(stream map[string]any, params map[string]string) {
  1210. params["security"] = "tls"
  1211. tlsSetting, _ := stream["tlsSettings"].(map[string]any)
  1212. alpns, _ := tlsSetting["alpn"].([]any)
  1213. var alpn []string
  1214. for _, a := range alpns {
  1215. alpn = append(alpn, a.(string))
  1216. }
  1217. if len(alpn) > 0 {
  1218. params["alpn"] = strings.Join(alpn, ",")
  1219. }
  1220. if sniValue, ok := searchKey(tlsSetting, "serverName"); ok {
  1221. params["sni"], _ = sniValue.(string)
  1222. }
  1223. tlsSettings, _ := searchKey(tlsSetting, "settings")
  1224. if tlsSetting != nil {
  1225. if fpValue, ok := searchKey(tlsSettings, "fingerprint"); ok {
  1226. params["fp"], _ = fpValue.(string)
  1227. }
  1228. if echValue, ok := searchKey(tlsSettings, "echConfigList"); ok {
  1229. if ech, _ := echValue.(string); ech != "" {
  1230. params["ech"] = ech
  1231. }
  1232. }
  1233. if vcn, ok := verifyPeerCertByNameValue(tlsSettings); ok {
  1234. params["vcn"] = vcn
  1235. }
  1236. if pins, ok := pinnedSha256List(tlsSettings); ok {
  1237. params["pcs"] = strings.Join(pins, ",")
  1238. }
  1239. }
  1240. }
  1241. func applyVmessTLSParams(stream map[string]any, obj map[string]any) {
  1242. tlsSetting, _ := stream["tlsSettings"].(map[string]any)
  1243. alpns, _ := tlsSetting["alpn"].([]any)
  1244. if len(alpns) > 0 {
  1245. var alpn []string
  1246. for _, a := range alpns {
  1247. alpn = append(alpn, a.(string))
  1248. }
  1249. obj["alpn"] = strings.Join(alpn, ",")
  1250. }
  1251. if sniValue, ok := searchKey(tlsSetting, "serverName"); ok {
  1252. obj["sni"], _ = sniValue.(string)
  1253. }
  1254. tlsSettings, _ := searchKey(tlsSetting, "settings")
  1255. if tlsSetting != nil {
  1256. if fpValue, ok := searchKey(tlsSettings, "fingerprint"); ok {
  1257. obj["fp"], _ = fpValue.(string)
  1258. }
  1259. if echValue, ok := searchKey(tlsSettings, "echConfigList"); ok {
  1260. if ech, _ := echValue.(string); ech != "" {
  1261. obj["ech"] = ech
  1262. }
  1263. }
  1264. if vcn, ok := verifyPeerCertByNameValue(tlsSettings); ok {
  1265. obj["vcn"] = vcn
  1266. }
  1267. if pins, ok := pinnedSha256List(tlsSettings); ok {
  1268. obj["pcs"] = strings.Join(pins, ",")
  1269. }
  1270. }
  1271. }
  1272. // verifyPeerCertByNameValue extracts tlsSettings.settings.verifyPeerCertByName
  1273. // (the v2rayN `vcn` param) as a trimmed string. Like pinnedPeerCertSha256 it is
  1274. // panel-only and flows into share links so clients verify the server
  1275. // certificate by this name — the replacement for the removed allowInsecure.
  1276. func verifyPeerCertByNameValue(tlsClientSettings any) (string, bool) {
  1277. raw, ok := searchKey(tlsClientSettings, "verifyPeerCertByName")
  1278. if !ok {
  1279. return "", false
  1280. }
  1281. s, ok := raw.(string)
  1282. if !ok {
  1283. return "", false
  1284. }
  1285. if s = strings.TrimSpace(s); s == "" {
  1286. return "", false
  1287. }
  1288. return s, true
  1289. }
  1290. // pinnedSha256List extracts tlsSettings.settings.pinnedPeerCertSha256 as a
  1291. // []string. The field is panel-only (stripped before the run-config reaches
  1292. // xray-core via internal/web/service/xray.go) but flows into share links so clients
  1293. // can pin the server's certificate hash.
  1294. func pinnedSha256List(tlsClientSettings any) ([]string, bool) {
  1295. raw, ok := searchKey(tlsClientSettings, "pinnedPeerCertSha256")
  1296. if !ok {
  1297. return nil, false
  1298. }
  1299. arr, ok := raw.([]any)
  1300. if !ok || len(arr) == 0 {
  1301. return nil, false
  1302. }
  1303. out := make([]string, 0, len(arr))
  1304. for _, v := range arr {
  1305. s, ok := v.(string)
  1306. if !ok || s == "" {
  1307. continue
  1308. }
  1309. out = append(out, s)
  1310. }
  1311. if len(out) == 0 {
  1312. return nil, false
  1313. }
  1314. return out, true
  1315. }
  1316. // hysteriaPinHex normalises a pinnedPeerCertSha256 entry into the 64-character
  1317. // lowercase hex form that Xray-core's Hysteria2 pinSHA256 parser requires.
  1318. //
  1319. // The panel stores pins in several shapes: base64 (xray-core's native TLS
  1320. // format, used by the generate button and the JSON subscription) and hex —
  1321. // either bare or colon-separated as `openssl x509 -fingerprint -sha256` emits
  1322. // it. Hysteria2 clients hex-decode pinSHA256 and crash on a base64 value, so
  1323. // each entry is coerced to bare hex here. Anything that is neither a 32-byte
  1324. // hex nor a 32-byte base64 SHA-256 is returned unchanged so unexpected data is
  1325. // not silently dropped. Mirrors decodeCertPin in internal/web/service/node.go.
  1326. func hysteriaPinHex(pin string) string {
  1327. pin = strings.TrimSpace(pin)
  1328. if h := strings.ReplaceAll(pin, ":", ""); len(h) == hex.EncodedLen(sha256.Size) {
  1329. if _, err := hex.DecodeString(h); err == nil {
  1330. return strings.ToLower(h)
  1331. }
  1332. }
  1333. for _, enc := range []*base64.Encoding{
  1334. base64.StdEncoding,
  1335. base64.RawStdEncoding,
  1336. base64.URLEncoding,
  1337. base64.RawURLEncoding,
  1338. } {
  1339. if b, err := enc.DecodeString(pin); err == nil && len(b) == sha256.Size {
  1340. return hex.EncodeToString(b)
  1341. }
  1342. }
  1343. return pin
  1344. }
  1345. func applyShareRealityParams(stream map[string]any, params map[string]string, clientKey string) {
  1346. params["security"] = "reality"
  1347. realitySetting, _ := stream["realitySettings"].(map[string]any)
  1348. realitySettings, _ := searchKey(realitySetting, "settings")
  1349. if realitySetting != nil {
  1350. if sniValue, ok := searchKey(realitySetting, "serverNames"); ok {
  1351. sNames, _ := sniValue.([]any)
  1352. params["sni"] = sNames[random.Num(len(sNames))].(string)
  1353. }
  1354. if pbkValue, ok := searchKey(realitySettings, "publicKey"); ok {
  1355. params["pbk"], _ = pbkValue.(string)
  1356. }
  1357. if sidValue, ok := searchKey(realitySetting, "shortIds"); ok {
  1358. shortIds, _ := sidValue.([]any)
  1359. params["sid"] = shortIds[random.Num(len(shortIds))].(string)
  1360. }
  1361. if fpValue, ok := searchKey(realitySettings, "fingerprint"); ok {
  1362. if fp, ok := fpValue.(string); ok && len(fp) > 0 {
  1363. params["fp"] = fp
  1364. }
  1365. }
  1366. if pqvValue, ok := searchKey(realitySettings, "mldsa65Verify"); ok {
  1367. if pqv, ok := pqvValue.(string); ok && len(pqv) > 0 {
  1368. params["pqv"] = pqv
  1369. }
  1370. }
  1371. seed := ""
  1372. if spxValue, ok := searchKey(realitySettings, "spiderX"); ok {
  1373. seed, _ = spxValue.(string)
  1374. }
  1375. params["spx"] = deriveSpiderX(seed, clientKey)
  1376. }
  1377. }
  1378. // subKey returns a stable per-client identity for deterministic derivations,
  1379. // preferring the subscription id and falling back to the (unique) email.
  1380. func subKey(c model.Client) string {
  1381. if c.SubID != "" {
  1382. return c.SubID
  1383. }
  1384. return c.Email
  1385. }
  1386. // deriveSpiderX maps the inbound's spiderX seed plus a stable client key to a
  1387. // deterministic per-client "/path"; frontend/src/lib/xray/spider-x.ts mirrors it.
  1388. func deriveSpiderX(seed, clientKey string) string {
  1389. if seed == "" && clientKey == "" {
  1390. return "/" + random.Seq(15)
  1391. }
  1392. sum := sha256.Sum256([]byte(seed + "|" + clientKey))
  1393. return "/" + hex.EncodeToString(sum[:])[:15]
  1394. }
  1395. func buildVmessLink(obj map[string]any) string {
  1396. jsonStr, _ := json.MarshalIndent(obj, "", " ")
  1397. return "vmess://" + base64.StdEncoding.EncodeToString(jsonStr)
  1398. }
  1399. func cloneVmessShareObj(baseObj map[string]any, newSecurity string) map[string]any {
  1400. newObj := map[string]any{}
  1401. for key, value := range baseObj {
  1402. if newSecurity != "none" || (key != "alpn" && key != "sni" && key != "fp" && key != "pcs") {
  1403. newObj[key] = value
  1404. }
  1405. }
  1406. return newObj
  1407. }
  1408. func applyExternalProxyTLSObj(ep map[string]any, obj map[string]any, security string) {
  1409. if security != "tls" {
  1410. return
  1411. }
  1412. if sni, ok := externalProxySNI(ep); ok {
  1413. obj["sni"] = sni
  1414. }
  1415. if fp, ok := ep["fingerprint"].(string); ok && fp != "" {
  1416. obj["fp"] = fp
  1417. }
  1418. if alpn, ok := externalProxyALPN(ep["alpn"]); ok {
  1419. obj["alpn"] = alpn
  1420. }
  1421. if pins, ok := externalProxyPins(ep["pinnedPeerCertSha256"]); ok {
  1422. obj["pcs"] = joinAnyStrings(pins)
  1423. }
  1424. if vcn, ok := ep["verifyPeerCertByName"].(string); ok && vcn != "" {
  1425. obj["vcn"] = vcn
  1426. }
  1427. if ech, ok := ep["echConfigList"].(string); ok && ech != "" {
  1428. obj["ech"] = ech
  1429. }
  1430. }
  1431. func applyExternalProxyTLSParams(ep map[string]any, params map[string]string, security string) {
  1432. if security != "tls" {
  1433. return
  1434. }
  1435. if sni, ok := externalProxySNI(ep); ok {
  1436. params["sni"] = sni
  1437. }
  1438. if fp, ok := ep["fingerprint"].(string); ok && fp != "" {
  1439. params["fp"] = fp
  1440. }
  1441. if alpn, ok := externalProxyALPN(ep["alpn"]); ok {
  1442. params["alpn"] = alpn
  1443. }
  1444. if pins, ok := externalProxyPins(ep["pinnedPeerCertSha256"]); ok {
  1445. params["pcs"] = joinAnyStrings(pins)
  1446. }
  1447. if vcn, ok := ep["verifyPeerCertByName"].(string); ok && vcn != "" {
  1448. params["vcn"] = vcn
  1449. }
  1450. if ech, ok := ep["echConfigList"].(string); ok && ech != "" {
  1451. params["ech"] = ech
  1452. }
  1453. }
  1454. // applyExternalProxyHysteriaParams overrides the cert pin for a single
  1455. // external-proxy entry on a Hysteria link. Hysteria carries the pin as a hex
  1456. // `pinSHA256` (not the `pcs` the URL-param protocols use), so each entry is
  1457. // coerced through hysteriaPinHex like the main pin. sni/fp/alpn are left as
  1458. // the inbound's own — Hysteria external proxies are typically alternate
  1459. // endpoints (port-hop / CDN) fronting the same certificate.
  1460. func applyExternalProxyHysteriaParams(ep map[string]any, params map[string]string) {
  1461. pins, ok := externalProxyPins(ep["pinnedPeerCertSha256"])
  1462. if !ok {
  1463. return
  1464. }
  1465. hexPins := make([]string, 0, len(pins))
  1466. for _, p := range pins {
  1467. if s, ok := p.(string); ok {
  1468. hexPins = append(hexPins, hysteriaPinHex(s))
  1469. }
  1470. }
  1471. params["pinSHA256"] = strings.Join(hexPins, ",")
  1472. }
  1473. // cloneStreamForExternalProxy returns a shallow clone of stream with
  1474. // tlsSettings (and its nested settings map) deep-copied. The external
  1475. // proxy loop mutates tlsSettings per iteration, so without isolating
  1476. // those maps each proxy's SNI/fingerprint/ALPN would leak into the next.
  1477. func cloneStreamForExternalProxy(stream map[string]any) map[string]any {
  1478. out := cloneMap(stream)
  1479. ts, ok := out["tlsSettings"].(map[string]any)
  1480. if !ok || ts == nil {
  1481. return out
  1482. }
  1483. clonedTs := cloneMap(ts)
  1484. if inner, ok := clonedTs["settings"].(map[string]any); ok && inner != nil {
  1485. clonedTs["settings"] = cloneMap(inner)
  1486. }
  1487. out["tlsSettings"] = clonedTs
  1488. return out
  1489. }
  1490. func applyExternalProxyTLSToStream(ep map[string]any, stream map[string]any, security string) {
  1491. if security != "tls" {
  1492. return
  1493. }
  1494. tlsSettings, _ := stream["tlsSettings"].(map[string]any)
  1495. if tlsSettings == nil {
  1496. tlsSettings = map[string]any{}
  1497. stream["tlsSettings"] = tlsSettings
  1498. }
  1499. if sni, ok := externalProxySNI(ep); ok {
  1500. tlsSettings["serverName"] = sni
  1501. }
  1502. if fp, ok := ep["fingerprint"].(string); ok && fp != "" {
  1503. tlsSettings["fingerprint"] = fp
  1504. settings, _ := tlsSettings["settings"].(map[string]any)
  1505. if settings == nil {
  1506. settings = map[string]any{}
  1507. tlsSettings["settings"] = settings
  1508. }
  1509. settings["fingerprint"] = fp
  1510. }
  1511. if alpn, ok := externalProxyALPNList(ep["alpn"]); ok {
  1512. tlsSettings["alpn"] = alpn
  1513. }
  1514. if pins, ok := externalProxyPins(ep["pinnedPeerCertSha256"]); ok {
  1515. settings, _ := tlsSettings["settings"].(map[string]any)
  1516. if settings == nil {
  1517. settings = map[string]any{}
  1518. tlsSettings["settings"] = settings
  1519. }
  1520. settings["pinnedPeerCertSha256"] = pins
  1521. }
  1522. if ech, ok := ep["echConfigList"].(string); ok && ech != "" {
  1523. settings, _ := tlsSettings["settings"].(map[string]any)
  1524. if settings == nil {
  1525. settings = map[string]any{}
  1526. tlsSettings["settings"] = settings
  1527. }
  1528. settings["echConfigList"] = ech
  1529. }
  1530. if vcn, ok := ep["verifyPeerCertByName"].(string); ok && vcn != "" {
  1531. settings, _ := tlsSettings["settings"].(map[string]any)
  1532. if settings == nil {
  1533. settings = map[string]any{}
  1534. tlsSettings["settings"] = settings
  1535. }
  1536. settings["verifyPeerCertByName"] = vcn
  1537. }
  1538. if ai, ok := ep["allowInsecure"].(bool); ok && ai {
  1539. settings, _ := tlsSettings["settings"].(map[string]any)
  1540. if settings == nil {
  1541. settings = map[string]any{}
  1542. tlsSettings["settings"] = settings
  1543. }
  1544. settings["allowInsecure"] = true
  1545. }
  1546. }
  1547. func externalProxySNI(ep map[string]any) (string, bool) {
  1548. if sni, ok := ep["sni"].(string); ok && sni != "" {
  1549. return sni, true
  1550. }
  1551. return "", false
  1552. }
  1553. func externalProxyALPN(value any) (string, bool) {
  1554. switch v := value.(type) {
  1555. case string:
  1556. return v, v != ""
  1557. case []string:
  1558. if len(v) == 0 {
  1559. return "", false
  1560. }
  1561. return strings.Join(v, ","), true
  1562. case []any:
  1563. alpn := make([]string, 0, len(v))
  1564. for _, item := range v {
  1565. if s, ok := item.(string); ok && s != "" {
  1566. alpn = append(alpn, s)
  1567. }
  1568. }
  1569. if len(alpn) == 0 {
  1570. return "", false
  1571. }
  1572. return strings.Join(alpn, ","), true
  1573. default:
  1574. return "", false
  1575. }
  1576. }
  1577. func externalProxyALPNList(value any) ([]any, bool) {
  1578. switch v := value.(type) {
  1579. case string:
  1580. if v == "" {
  1581. return nil, false
  1582. }
  1583. parts := strings.Split(v, ",")
  1584. out := make([]any, 0, len(parts))
  1585. for _, part := range parts {
  1586. if part = strings.TrimSpace(part); part != "" {
  1587. out = append(out, part)
  1588. }
  1589. }
  1590. return out, len(out) > 0
  1591. case []string:
  1592. out := make([]any, 0, len(v))
  1593. for _, item := range v {
  1594. if item != "" {
  1595. out = append(out, item)
  1596. }
  1597. }
  1598. return out, len(out) > 0
  1599. case []any:
  1600. out := make([]any, 0, len(v))
  1601. for _, item := range v {
  1602. if s, ok := item.(string); ok && s != "" {
  1603. out = append(out, s)
  1604. }
  1605. }
  1606. return out, len(out) > 0
  1607. default:
  1608. return nil, false
  1609. }
  1610. }
  1611. // externalProxyPins extracts an external-proxy entry's pinnedPeerCertSha256
  1612. // as a []any of non-empty strings. The []any element type matches what the
  1613. // JSON/Clash sub builders expect when reading the value back off the cloned
  1614. // stream's tlsSettings.settings.
  1615. func externalProxyPins(value any) ([]any, bool) {
  1616. switch v := value.(type) {
  1617. case []string:
  1618. out := make([]any, 0, len(v))
  1619. for _, item := range v {
  1620. if item != "" {
  1621. out = append(out, item)
  1622. }
  1623. }
  1624. return out, len(out) > 0
  1625. case []any:
  1626. out := make([]any, 0, len(v))
  1627. for _, item := range v {
  1628. if s, ok := item.(string); ok && s != "" {
  1629. out = append(out, s)
  1630. }
  1631. }
  1632. return out, len(out) > 0
  1633. default:
  1634. return nil, false
  1635. }
  1636. }
  1637. func joinAnyStrings(items []any) string {
  1638. parts := make([]string, 0, len(items))
  1639. for _, item := range items {
  1640. if s, ok := item.(string); ok {
  1641. parts = append(parts, s)
  1642. }
  1643. }
  1644. return strings.Join(parts, ",")
  1645. }
  1646. // buildVmessExternalProxyLinks is a thin adapter: it maps the legacy
  1647. // externalProxy entries to []ShareEndpoint and renders them through the unified
  1648. // endpoint path. Kept as a thin shim over the unified endpoint builder so
  1649. // genVmessLink keeps calling one helper (now threading transport through).
  1650. func (s *SubService) buildVmessExternalProxyLinks(externalProxies []any, baseObj map[string]any, inbound *model.Inbound, email string, transport string) string {
  1651. eps := make([]ShareEndpoint, 0, len(externalProxies))
  1652. for _, externalProxy := range externalProxies {
  1653. ep, _ := externalProxy.(map[string]any)
  1654. eps = append(eps, externalProxyToEndpoint(ep))
  1655. }
  1656. return s.buildEndpointVmessLinks(eps, baseObj, inbound, email, transport)
  1657. }
  1658. // buildLinkWithParams appends ?query and #fragment to a pre-built
  1659. // scheme://userinfo@host:port string without re-parsing it. The caller
  1660. // has already escaped userinfo via encodeUserinfo (or chosen a base64
  1661. // alphabet with no reserved chars); a url.Parse + .String() round-trip
  1662. // would silently decode that escaping because Go's userinfo emitter
  1663. // leaves sub-delims (=, +, ;) literal, which breaks Trojan/Hysteria/SS
  1664. // clients that reject those chars in the password.
  1665. func buildLinkWithParams(link string, params map[string]string, fragment string) string {
  1666. return appendQueryAndFragment(link, params, fragment, "", false)
  1667. }
  1668. // buildLinkWithParamsAndSecurity is buildLinkWithParams plus an
  1669. // external-proxy override: the `security` key in params is replaced with
  1670. // the supplied value, and TLS hint fields (alpn/sni/fp/pcs) are stripped
  1671. // when the override is `none`.
  1672. func buildLinkWithParamsAndSecurity(link string, params map[string]string, fragment, security string, omitTLSFields bool) string {
  1673. return appendQueryAndFragment(link, params, fragment, security, omitTLSFields)
  1674. }
  1675. func appendQueryAndFragment(link string, params map[string]string, fragment, securityOverride string, omitTLSFields bool) string {
  1676. var sb strings.Builder
  1677. sb.WriteString(link)
  1678. if len(params) > 0 {
  1679. q := url.Values{}
  1680. for k, v := range params {
  1681. if securityOverride != "" && k == "security" {
  1682. v = securityOverride
  1683. }
  1684. if omitTLSFields && (k == "alpn" || k == "sni" || k == "fp" || k == "pcs") {
  1685. continue
  1686. }
  1687. q.Set(k, v)
  1688. }
  1689. encoded := q.Encode()
  1690. if encoded != "" {
  1691. if strings.Contains(link, "?") {
  1692. sb.WriteByte('&')
  1693. } else {
  1694. sb.WriteByte('?')
  1695. }
  1696. sb.WriteString(encoded)
  1697. }
  1698. }
  1699. if fragment != "" {
  1700. sb.WriteByte('#')
  1701. // Match the frontend's encodeURIComponent(remark): spaces become
  1702. // %20 (not + as in query strings).
  1703. sb.WriteString(strings.ReplaceAll(url.QueryEscape(fragment), "+", "%20"))
  1704. }
  1705. return sb.String()
  1706. }
  1707. // buildExternalProxyURLLinks is a thin adapter: it maps the legacy externalProxy
  1708. // entries to []ShareEndpoint and renders them through the unified endpoint path.
  1709. // Kept so the genVless/genTrojan/genShadowsocks call sites are unchanged.
  1710. func (s *SubService) buildExternalProxyURLLinks(
  1711. externalProxies []any,
  1712. params map[string]string,
  1713. baseSecurity string,
  1714. makeLink func(ep map[string]any, dest string, port int) string,
  1715. makeRemark func(ep map[string]any) string,
  1716. ) string {
  1717. eps := make([]ShareEndpoint, 0, len(externalProxies))
  1718. for _, externalProxy := range externalProxies {
  1719. ep, _ := externalProxy.(map[string]any)
  1720. eps = append(eps, externalProxyToEndpoint(ep))
  1721. }
  1722. return s.buildEndpointLinks(eps, params, baseSecurity, func(e ShareEndpoint) string {
  1723. return makeLink(e.ep, e.Address, e.Port)
  1724. }, func(e ShareEndpoint) string {
  1725. return makeRemark(e.ep)
  1726. })
  1727. }
  1728. func cloneStringMap(source map[string]string) map[string]string {
  1729. cloned := make(map[string]string, len(source))
  1730. maps.Copy(cloned, source)
  1731. return cloned
  1732. }
  1733. // genRemark builds the remark for a non-host link (raw default / legacy
  1734. // externalProxy / synthetic JSON-Clash entry). A set remark template drives it
  1735. // in both the body and display contexts (genTemplatedRemark renders the
  1736. // name-only part on displays); with no template it falls back to the inbound
  1737. // remark, extra and email joined by "-".
  1738. func (s *SubService) genRemark(inbound *model.Inbound, email string, extra string, transport string) string {
  1739. if s.remarkTemplate != "" {
  1740. return s.genTemplatedRemark(inbound, s.lookupClient(inbound, email), extra, transport)
  1741. }
  1742. return fallbackRemark(inbound.Remark, extra, email)
  1743. }
  1744. func fallbackRemark(parts ...string) string {
  1745. out := make([]string, 0, len(parts))
  1746. for _, p := range parts {
  1747. if p != "" {
  1748. out = append(out, p)
  1749. }
  1750. }
  1751. return strings.Join(out, "-")
  1752. }
  1753. // findClientStats returns the inbound's traffic record for email, if present.
  1754. func (s *SubService) findClientStats(inbound *model.Inbound, email string) (xray.ClientTraffic, bool) {
  1755. for _, clientStat := range inbound.ClientStats {
  1756. if clientStat.Email == email {
  1757. return clientStat, true
  1758. }
  1759. }
  1760. return xray.ClientTraffic{}, false
  1761. }
  1762. // statsByEmailFromDB resolves a client's traffic row straight from the DB by its
  1763. // globally-unique email, caching the hit into statsByEmail for the rest of the
  1764. // request. It's the last-resort lookup behind statsForClient: the preloaded
  1765. // ClientStats and the statsByEmail index are both keyed by
  1766. // client_traffics.inbound_id, which is written once by AddClientStat and never
  1767. // updated. When an inbound is deleted and recreated it gets a new id, so the old
  1768. // row is orphaned from every loaded inbound and both in-memory paths miss —
  1769. // leaving {{TRAFFIC_USED}} stuck at 0 for pre-existing clients even though their
  1770. // usage is intact (#5567). Matching by email recovers it, the same way the
  1771. // sub-info header's AggregateTrafficByEmails already does.
  1772. func (s *SubService) statsByEmailFromDB(email string) (xray.ClientTraffic, bool) {
  1773. db := database.GetDB()
  1774. if db == nil {
  1775. return xray.ClientTraffic{}, false
  1776. }
  1777. var row xray.ClientTraffic
  1778. if err := db.Model(&xray.ClientTraffic{}).Where("email = ?", email).First(&row).Error; err != nil {
  1779. return xray.ClientTraffic{}, false
  1780. }
  1781. if s.statsByEmail == nil {
  1782. s.statsByEmail = map[string]xray.ClientTraffic{}
  1783. }
  1784. s.statsByEmail[email] = row
  1785. return row, true
  1786. }
  1787. func searchKey(data any, key string) (any, bool) {
  1788. switch val := data.(type) {
  1789. case map[string]any:
  1790. for k, v := range val {
  1791. if k == key {
  1792. return v, true
  1793. }
  1794. if result, ok := searchKey(v, key); ok {
  1795. return result, true
  1796. }
  1797. }
  1798. case []any:
  1799. for _, v := range val {
  1800. if result, ok := searchKey(v, key); ok {
  1801. return result, true
  1802. }
  1803. }
  1804. }
  1805. return nil, false
  1806. }
  1807. // buildXhttpExtra walks an xhttpSettings map and returns the JSON blob
  1808. // that goes into the URL's `extra` param (or, for VMess, the link
  1809. // object). Carries ONLY the bidirectional fields from xray-core's
  1810. // SplitHTTPConfig — i.e. the ones the server enforces and the client
  1811. // must match. Strictly one-sided fields are excluded:
  1812. //
  1813. // - server-only (noSSEHeader, scMaxBufferedPosts, scStreamUpServerSecs,
  1814. // serverMaxHeaderBytes) — client wouldn't read them, so emitting
  1815. // them just bloats the URL.
  1816. // - client-only values are included only when present in the inbound
  1817. // JSON. Some deployments/imported configs carry them there, and the
  1818. // subscription link is the only place clients can receive them.
  1819. //
  1820. // Truthy-only guards keep default inbounds emitting the same compact URL
  1821. // they did before this helper grew.
  1822. func buildXhttpExtra(xhttp map[string]any) map[string]any {
  1823. if xhttp == nil {
  1824. return nil
  1825. }
  1826. extra := map[string]any{}
  1827. if mode, ok := xhttp["mode"].(string); ok && len(mode) > 0 {
  1828. extra["mode"] = mode
  1829. }
  1830. if xpb, ok := xhttp["xPaddingBytes"].(string); ok && len(xpb) > 0 {
  1831. extra["xPaddingBytes"] = xpb
  1832. }
  1833. if obfs, ok := xhttp["xPaddingObfsMode"].(bool); ok && obfs {
  1834. extra["xPaddingObfsMode"] = true
  1835. for _, field := range []string{"xPaddingKey", "xPaddingHeader", "xPaddingPlacement", "xPaddingMethod"} {
  1836. if v, ok := xhttp[field].(string); ok && len(v) > 0 {
  1837. extra[field] = v
  1838. }
  1839. }
  1840. }
  1841. stringFields := []string{
  1842. "uplinkHTTPMethod",
  1843. "sessionIDPlacement", "sessionIDKey", "sessionIDTable", "sessionIDLength",
  1844. "seqPlacement", "seqKey",
  1845. "uplinkDataPlacement", "uplinkDataKey",
  1846. "scMaxEachPostBytes", "scMinPostsIntervalMs",
  1847. }
  1848. // Values matching xray-core's own defaults are redundant on the wire and
  1849. // the literal scMinPostsIntervalMs=30 is a known DPI fingerprint (#5141).
  1850. // Old panels seeded these defaults into every xhttp inbound, so filter
  1851. // them here instead of requiring every stored config to be re-saved.
  1852. coreDefaults := map[string]string{
  1853. "scMaxEachPostBytes": "1000000",
  1854. "scMinPostsIntervalMs": "30",
  1855. }
  1856. for _, field := range stringFields {
  1857. if v, ok := xhttp[field].(string); ok && len(v) > 0 && v != coreDefaults[field] {
  1858. extra[field] = v
  1859. }
  1860. }
  1861. // Legacy inbounds (pre xray-core #6258) stored sessionPlacement/sessionKey.
  1862. // Lift them onto the renamed keys so links from not-yet-resaved configs
  1863. // still carry the session settings. Mirrors the frontend migration.
  1864. for legacy, renamed := range map[string]string{
  1865. "sessionPlacement": "sessionIDPlacement",
  1866. "sessionKey": "sessionIDKey",
  1867. } {
  1868. if _, exists := extra[renamed]; !exists {
  1869. if v, ok := xhttp[legacy].(string); ok && len(v) > 0 {
  1870. extra[renamed] = v
  1871. }
  1872. }
  1873. }
  1874. for _, field := range []string{"uplinkChunkSize"} {
  1875. if v, ok := nonZeroShareValue(xhttp[field]); ok {
  1876. extra[field] = v
  1877. }
  1878. }
  1879. for _, field := range []string{"noGRPCHeader"} {
  1880. if v, ok := xhttp[field].(bool); ok && v {
  1881. extra[field] = v
  1882. }
  1883. }
  1884. for _, field := range []string{"xmux", "downloadSettings"} {
  1885. if v, ok := nonEmptyShareObject(xhttp[field]); ok {
  1886. extra[field] = v
  1887. }
  1888. }
  1889. // Headers — emitted as the {name: value} map upstream's struct
  1890. // expects. The server runtime ignores this field, but the client
  1891. // (consuming the share link) honors it. Drop any "host" entry —
  1892. // host already wins as a top-level URL param.
  1893. if rawHeaders, ok := xhttp["headers"].(map[string]any); ok && len(rawHeaders) > 0 {
  1894. out := map[string]any{}
  1895. for k, v := range rawHeaders {
  1896. if strings.EqualFold(k, "host") {
  1897. continue
  1898. }
  1899. out[k] = v
  1900. }
  1901. if len(out) > 0 {
  1902. extra["headers"] = out
  1903. }
  1904. }
  1905. if len(extra) == 0 {
  1906. return nil
  1907. }
  1908. return extra
  1909. }
  1910. func nonZeroShareValue(v any) (any, bool) {
  1911. switch value := v.(type) {
  1912. case string:
  1913. return value, value != ""
  1914. case int:
  1915. return value, value != 0
  1916. case int32:
  1917. return value, value != 0
  1918. case int64:
  1919. return value, value != 0
  1920. case float32:
  1921. return value, value != 0
  1922. case float64:
  1923. return value, value != 0
  1924. default:
  1925. return nil, false
  1926. }
  1927. }
  1928. func nonEmptyShareObject(v any) (any, bool) {
  1929. switch value := v.(type) {
  1930. case map[string]any:
  1931. return value, len(value) > 0
  1932. case map[string]string:
  1933. return value, len(value) > 0
  1934. case []any:
  1935. return value, len(value) > 0
  1936. default:
  1937. return nil, false
  1938. }
  1939. }
  1940. // applyXhttpExtraParams emits the full xhttp config into the URL query
  1941. // params of a vless:// / trojan:// / ss:// link. Sets path/host/mode at
  1942. // top level (xray's Build() always lets these win over `extra`) and packs
  1943. // everything else into a JSON `extra` param. Also writes the flat
  1944. // `x_padding_bytes` param sing-box-family clients understand.
  1945. //
  1946. // Without this, the admin's custom xPaddingBytes / sessionKey / etc. never
  1947. // reach the client and handshakes are silently rejected with
  1948. // `invalid padding (...) length: 0` — the client-visible symptom is
  1949. // "xhttp doesn't connect" on OpenWRT / sing-box.
  1950. //
  1951. // Two encodings are written so every popular client can read at least one:
  1952. //
  1953. // - x_padding_bytes=<range> — flat param, understood by sing-box and its
  1954. // derivatives (Podkop, OpenWRT sing-box, Karing, NekoBox, …).
  1955. // - extra=<url-encoded-json> — full xhttp settings blob, which is how
  1956. // xray-core clients (v2rayNG, Happ, Furious, Exclave, …) pick up the
  1957. // bidirectional fields beyond path/host/mode.
  1958. func applyXhttpExtraParams(xhttp map[string]any, params map[string]string) {
  1959. if xhttp == nil {
  1960. return
  1961. }
  1962. applyPathAndHostParams(xhttp, params)
  1963. if mode, ok := xhttp["mode"].(string); ok {
  1964. params["mode"] = mode
  1965. }
  1966. if xpb, ok := xhttp["xPaddingBytes"].(string); ok && len(xpb) > 0 {
  1967. params["x_padding_bytes"] = xpb
  1968. }
  1969. extra := buildXhttpExtra(xhttp)
  1970. if extra != nil {
  1971. if b, err := json.Marshal(extra); err == nil {
  1972. params["extra"] = string(b)
  1973. }
  1974. }
  1975. }
  1976. var kcpMaskToHeaderType = map[string]string{
  1977. "dns": "dns",
  1978. "dtls": "dtls",
  1979. "srtp": "srtp",
  1980. "utp": "utp",
  1981. "wechat": "wechat-video",
  1982. "wireguard": "wireguard",
  1983. }
  1984. var validFinalMaskUDPTypes = map[string]struct{}{
  1985. "salamander": {},
  1986. "mkcp-legacy": {},
  1987. "xdns": {},
  1988. "xicmp": {},
  1989. "noise": {},
  1990. "header-custom": {},
  1991. "realm": {},
  1992. }
  1993. var validFinalMaskTCPTypes = map[string]struct{}{
  1994. "header-custom": {},
  1995. "fragment": {},
  1996. "sudoku": {},
  1997. }
  1998. // applyKcpShareParams reconstructs legacy KCP share-link fields from either
  1999. // the historical kcpSettings.header/seed shape or the current finalmask model.
  2000. // This keeps subscription output compatible while avoiding panics when older
  2001. // keys are absent from modern inbounds.
  2002. func applyKcpShareParams(stream map[string]any, params map[string]string) {
  2003. extractKcpShareFields(stream).applyToParams(params)
  2004. }
  2005. func applyKcpShareObj(stream map[string]any, obj map[string]any) {
  2006. extractKcpShareFields(stream).applyToObj(obj)
  2007. }
  2008. type kcpShareFields struct {
  2009. headerType string
  2010. seed string
  2011. mtu int
  2012. tti int
  2013. }
  2014. func (f kcpShareFields) applyToParams(params map[string]string) {
  2015. if f.headerType != "" && f.headerType != "none" {
  2016. params["headerType"] = f.headerType
  2017. }
  2018. setStringParam(params, "seed", f.seed)
  2019. setIntParam(params, "mtu", f.mtu)
  2020. setIntParam(params, "tti", f.tti)
  2021. }
  2022. func (f kcpShareFields) applyToObj(obj map[string]any) {
  2023. if f.headerType != "" && f.headerType != "none" {
  2024. obj["type"] = f.headerType
  2025. }
  2026. setStringField(obj, "path", f.seed)
  2027. setIntField(obj, "mtu", f.mtu)
  2028. setIntField(obj, "tti", f.tti)
  2029. }
  2030. func extractKcpShareFields(stream map[string]any) kcpShareFields {
  2031. fields := kcpShareFields{headerType: "none"}
  2032. if kcp, ok := stream["kcpSettings"].(map[string]any); ok {
  2033. if header, ok := kcp["header"].(map[string]any); ok {
  2034. if value, ok := header["type"].(string); ok && value != "" {
  2035. fields.headerType = value
  2036. }
  2037. }
  2038. if value, ok := kcp["seed"].(string); ok && value != "" {
  2039. fields.seed = value
  2040. }
  2041. if value, ok := readPositiveInt(kcp["mtu"]); ok {
  2042. fields.mtu = value
  2043. }
  2044. if value, ok := readPositiveInt(kcp["tti"]); ok {
  2045. fields.tti = value
  2046. }
  2047. }
  2048. for _, rawMask := range normalizedFinalMaskUDPMasks(stream["finalmask"]) {
  2049. mask, _ := rawMask.(map[string]any)
  2050. if mask == nil {
  2051. continue
  2052. }
  2053. if maskType, _ := mask["type"].(string); maskType != "mkcp-legacy" {
  2054. continue
  2055. }
  2056. settings, _ := mask["settings"].(map[string]any)
  2057. header, _ := settings["header"].(string)
  2058. value, _ := settings["value"].(string)
  2059. if header == "" {
  2060. fields.seed = value
  2061. continue
  2062. }
  2063. if mapped, ok := kcpMaskToHeaderType[header]; ok {
  2064. fields.headerType = mapped
  2065. }
  2066. }
  2067. return fields
  2068. }
  2069. func readPositiveInt(value any) (int, bool) {
  2070. switch number := value.(type) {
  2071. case int:
  2072. return number, number > 0
  2073. case int32:
  2074. return int(number), number > 0
  2075. case int64:
  2076. return int(number), number > 0
  2077. case float32:
  2078. parsed := int(number)
  2079. return parsed, parsed > 0
  2080. case float64:
  2081. parsed := int(number)
  2082. return parsed, parsed > 0
  2083. default:
  2084. return 0, false
  2085. }
  2086. }
  2087. func setStringParam(params map[string]string, key, value string) {
  2088. if value == "" {
  2089. delete(params, key)
  2090. return
  2091. }
  2092. params[key] = value
  2093. }
  2094. func setIntParam(params map[string]string, key string, value int) {
  2095. if value <= 0 {
  2096. delete(params, key)
  2097. return
  2098. }
  2099. params[key] = fmt.Sprintf("%d", value)
  2100. }
  2101. func setStringField(obj map[string]any, key, value string) {
  2102. if value == "" {
  2103. delete(obj, key)
  2104. return
  2105. }
  2106. obj[key] = value
  2107. }
  2108. func setIntField(obj map[string]any, key string, value int) {
  2109. if value <= 0 {
  2110. delete(obj, key)
  2111. return
  2112. }
  2113. obj[key] = value
  2114. }
  2115. // applyFinalMaskParams exports the finalmask payload as the compact
  2116. // `fm=<json>` share-link field used by v2rayN-compatible clients.
  2117. func applyFinalMaskParams(finalmask map[string]any, params map[string]string) {
  2118. if fm, ok := marshalFinalMask(finalmask); ok {
  2119. params["fm"] = fm
  2120. }
  2121. }
  2122. func applyFinalMaskObj(finalmask map[string]any, obj map[string]any) {
  2123. if fm, ok := marshalFinalMask(finalmask); ok {
  2124. obj["fm"] = fm
  2125. }
  2126. }
  2127. func marshalFinalMask(finalmask map[string]any) (string, bool) {
  2128. normalized := normalizeFinalMask(finalmask)
  2129. if !hasFinalMaskContent(normalized) {
  2130. return "", false
  2131. }
  2132. b, err := json.Marshal(normalized)
  2133. if err != nil || len(b) == 0 || string(b) == "null" {
  2134. return "", false
  2135. }
  2136. return string(b), true
  2137. }
  2138. func normalizeFinalMask(finalmask map[string]any) map[string]any {
  2139. tcpMasks := normalizedFinalMaskTCPMasks(finalmask)
  2140. udpMasks := normalizedFinalMaskUDPMasks(finalmask)
  2141. quicParams, hasQuicParams := finalmask["quicParams"].(map[string]any)
  2142. if len(tcpMasks) == 0 && len(udpMasks) == 0 && !hasQuicParams {
  2143. return nil
  2144. }
  2145. result := map[string]any{}
  2146. if len(tcpMasks) > 0 {
  2147. result["tcp"] = tcpMasks
  2148. }
  2149. if len(udpMasks) > 0 {
  2150. result["udp"] = udpMasks
  2151. }
  2152. if hasQuicParams && len(quicParams) > 0 {
  2153. result["quicParams"] = quicParams
  2154. }
  2155. return result
  2156. }
  2157. func normalizedFinalMaskTCPMasks(value any) []any {
  2158. finalmask, _ := value.(map[string]any)
  2159. if finalmask == nil {
  2160. return nil
  2161. }
  2162. rawMasks, _ := finalmask["tcp"].([]any)
  2163. if len(rawMasks) == 0 {
  2164. return nil
  2165. }
  2166. normalized := make([]any, 0, len(rawMasks))
  2167. for _, rawMask := range rawMasks {
  2168. mask, _ := rawMask.(map[string]any)
  2169. if mask == nil {
  2170. continue
  2171. }
  2172. maskType, _ := mask["type"].(string)
  2173. if _, ok := validFinalMaskTCPTypes[maskType]; !ok || maskType == "" {
  2174. continue
  2175. }
  2176. normalizedMask := map[string]any{"type": maskType}
  2177. if settings, ok := mask["settings"].(map[string]any); ok && len(settings) > 0 {
  2178. normalizedMask["settings"] = settings
  2179. }
  2180. normalized = append(normalized, normalizedMask)
  2181. }
  2182. if len(normalized) == 0 {
  2183. return nil
  2184. }
  2185. return normalized
  2186. }
  2187. func normalizedFinalMaskUDPMasks(value any) []any {
  2188. finalmask, _ := value.(map[string]any)
  2189. if finalmask == nil {
  2190. return nil
  2191. }
  2192. rawMasks, _ := finalmask["udp"].([]any)
  2193. if len(rawMasks) == 0 {
  2194. return nil
  2195. }
  2196. normalized := make([]any, 0, len(rawMasks))
  2197. for _, rawMask := range rawMasks {
  2198. mask, _ := rawMask.(map[string]any)
  2199. if mask == nil {
  2200. continue
  2201. }
  2202. maskType, _ := mask["type"].(string)
  2203. if _, ok := validFinalMaskUDPTypes[maskType]; !ok || maskType == "" {
  2204. continue
  2205. }
  2206. normalizedMask := map[string]any{"type": maskType}
  2207. if settings, ok := mask["settings"].(map[string]any); ok && len(settings) > 0 {
  2208. normalizedMask["settings"] = settings
  2209. }
  2210. normalized = append(normalized, normalizedMask)
  2211. }
  2212. if len(normalized) == 0 {
  2213. return nil
  2214. }
  2215. return normalized
  2216. }
  2217. func hasFinalMaskContent(value any) bool {
  2218. switch v := value.(type) {
  2219. case nil:
  2220. return false
  2221. case string:
  2222. return len(v) > 0
  2223. case map[string]any:
  2224. for _, item := range v {
  2225. if hasFinalMaskContent(item) {
  2226. return true
  2227. }
  2228. }
  2229. return false
  2230. case []any:
  2231. return slices.ContainsFunc(v, hasFinalMaskContent)
  2232. default:
  2233. return true
  2234. }
  2235. }
  2236. func searchHost(headers any) string {
  2237. data, _ := headers.(map[string]any)
  2238. for k, v := range data {
  2239. if strings.EqualFold(k, "host") {
  2240. switch v.(type) {
  2241. case []any:
  2242. hosts, _ := v.([]any)
  2243. if len(hosts) > 0 {
  2244. return hosts[0].(string)
  2245. } else {
  2246. return ""
  2247. }
  2248. case any:
  2249. return v.(string)
  2250. }
  2251. }
  2252. }
  2253. return ""
  2254. }
  2255. // PageData is a view model for subpage.html
  2256. // PageData contains data for rendering the subscription information page.
  2257. type PageData struct {
  2258. Host string
  2259. BasePath string
  2260. SId string
  2261. Enabled bool
  2262. Download string
  2263. Upload string
  2264. Total string
  2265. Used string
  2266. Remained string
  2267. Expire int64
  2268. LastOnline int64
  2269. Datepicker string
  2270. DownloadByte int64
  2271. UploadByte int64
  2272. TotalByte int64
  2273. SubUrl string
  2274. SubJsonUrl string
  2275. SubClashUrl string
  2276. SubTitle string
  2277. SubSupportUrl string
  2278. Result []string
  2279. Emails []string
  2280. }
  2281. // ResolveRequest extracts scheme and host info from request/headers consistently.
  2282. // ResolveRequest extracts scheme, host, and header information from an HTTP request.
  2283. func (s *SubService) ResolveRequest(c *gin.Context) (scheme string, host string, hostWithPort string, hostHeader string) {
  2284. // scheme
  2285. scheme = "http"
  2286. if c.Request.TLS != nil || strings.EqualFold(c.GetHeader("X-Forwarded-Proto"), "https") {
  2287. scheme = "https"
  2288. }
  2289. // base host (no port)
  2290. if h, err := getHostFromXFH(c.GetHeader("X-Forwarded-Host")); err == nil && h != "" {
  2291. host = h
  2292. }
  2293. if host == "" {
  2294. host = c.GetHeader("X-Real-IP")
  2295. }
  2296. if host == "" {
  2297. var err error
  2298. host, _, err = net.SplitHostPort(c.Request.Host)
  2299. if err != nil {
  2300. host = c.Request.Host
  2301. }
  2302. }
  2303. // host:port for URLs
  2304. hostWithPort = c.GetHeader("X-Forwarded-Host")
  2305. if hostWithPort == "" {
  2306. hostWithPort = c.Request.Host
  2307. }
  2308. if hostWithPort == "" {
  2309. hostWithPort = host
  2310. }
  2311. // header display host
  2312. hostHeader = c.GetHeader("X-Forwarded-Host")
  2313. if hostHeader == "" {
  2314. hostHeader = c.GetHeader("X-Real-IP")
  2315. }
  2316. if hostHeader == "" {
  2317. hostHeader = host
  2318. }
  2319. return
  2320. }
  2321. // BuildURLs constructs absolute subscription and JSON subscription URLs for a given subscription ID.
  2322. // It prioritizes configured URIs, then individual settings, and finally falls back to request-derived components.
  2323. func (s *SubService) BuildURLs(subPath, subJsonPath, subClashPath, subId string) (subURL, subJsonURL, subClashURL string) {
  2324. if subId == "" {
  2325. return "", "", ""
  2326. }
  2327. configuredSubURI, _ := s.settingService.GetSubURI()
  2328. configuredSubJsonURI, _ := s.settingService.GetSubJsonURI()
  2329. configuredSubClashURI, _ := s.settingService.GetSubClashURI()
  2330. // Same base as the panel's Client Information page; s.address is the
  2331. // subscriber's host already normalized away from any loopback/bind IP.
  2332. base := s.settingService.BuildSubURIBase(s.address)
  2333. subURL = s.buildSingleURL(configuredSubURI, base, subPath, subId)
  2334. // When subURI is explicitly configured (reverse-proxy setup), use its
  2335. // scheme+host as the base for JSON and Clash URLs so they match the
  2336. // reverse-proxy endpoint instead of the raw sub-server port. Fall back
  2337. // to the request-derived base if subURI is empty or can't be parsed
  2338. // into a scheme+host (e.g. a malformed value with no scheme).
  2339. jsonClashBase := base
  2340. if configuredSubURI != "" {
  2341. if derived := s.extractBaseFromURI(configuredSubURI); derived != "" {
  2342. jsonClashBase = derived
  2343. }
  2344. }
  2345. subJsonURL = s.buildSingleURL(configuredSubJsonURI, jsonClashBase, subJsonPath, subId)
  2346. subClashURL = s.buildSingleURL(configuredSubClashURI, jsonClashBase, subClashPath, subId)
  2347. return subURL, subJsonURL, subClashURL
  2348. }
  2349. // extractBaseFromURI extracts scheme://host from a configured URI.
  2350. // e.g., "https://example.com/sub-xxx/" → "https://example.com".
  2351. // Returns "" when the URI is empty or lacks a scheme/host, so callers can
  2352. // fall back to the request-derived base instead of emitting a broken value.
  2353. func (s *SubService) extractBaseFromURI(uri string) string {
  2354. u, err := url.Parse(uri)
  2355. if err != nil || u.Scheme == "" || u.Host == "" {
  2356. return ""
  2357. }
  2358. return fmt.Sprintf("%s://%s", u.Scheme, u.Host)
  2359. }
  2360. // buildSingleURL constructs a single URL using configured URI or base components
  2361. func (s *SubService) buildSingleURL(configuredURI, base, basePath, subId string) string {
  2362. if configuredURI != "" {
  2363. return s.joinPathWithID(configuredURI, subId)
  2364. }
  2365. return s.joinPathWithID(base+basePath, subId)
  2366. }
  2367. // joinPathWithID safely joins a base path with a subscription ID
  2368. func (s *SubService) joinPathWithID(basePath, subId string) string {
  2369. if strings.HasSuffix(basePath, "/") {
  2370. return basePath + subId
  2371. }
  2372. return basePath + "/" + subId
  2373. }
  2374. // BuildPageData parses header and prepares the template view model.
  2375. // BuildPageData constructs page data for rendering the subscription information page.
  2376. 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 {
  2377. download := common.FormatTraffic(traffic.Down)
  2378. upload := common.FormatTraffic(traffic.Up)
  2379. total := "∞"
  2380. used := common.FormatTraffic(traffic.Up + traffic.Down)
  2381. remained := ""
  2382. if traffic.Total > 0 {
  2383. total = common.FormatTraffic(traffic.Total)
  2384. left := max(traffic.Total-(traffic.Up+traffic.Down), 0)
  2385. remained = common.FormatTraffic(left)
  2386. }
  2387. datepicker := s.datepicker
  2388. if datepicker == "" {
  2389. datepicker = "gregorian"
  2390. }
  2391. pageLinks := make([]string, 0, len(subs))
  2392. pageEmails := make([]string, 0, len(subs))
  2393. for i, sub := range subs {
  2394. email := ""
  2395. if i < len(emails) {
  2396. email = emails[i]
  2397. }
  2398. for _, link := range splitLinkLines(sub) {
  2399. pageLinks = append(pageLinks, link)
  2400. pageEmails = append(pageEmails, email)
  2401. }
  2402. }
  2403. return PageData{
  2404. Host: hostHeader,
  2405. BasePath: basePath,
  2406. SId: subId,
  2407. Enabled: traffic.Enable,
  2408. Download: download,
  2409. Upload: upload,
  2410. Total: total,
  2411. Used: used,
  2412. Remained: remained,
  2413. Expire: traffic.ExpiryTime / 1000,
  2414. LastOnline: lastOnline,
  2415. Datepicker: datepicker,
  2416. DownloadByte: traffic.Down,
  2417. UploadByte: traffic.Up,
  2418. TotalByte: traffic.Total,
  2419. SubUrl: subURL,
  2420. SubJsonUrl: subJsonURL,
  2421. SubClashUrl: subClashURL,
  2422. SubTitle: subTitle,
  2423. SubSupportUrl: subSupportUrl,
  2424. Result: pageLinks,
  2425. Emails: pageEmails,
  2426. }
  2427. }
  2428. func getHostFromXFH(s string) (string, error) {
  2429. if strings.Contains(s, ":") {
  2430. realHost, _, err := net.SplitHostPort(s)
  2431. if err != nil {
  2432. return "", err
  2433. }
  2434. return realHost, nil
  2435. }
  2436. return s, nil
  2437. }