1
0

service.go 81 KB

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