service.go 69 KB

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