service.go 68 KB

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