1
0

service.go 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271
  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).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. func (s *SubService) genVlessLink(inbound *model.Inbound, email string) string {
  452. if inbound.Protocol != model.VLESS {
  453. return ""
  454. }
  455. address := s.resolveInboundAddress(inbound)
  456. stream := unmarshalStreamSettings(inbound.StreamSettings)
  457. clients, _ := s.inboundService.GetClients(inbound)
  458. clientIndex := findClientIndex(clients, email)
  459. uuid := clients[clientIndex].ID
  460. port := inbound.Port
  461. streamNetwork := stream["network"].(string)
  462. params := make(map[string]string)
  463. params["type"] = streamNetwork
  464. // Add encryption parameter for VLESS from inbound settings
  465. var settings map[string]any
  466. json.Unmarshal([]byte(inbound.Settings), &settings)
  467. if encryption, ok := settings["encryption"].(string); ok {
  468. params["encryption"] = encryption
  469. }
  470. applyShareNetworkParams(stream, streamNetwork, params)
  471. if finalmask, ok := stream["finalmask"].(map[string]any); ok {
  472. applyFinalMaskParams(finalmask, params)
  473. }
  474. security, _ := stream["security"].(string)
  475. switch security {
  476. case "tls":
  477. applyShareTLSParams(stream, params)
  478. if streamNetwork == "tcp" && len(clients[clientIndex].Flow) > 0 {
  479. params["flow"] = clients[clientIndex].Flow
  480. }
  481. case "reality":
  482. applyShareRealityParams(stream, params)
  483. if streamNetwork == "tcp" && len(clients[clientIndex].Flow) > 0 {
  484. params["flow"] = clients[clientIndex].Flow
  485. }
  486. default:
  487. params["security"] = "none"
  488. // VLESS encryption (vlessenc / ML-KEM) carries XTLS Vision over XHTTP
  489. // without transport TLS.
  490. if streamNetwork == "xhttp" && len(clients[clientIndex].Flow) > 0 && vlessEncryptionEnabled(settings) {
  491. params["flow"] = clients[clientIndex].Flow
  492. }
  493. }
  494. externalProxies, _ := stream["externalProxy"].([]any)
  495. if len(externalProxies) > 0 {
  496. return s.buildExternalProxyURLLinks(
  497. externalProxies,
  498. params,
  499. security,
  500. func(dest string, port int) string {
  501. return fmt.Sprintf("vless://%s@%s:%d", uuid, dest, port)
  502. },
  503. func(ep map[string]any) string {
  504. return s.genRemark(inbound, email, ep["remark"].(string))
  505. },
  506. )
  507. }
  508. link := fmt.Sprintf("vless://%s@%s:%d", uuid, address, port)
  509. return buildLinkWithParams(link, params, s.genRemark(inbound, email, ""))
  510. }
  511. func (s *SubService) genTrojanLink(inbound *model.Inbound, email string) string {
  512. if inbound.Protocol != model.Trojan {
  513. return ""
  514. }
  515. address := s.resolveInboundAddress(inbound)
  516. stream := unmarshalStreamSettings(inbound.StreamSettings)
  517. clients, _ := s.inboundService.GetClients(inbound)
  518. clientIndex := findClientIndex(clients, email)
  519. password := encodeUserinfo(clients[clientIndex].Password)
  520. port := inbound.Port
  521. streamNetwork := stream["network"].(string)
  522. params := make(map[string]string)
  523. params["type"] = streamNetwork
  524. applyShareNetworkParams(stream, streamNetwork, params)
  525. if finalmask, ok := stream["finalmask"].(map[string]any); ok {
  526. applyFinalMaskParams(finalmask, params)
  527. }
  528. security, _ := stream["security"].(string)
  529. switch security {
  530. case "tls":
  531. applyShareTLSParams(stream, params)
  532. case "reality":
  533. applyShareRealityParams(stream, params)
  534. if streamNetwork == "tcp" && len(clients[clientIndex].Flow) > 0 {
  535. params["flow"] = clients[clientIndex].Flow
  536. }
  537. default:
  538. params["security"] = "none"
  539. }
  540. externalProxies, _ := stream["externalProxy"].([]any)
  541. if len(externalProxies) > 0 {
  542. return s.buildExternalProxyURLLinks(
  543. externalProxies,
  544. params,
  545. security,
  546. func(dest string, port int) string {
  547. return fmt.Sprintf("trojan://%s@%s:%d", password, dest, port)
  548. },
  549. func(ep map[string]any) string {
  550. return s.genRemark(inbound, email, ep["remark"].(string))
  551. },
  552. )
  553. }
  554. link := fmt.Sprintf("trojan://%s@%s:%d", password, address, port)
  555. return buildLinkWithParams(link, params, s.genRemark(inbound, email, ""))
  556. }
  557. // encodeUserinfo percent-encodes a userinfo (password/auth) value so it
  558. // can be safely embedded in a `scheme://<value>@host:port` URL. RFC 3986
  559. // allows `=` in userinfo as a sub-delim, but several Trojan and Hysteria
  560. // clients reject share-links where the password contains literal `/`
  561. // or `=` (notably the common base64-with-padding shape produced by the
  562. // panel). Encode them too — this matches encodeURIComponent() on the
  563. // frontend and round-trips cleanly through net/url's parser.
  564. func encodeUserinfo(s string) string {
  565. return strings.ReplaceAll(url.QueryEscape(s), "+", "%20")
  566. }
  567. func (s *SubService) genShadowsocksLink(inbound *model.Inbound, email string) string {
  568. if inbound.Protocol != model.Shadowsocks {
  569. return ""
  570. }
  571. address := s.resolveInboundAddress(inbound)
  572. stream := unmarshalStreamSettings(inbound.StreamSettings)
  573. clients, _ := s.inboundService.GetClients(inbound)
  574. var settings map[string]any
  575. json.Unmarshal([]byte(inbound.Settings), &settings)
  576. inboundPassword := settings["password"].(string)
  577. method := settings["method"].(string)
  578. clientIndex := findClientIndex(clients, email)
  579. streamNetwork := stream["network"].(string)
  580. params := make(map[string]string)
  581. params["type"] = streamNetwork
  582. applyShareNetworkParams(stream, streamNetwork, params)
  583. if finalmask, ok := stream["finalmask"].(map[string]any); ok {
  584. applyFinalMaskParams(finalmask, params)
  585. }
  586. security, _ := stream["security"].(string)
  587. if security == "tls" {
  588. applyShareTLSParams(stream, params)
  589. }
  590. encPart := fmt.Sprintf("%s:%s", method, clients[clientIndex].Password)
  591. if method[0] == '2' {
  592. encPart = fmt.Sprintf("%s:%s:%s", method, inboundPassword, clients[clientIndex].Password)
  593. }
  594. externalProxies, _ := stream["externalProxy"].([]any)
  595. if len(externalProxies) > 0 {
  596. proxyParams := cloneStringMap(params)
  597. proxyParams["security"] = security
  598. return s.buildExternalProxyURLLinks(
  599. externalProxies,
  600. proxyParams,
  601. security,
  602. func(dest string, port int) string {
  603. return fmt.Sprintf("ss://%s@%s:%d", base64.RawURLEncoding.EncodeToString([]byte(encPart)), dest, port)
  604. },
  605. func(ep map[string]any) string {
  606. return s.genRemark(inbound, email, ep["remark"].(string))
  607. },
  608. )
  609. }
  610. link := fmt.Sprintf("ss://%s@%s:%d", base64.RawURLEncoding.EncodeToString([]byte(encPart)), address, inbound.Port)
  611. return buildLinkWithParams(link, params, s.genRemark(inbound, email, ""))
  612. }
  613. func (s *SubService) genHysteriaLink(inbound *model.Inbound, email string) string {
  614. if inbound.Protocol != model.Hysteria {
  615. return ""
  616. }
  617. var stream map[string]any
  618. json.Unmarshal([]byte(inbound.StreamSettings), &stream)
  619. clients, _ := s.inboundService.GetClients(inbound)
  620. clientIndex := -1
  621. for i, client := range clients {
  622. if client.Email == email {
  623. clientIndex = i
  624. break
  625. }
  626. }
  627. auth := encodeUserinfo(clients[clientIndex].Auth)
  628. params := make(map[string]string)
  629. params["security"] = "tls"
  630. tlsSetting, _ := stream["tlsSettings"].(map[string]any)
  631. alpns, _ := tlsSetting["alpn"].([]any)
  632. var alpn []string
  633. for _, a := range alpns {
  634. alpn = append(alpn, a.(string))
  635. }
  636. if len(alpn) > 0 {
  637. params["alpn"] = strings.Join(alpn, ",")
  638. }
  639. if sniValue, ok := searchKey(tlsSetting, "serverName"); ok {
  640. params["sni"], _ = sniValue.(string)
  641. }
  642. tlsSettings, _ := searchKey(tlsSetting, "settings")
  643. if tlsSetting != nil {
  644. if fpValue, ok := searchKey(tlsSettings, "fingerprint"); ok {
  645. params["fp"], _ = fpValue.(string)
  646. }
  647. if echValue, ok := searchKey(tlsSettings, "echConfigList"); ok {
  648. if ech, _ := echValue.(string); ech != "" {
  649. params["ech"] = ech
  650. }
  651. }
  652. if pins, ok := pinnedSha256List(tlsSettings); ok {
  653. for i, p := range pins {
  654. pins[i] = hysteriaPinHex(p)
  655. }
  656. params["pinSHA256"] = strings.Join(pins, ",")
  657. }
  658. }
  659. // salamander obfs (Hysteria2). The panel-side link generator already
  660. // emits these; keep the subscription output in sync so a client has
  661. // the obfs password to match the server.
  662. if finalmask, ok := stream["finalmask"].(map[string]any); ok {
  663. applyFinalMaskParams(finalmask, params)
  664. if udpMasks, ok := finalmask["udp"].([]any); ok {
  665. for _, m := range udpMasks {
  666. mask, _ := m.(map[string]any)
  667. if mask == nil || mask["type"] != "salamander" {
  668. continue
  669. }
  670. settings, _ := mask["settings"].(map[string]any)
  671. if pw, ok := settings["password"].(string); ok && pw != "" {
  672. params["obfs"] = "salamander"
  673. params["obfs-password"] = pw
  674. break
  675. }
  676. }
  677. }
  678. }
  679. var settings map[string]any
  680. json.Unmarshal([]byte(inbound.Settings), &settings)
  681. version, _ := settings["version"].(float64)
  682. protocol := "hysteria2"
  683. if int(version) == 1 {
  684. protocol = "hysteria"
  685. }
  686. // Fan out one link per External Proxy entry if any. Previously this
  687. // generator ignored `externalProxy` entirely, so the link kept the
  688. // server's own IP/port even when the admin configured an alternate
  689. // endpoint (e.g. a CDN hostname + port that forwards to the node).
  690. // Matches the behaviour of genVlessLink / genTrojanLink / ….
  691. externalProxies, _ := stream["externalProxy"].([]any)
  692. if len(externalProxies) > 0 {
  693. links := make([]string, 0, len(externalProxies))
  694. for _, externalProxy := range externalProxies {
  695. ep, ok := externalProxy.(map[string]any)
  696. if !ok {
  697. continue
  698. }
  699. dest, _ := ep["dest"].(string)
  700. portF, okPort := ep["port"].(float64)
  701. if dest == "" || !okPort {
  702. continue
  703. }
  704. epRemark, _ := ep["remark"].(string)
  705. epParams := cloneStringMap(params)
  706. applyExternalProxyHysteriaParams(ep, epParams)
  707. link := fmt.Sprintf("%s://%s@%s:%d", protocol, auth, dest, int(portF))
  708. links = append(links, buildLinkWithParams(link, epParams, s.genRemark(inbound, email, epRemark)))
  709. }
  710. return strings.Join(links, "\n")
  711. }
  712. // No external proxy configured — use the inbound's resolved address so
  713. // node-managed inbounds get the node's host instead of the central panel's.
  714. if hopPorts := hysteriaHopPorts(stream); hopPorts != "" {
  715. params["mport"] = hopPorts
  716. }
  717. link := fmt.Sprintf("%s://%s@%s:%d", protocol, auth, s.resolveInboundAddress(inbound), inbound.Port)
  718. return buildLinkWithParams(link, params, s.genRemark(inbound, email, ""))
  719. }
  720. // hysteriaHopPorts returns the configured Hysteria2 UDP port-hopping range
  721. // (finalmask.quicParams.udpHop.ports), or "" when port hopping is off. The
  722. // range is emitted as the v2rayN-compatible `mport` query param; the URL port
  723. // field stays numeric so .NET-Uri-based importers (v2rayN) can parse the link.
  724. func hysteriaHopPorts(stream map[string]any) string {
  725. finalmask, _ := stream["finalmask"].(map[string]any)
  726. quicParams, _ := finalmask["quicParams"].(map[string]any)
  727. udpHop, _ := quicParams["udpHop"].(map[string]any)
  728. ports, _ := udpHop["ports"].(string)
  729. return strings.TrimSpace(ports)
  730. }
  731. // loadNodes refreshes nodesByID from the DB. Called once per request so
  732. // the per-inbound resolveInboundAddress lookups are pure map reads.
  733. // We filter to address != ” so a half-configured node row doesn't
  734. // accidentally produce a useless host like "https://:2053".
  735. func (s *SubService) loadNodes() {
  736. db := database.GetDB()
  737. var nodes []*model.Node
  738. if err := db.Model(&model.Node{}).Where("address != ''").Find(&nodes).Error; err != nil {
  739. logger.Warning("subscription: load nodes failed:", err)
  740. s.nodesByID = nil
  741. return
  742. }
  743. m := make(map[int]*model.Node, len(nodes))
  744. for _, n := range nodes {
  745. m[n.Id] = n
  746. }
  747. s.nodesByID = m
  748. }
  749. // resolveInboundAddress picks the host an external client should connect to,
  750. // honoring the inbound's share address strategy the same way the panel's
  751. // share/QR link builder does (#5208):
  752. // - "listen": an explicit, client-reachable bind Listen wins, backed by the
  753. // node's address for node-managed inbounds;
  754. // - "custom": the inbound's ShareAddr wins, then node, then listen;
  755. // - "node" (default, and any unknown value): the node's address for
  756. // node-managed inbounds, then a routable Listen — the pre-strategy order.
  757. //
  758. // Every chain ends at the subscriber's request host (s.address). A
  759. // loopback/wildcard bind or a unix-domain-socket listen is a server-side
  760. // detail and is never advertised; External Proxy still overrides everything
  761. // upstream of this call.
  762. func (s *SubService) resolveInboundAddress(inbound *model.Inbound) string {
  763. var nodeAddr string
  764. if inbound.NodeID != nil && s.nodesByID != nil {
  765. if n, ok := s.nodesByID[*inbound.NodeID]; ok {
  766. nodeAddr = n.Address
  767. }
  768. }
  769. var listenAddr string
  770. if listen := inbound.Listen; listen != "" && listen[0] != '@' && listen[0] != '/' && isRoutableHost(listen) {
  771. listenAddr = listen
  772. }
  773. candidates := []string{nodeAddr, listenAddr}
  774. switch inbound.ShareAddrStrategy {
  775. case "listen":
  776. candidates = []string{listenAddr, nodeAddr}
  777. case "custom":
  778. candidates = []string{strings.TrimSpace(inbound.ShareAddr), nodeAddr, listenAddr}
  779. }
  780. for _, c := range candidates {
  781. if c != "" {
  782. return c
  783. }
  784. }
  785. return s.address
  786. }
  787. func findClientIndex(clients []model.Client, email string) int {
  788. for i, client := range clients {
  789. if client.Email == email {
  790. return i
  791. }
  792. }
  793. return -1
  794. }
  795. func unmarshalStreamSettings(streamSettings string) map[string]any {
  796. var stream map[string]any
  797. json.Unmarshal([]byte(streamSettings), &stream)
  798. return stream
  799. }
  800. func applyPathAndHostParams(settings map[string]any, params map[string]string) {
  801. params["path"] = settings["path"].(string)
  802. if host, ok := settings["host"].(string); ok && len(host) > 0 {
  803. params["host"] = host
  804. } else {
  805. headers, _ := settings["headers"].(map[string]any)
  806. params["host"] = searchHost(headers)
  807. }
  808. }
  809. func applyPathAndHostObj(settings map[string]any, obj map[string]any) {
  810. obj["path"] = settings["path"].(string)
  811. if host, ok := settings["host"].(string); ok && len(host) > 0 {
  812. obj["host"] = host
  813. } else {
  814. headers, _ := settings["headers"].(map[string]any)
  815. obj["host"] = searchHost(headers)
  816. }
  817. }
  818. func applyShareNetworkParams(stream map[string]any, streamNetwork string, params map[string]string) {
  819. switch streamNetwork {
  820. case "tcp":
  821. tcp, _ := stream["tcpSettings"].(map[string]any)
  822. header, _ := tcp["header"].(map[string]any)
  823. typeStr, _ := header["type"].(string)
  824. if typeStr == "http" {
  825. request := header["request"].(map[string]any)
  826. requestPath, _ := request["path"].([]any)
  827. params["path"] = requestPath[0].(string)
  828. host := ""
  829. if response, ok := header["response"].(map[string]any); ok {
  830. if respHeaders, ok := response["headers"].(map[string]any); ok {
  831. host = searchHost(respHeaders)
  832. }
  833. }
  834. if host == "" {
  835. headers, _ := request["headers"].(map[string]any)
  836. host = searchHost(headers)
  837. }
  838. params["host"] = host
  839. params["headerType"] = "http"
  840. }
  841. case "kcp":
  842. applyKcpShareParams(stream, params)
  843. case "ws":
  844. ws, _ := stream["wsSettings"].(map[string]any)
  845. applyPathAndHostParams(ws, params)
  846. case "grpc":
  847. grpc, _ := stream["grpcSettings"].(map[string]any)
  848. params["serviceName"] = grpc["serviceName"].(string)
  849. params["authority"], _ = grpc["authority"].(string)
  850. if grpc["multiMode"].(bool) {
  851. params["mode"] = "multi"
  852. }
  853. case "httpupgrade":
  854. httpupgrade, _ := stream["httpupgradeSettings"].(map[string]any)
  855. applyPathAndHostParams(httpupgrade, params)
  856. case "xhttp":
  857. xhttp, _ := stream["xhttpSettings"].(map[string]any)
  858. applyXhttpExtraParams(xhttp, params)
  859. }
  860. }
  861. // applyXhttpExtraObj copies the bidirectional xhttp settings into the
  862. // VMess base64 JSON link object. VMess supports arbitrary keys, so we
  863. // flatten the SplitHTTPConfig "extra" fields directly onto obj.
  864. func applyXhttpExtraObj(xhttp map[string]any, obj map[string]any) {
  865. if xpb, ok := xhttp["xPaddingBytes"].(string); ok && len(xpb) > 0 {
  866. obj["x_padding_bytes"] = xpb
  867. }
  868. maps.Copy(obj, buildXhttpExtra(xhttp))
  869. }
  870. func applyVmessNetworkParams(stream map[string]any, network string, obj map[string]any) {
  871. obj["net"] = network
  872. switch network {
  873. case "tcp":
  874. tcp, _ := stream["tcpSettings"].(map[string]any)
  875. header, _ := tcp["header"].(map[string]any)
  876. typeStr, _ := header["type"].(string)
  877. obj["type"] = typeStr
  878. if typeStr == "http" {
  879. request := header["request"].(map[string]any)
  880. requestPath, _ := request["path"].([]any)
  881. obj["path"] = requestPath[0].(string)
  882. host := ""
  883. if response, ok := header["response"].(map[string]any); ok {
  884. if respHeaders, ok := response["headers"].(map[string]any); ok {
  885. host = searchHost(respHeaders)
  886. }
  887. }
  888. if host == "" {
  889. headers, _ := request["headers"].(map[string]any)
  890. host = searchHost(headers)
  891. }
  892. obj["host"] = host
  893. }
  894. case "kcp":
  895. applyKcpShareObj(stream, obj)
  896. case "ws":
  897. ws, _ := stream["wsSettings"].(map[string]any)
  898. applyPathAndHostObj(ws, obj)
  899. case "grpc":
  900. grpc, _ := stream["grpcSettings"].(map[string]any)
  901. obj["path"] = grpc["serviceName"].(string)
  902. obj["authority"] = grpc["authority"].(string)
  903. if grpc["multiMode"].(bool) {
  904. obj["type"] = "multi"
  905. }
  906. case "httpupgrade":
  907. httpupgrade, _ := stream["httpupgradeSettings"].(map[string]any)
  908. applyPathAndHostObj(httpupgrade, obj)
  909. case "xhttp":
  910. xhttp, _ := stream["xhttpSettings"].(map[string]any)
  911. applyPathAndHostObj(xhttp, obj)
  912. if mode, ok := xhttp["mode"].(string); ok {
  913. obj["mode"] = mode
  914. }
  915. applyXhttpExtraObj(xhttp, obj)
  916. }
  917. }
  918. func applyShareTLSParams(stream map[string]any, params map[string]string) {
  919. params["security"] = "tls"
  920. tlsSetting, _ := stream["tlsSettings"].(map[string]any)
  921. alpns, _ := tlsSetting["alpn"].([]any)
  922. var alpn []string
  923. for _, a := range alpns {
  924. alpn = append(alpn, a.(string))
  925. }
  926. if len(alpn) > 0 {
  927. params["alpn"] = strings.Join(alpn, ",")
  928. }
  929. if sniValue, ok := searchKey(tlsSetting, "serverName"); ok {
  930. params["sni"], _ = sniValue.(string)
  931. }
  932. tlsSettings, _ := searchKey(tlsSetting, "settings")
  933. if tlsSetting != nil {
  934. if fpValue, ok := searchKey(tlsSettings, "fingerprint"); ok {
  935. params["fp"], _ = fpValue.(string)
  936. }
  937. if echValue, ok := searchKey(tlsSettings, "echConfigList"); ok {
  938. if ech, _ := echValue.(string); ech != "" {
  939. params["ech"] = ech
  940. }
  941. }
  942. if pins, ok := pinnedSha256List(tlsSettings); ok {
  943. params["pcs"] = strings.Join(pins, ",")
  944. }
  945. }
  946. }
  947. func applyVmessTLSParams(stream map[string]any, obj map[string]any) {
  948. tlsSetting, _ := stream["tlsSettings"].(map[string]any)
  949. alpns, _ := tlsSetting["alpn"].([]any)
  950. if len(alpns) > 0 {
  951. var alpn []string
  952. for _, a := range alpns {
  953. alpn = append(alpn, a.(string))
  954. }
  955. obj["alpn"] = strings.Join(alpn, ",")
  956. }
  957. if sniValue, ok := searchKey(tlsSetting, "serverName"); ok {
  958. obj["sni"], _ = sniValue.(string)
  959. }
  960. tlsSettings, _ := searchKey(tlsSetting, "settings")
  961. if tlsSetting != nil {
  962. if fpValue, ok := searchKey(tlsSettings, "fingerprint"); ok {
  963. obj["fp"], _ = fpValue.(string)
  964. }
  965. if echValue, ok := searchKey(tlsSettings, "echConfigList"); ok {
  966. if ech, _ := echValue.(string); ech != "" {
  967. obj["ech"] = ech
  968. }
  969. }
  970. if pins, ok := pinnedSha256List(tlsSettings); ok {
  971. obj["pcs"] = strings.Join(pins, ",")
  972. }
  973. }
  974. }
  975. // pinnedSha256List extracts tlsSettings.settings.pinnedPeerCertSha256 as a
  976. // []string. The field is panel-only (stripped before the run-config reaches
  977. // xray-core via internal/web/service/xray.go) but flows into share links so clients
  978. // can pin the server's certificate hash.
  979. func pinnedSha256List(tlsClientSettings any) ([]string, bool) {
  980. raw, ok := searchKey(tlsClientSettings, "pinnedPeerCertSha256")
  981. if !ok {
  982. return nil, false
  983. }
  984. arr, ok := raw.([]any)
  985. if !ok || len(arr) == 0 {
  986. return nil, false
  987. }
  988. out := make([]string, 0, len(arr))
  989. for _, v := range arr {
  990. s, ok := v.(string)
  991. if !ok || s == "" {
  992. continue
  993. }
  994. out = append(out, s)
  995. }
  996. if len(out) == 0 {
  997. return nil, false
  998. }
  999. return out, true
  1000. }
  1001. // hysteriaPinHex normalises a pinnedPeerCertSha256 entry into the 64-character
  1002. // lowercase hex form that Xray-core's Hysteria2 pinSHA256 parser requires.
  1003. //
  1004. // The panel stores pins in several shapes: base64 (xray-core's native TLS
  1005. // format, used by the generate button and the JSON subscription) and hex —
  1006. // either bare or colon-separated as `openssl x509 -fingerprint -sha256` emits
  1007. // it. Hysteria2 clients hex-decode pinSHA256 and crash on a base64 value, so
  1008. // each entry is coerced to bare hex here. Anything that is neither a 32-byte
  1009. // hex nor a 32-byte base64 SHA-256 is returned unchanged so unexpected data is
  1010. // not silently dropped. Mirrors decodeCertPin in internal/web/service/node.go.
  1011. func hysteriaPinHex(pin string) string {
  1012. pin = strings.TrimSpace(pin)
  1013. if h := strings.ReplaceAll(pin, ":", ""); len(h) == hex.EncodedLen(sha256.Size) {
  1014. if _, err := hex.DecodeString(h); err == nil {
  1015. return strings.ToLower(h)
  1016. }
  1017. }
  1018. for _, enc := range []*base64.Encoding{
  1019. base64.StdEncoding,
  1020. base64.RawStdEncoding,
  1021. base64.URLEncoding,
  1022. base64.RawURLEncoding,
  1023. } {
  1024. if b, err := enc.DecodeString(pin); err == nil && len(b) == sha256.Size {
  1025. return hex.EncodeToString(b)
  1026. }
  1027. }
  1028. return pin
  1029. }
  1030. func applyShareRealityParams(stream map[string]any, params map[string]string) {
  1031. params["security"] = "reality"
  1032. realitySetting, _ := stream["realitySettings"].(map[string]any)
  1033. realitySettings, _ := searchKey(realitySetting, "settings")
  1034. if realitySetting != nil {
  1035. if sniValue, ok := searchKey(realitySetting, "serverNames"); ok {
  1036. sNames, _ := sniValue.([]any)
  1037. params["sni"] = sNames[random.Num(len(sNames))].(string)
  1038. }
  1039. if pbkValue, ok := searchKey(realitySettings, "publicKey"); ok {
  1040. params["pbk"], _ = pbkValue.(string)
  1041. }
  1042. if sidValue, ok := searchKey(realitySetting, "shortIds"); ok {
  1043. shortIds, _ := sidValue.([]any)
  1044. params["sid"] = shortIds[random.Num(len(shortIds))].(string)
  1045. }
  1046. if fpValue, ok := searchKey(realitySettings, "fingerprint"); ok {
  1047. if fp, ok := fpValue.(string); ok && len(fp) > 0 {
  1048. params["fp"] = fp
  1049. }
  1050. }
  1051. if pqvValue, ok := searchKey(realitySettings, "mldsa65Verify"); ok {
  1052. if pqv, ok := pqvValue.(string); ok && len(pqv) > 0 {
  1053. params["pqv"] = pqv
  1054. }
  1055. }
  1056. params["spx"] = "/" + random.Seq(15)
  1057. }
  1058. }
  1059. func buildVmessLink(obj map[string]any) string {
  1060. jsonStr, _ := json.MarshalIndent(obj, "", " ")
  1061. return "vmess://" + base64.StdEncoding.EncodeToString(jsonStr)
  1062. }
  1063. func cloneVmessShareObj(baseObj map[string]any, newSecurity string) map[string]any {
  1064. newObj := map[string]any{}
  1065. for key, value := range baseObj {
  1066. if !(newSecurity == "none" && (key == "alpn" || key == "sni" || key == "fp" || key == "pcs")) {
  1067. newObj[key] = value
  1068. }
  1069. }
  1070. return newObj
  1071. }
  1072. func applyExternalProxyTLSObj(ep map[string]any, obj map[string]any, security string) {
  1073. if security != "tls" {
  1074. return
  1075. }
  1076. if sni, ok := externalProxySNI(ep); ok {
  1077. obj["sni"] = sni
  1078. }
  1079. if fp, ok := ep["fingerprint"].(string); ok && fp != "" {
  1080. obj["fp"] = fp
  1081. }
  1082. if alpn, ok := externalProxyALPN(ep["alpn"]); ok {
  1083. obj["alpn"] = alpn
  1084. }
  1085. if pins, ok := externalProxyPins(ep["pinnedPeerCertSha256"]); ok {
  1086. obj["pcs"] = joinAnyStrings(pins)
  1087. }
  1088. if ech, ok := ep["echConfigList"].(string); ok && ech != "" {
  1089. obj["ech"] = ech
  1090. }
  1091. }
  1092. func applyExternalProxyTLSParams(ep map[string]any, params map[string]string, security string) {
  1093. if security != "tls" {
  1094. return
  1095. }
  1096. if sni, ok := externalProxySNI(ep); ok {
  1097. params["sni"] = sni
  1098. }
  1099. if fp, ok := ep["fingerprint"].(string); ok && fp != "" {
  1100. params["fp"] = fp
  1101. }
  1102. if alpn, ok := externalProxyALPN(ep["alpn"]); ok {
  1103. params["alpn"] = alpn
  1104. }
  1105. if pins, ok := externalProxyPins(ep["pinnedPeerCertSha256"]); ok {
  1106. params["pcs"] = joinAnyStrings(pins)
  1107. }
  1108. if ech, ok := ep["echConfigList"].(string); ok && ech != "" {
  1109. params["ech"] = ech
  1110. }
  1111. }
  1112. // applyExternalProxyHysteriaParams overrides the cert pin for a single
  1113. // external-proxy entry on a Hysteria link. Hysteria carries the pin as a hex
  1114. // `pinSHA256` (not the `pcs` the URL-param protocols use), so each entry is
  1115. // coerced through hysteriaPinHex like the main pin. sni/fp/alpn are left as
  1116. // the inbound's own — Hysteria external proxies are typically alternate
  1117. // endpoints (port-hop / CDN) fronting the same certificate.
  1118. func applyExternalProxyHysteriaParams(ep map[string]any, params map[string]string) {
  1119. pins, ok := externalProxyPins(ep["pinnedPeerCertSha256"])
  1120. if !ok {
  1121. return
  1122. }
  1123. hexPins := make([]string, 0, len(pins))
  1124. for _, p := range pins {
  1125. if s, ok := p.(string); ok {
  1126. hexPins = append(hexPins, hysteriaPinHex(s))
  1127. }
  1128. }
  1129. params["pinSHA256"] = strings.Join(hexPins, ",")
  1130. }
  1131. // cloneStreamForExternalProxy returns a shallow clone of stream with
  1132. // tlsSettings (and its nested settings map) deep-copied. The external
  1133. // proxy loop mutates tlsSettings per iteration, so without isolating
  1134. // those maps each proxy's SNI/fingerprint/ALPN would leak into the next.
  1135. func cloneStreamForExternalProxy(stream map[string]any) map[string]any {
  1136. out := cloneMap(stream)
  1137. ts, ok := out["tlsSettings"].(map[string]any)
  1138. if !ok || ts == nil {
  1139. return out
  1140. }
  1141. clonedTs := cloneMap(ts)
  1142. if inner, ok := clonedTs["settings"].(map[string]any); ok && inner != nil {
  1143. clonedTs["settings"] = cloneMap(inner)
  1144. }
  1145. out["tlsSettings"] = clonedTs
  1146. return out
  1147. }
  1148. func applyExternalProxyTLSToStream(ep map[string]any, stream map[string]any, security string) {
  1149. if security != "tls" {
  1150. return
  1151. }
  1152. tlsSettings, _ := stream["tlsSettings"].(map[string]any)
  1153. if tlsSettings == nil {
  1154. tlsSettings = map[string]any{}
  1155. stream["tlsSettings"] = tlsSettings
  1156. }
  1157. if sni, ok := externalProxySNI(ep); ok {
  1158. tlsSettings["serverName"] = sni
  1159. }
  1160. if fp, ok := ep["fingerprint"].(string); ok && fp != "" {
  1161. tlsSettings["fingerprint"] = fp
  1162. settings, _ := tlsSettings["settings"].(map[string]any)
  1163. if settings == nil {
  1164. settings = map[string]any{}
  1165. tlsSettings["settings"] = settings
  1166. }
  1167. settings["fingerprint"] = fp
  1168. }
  1169. if alpn, ok := externalProxyALPNList(ep["alpn"]); ok {
  1170. tlsSettings["alpn"] = alpn
  1171. }
  1172. if pins, ok := externalProxyPins(ep["pinnedPeerCertSha256"]); ok {
  1173. settings, _ := tlsSettings["settings"].(map[string]any)
  1174. if settings == nil {
  1175. settings = map[string]any{}
  1176. tlsSettings["settings"] = settings
  1177. }
  1178. settings["pinnedPeerCertSha256"] = pins
  1179. }
  1180. if ech, ok := ep["echConfigList"].(string); ok && ech != "" {
  1181. settings, _ := tlsSettings["settings"].(map[string]any)
  1182. if settings == nil {
  1183. settings = map[string]any{}
  1184. tlsSettings["settings"] = settings
  1185. }
  1186. settings["echConfigList"] = ech
  1187. }
  1188. }
  1189. func externalProxySNI(ep map[string]any) (string, bool) {
  1190. if sni, ok := ep["sni"].(string); ok && sni != "" {
  1191. return sni, true
  1192. }
  1193. return "", false
  1194. }
  1195. func externalProxyALPN(value any) (string, bool) {
  1196. switch v := value.(type) {
  1197. case string:
  1198. return v, v != ""
  1199. case []string:
  1200. if len(v) == 0 {
  1201. return "", false
  1202. }
  1203. return strings.Join(v, ","), true
  1204. case []any:
  1205. alpn := make([]string, 0, len(v))
  1206. for _, item := range v {
  1207. if s, ok := item.(string); ok && s != "" {
  1208. alpn = append(alpn, s)
  1209. }
  1210. }
  1211. if len(alpn) == 0 {
  1212. return "", false
  1213. }
  1214. return strings.Join(alpn, ","), true
  1215. default:
  1216. return "", false
  1217. }
  1218. }
  1219. func externalProxyALPNList(value any) ([]any, bool) {
  1220. switch v := value.(type) {
  1221. case string:
  1222. if v == "" {
  1223. return nil, false
  1224. }
  1225. parts := strings.Split(v, ",")
  1226. out := make([]any, 0, len(parts))
  1227. for _, part := range parts {
  1228. if part = strings.TrimSpace(part); part != "" {
  1229. out = append(out, part)
  1230. }
  1231. }
  1232. return out, len(out) > 0
  1233. case []string:
  1234. out := make([]any, 0, len(v))
  1235. for _, item := range v {
  1236. if item != "" {
  1237. out = append(out, item)
  1238. }
  1239. }
  1240. return out, len(out) > 0
  1241. case []any:
  1242. out := make([]any, 0, len(v))
  1243. for _, item := range v {
  1244. if s, ok := item.(string); ok && s != "" {
  1245. out = append(out, s)
  1246. }
  1247. }
  1248. return out, len(out) > 0
  1249. default:
  1250. return nil, false
  1251. }
  1252. }
  1253. // externalProxyPins extracts an external-proxy entry's pinnedPeerCertSha256
  1254. // as a []any of non-empty strings. The []any element type matches what the
  1255. // JSON/Clash sub builders expect when reading the value back off the cloned
  1256. // stream's tlsSettings.settings.
  1257. func externalProxyPins(value any) ([]any, bool) {
  1258. switch v := value.(type) {
  1259. case []string:
  1260. out := make([]any, 0, len(v))
  1261. for _, item := range v {
  1262. if item != "" {
  1263. out = append(out, item)
  1264. }
  1265. }
  1266. return out, len(out) > 0
  1267. case []any:
  1268. out := make([]any, 0, len(v))
  1269. for _, item := range v {
  1270. if s, ok := item.(string); ok && s != "" {
  1271. out = append(out, s)
  1272. }
  1273. }
  1274. return out, len(out) > 0
  1275. default:
  1276. return nil, false
  1277. }
  1278. }
  1279. func joinAnyStrings(items []any) string {
  1280. parts := make([]string, 0, len(items))
  1281. for _, item := range items {
  1282. if s, ok := item.(string); ok {
  1283. parts = append(parts, s)
  1284. }
  1285. }
  1286. return strings.Join(parts, ",")
  1287. }
  1288. func (s *SubService) buildVmessExternalProxyLinks(externalProxies []any, baseObj map[string]any, inbound *model.Inbound, email string) string {
  1289. var links strings.Builder
  1290. for index, externalProxy := range externalProxies {
  1291. ep, _ := externalProxy.(map[string]any)
  1292. newSecurity, _ := ep["forceTls"].(string)
  1293. securityToApply := baseObj["tls"].(string)
  1294. if newSecurity != "same" {
  1295. securityToApply = newSecurity
  1296. }
  1297. newObj := cloneVmessShareObj(baseObj, newSecurity)
  1298. newObj["ps"] = s.genRemark(inbound, email, ep["remark"].(string))
  1299. newObj["add"] = ep["dest"].(string)
  1300. newObj["port"] = int(ep["port"].(float64))
  1301. if newSecurity != "same" {
  1302. newObj["tls"] = newSecurity
  1303. }
  1304. applyExternalProxyTLSObj(ep, newObj, securityToApply)
  1305. if index > 0 {
  1306. links.WriteString("\n")
  1307. }
  1308. links.WriteString(buildVmessLink(newObj))
  1309. }
  1310. return links.String()
  1311. }
  1312. // buildLinkWithParams appends ?query and #fragment to a pre-built
  1313. // scheme://userinfo@host:port string without re-parsing it. The caller
  1314. // has already escaped userinfo via encodeUserinfo (or chosen a base64
  1315. // alphabet with no reserved chars); a url.Parse + .String() round-trip
  1316. // would silently decode that escaping because Go's userinfo emitter
  1317. // leaves sub-delims (=, +, ;) literal, which breaks Trojan/Hysteria/SS
  1318. // clients that reject those chars in the password.
  1319. func buildLinkWithParams(link string, params map[string]string, fragment string) string {
  1320. return appendQueryAndFragment(link, params, fragment, "", false)
  1321. }
  1322. // buildLinkWithParamsAndSecurity is buildLinkWithParams plus an
  1323. // external-proxy override: the `security` key in params is replaced with
  1324. // the supplied value, and TLS hint fields (alpn/sni/fp/pcs) are stripped
  1325. // when the override is `none`.
  1326. func buildLinkWithParamsAndSecurity(link string, params map[string]string, fragment, security string, omitTLSFields bool) string {
  1327. return appendQueryAndFragment(link, params, fragment, security, omitTLSFields)
  1328. }
  1329. func appendQueryAndFragment(link string, params map[string]string, fragment, securityOverride string, omitTLSFields bool) string {
  1330. var sb strings.Builder
  1331. sb.WriteString(link)
  1332. if len(params) > 0 {
  1333. q := url.Values{}
  1334. for k, v := range params {
  1335. if securityOverride != "" && k == "security" {
  1336. v = securityOverride
  1337. }
  1338. if omitTLSFields && (k == "alpn" || k == "sni" || k == "fp" || k == "pcs") {
  1339. continue
  1340. }
  1341. q.Set(k, v)
  1342. }
  1343. encoded := q.Encode()
  1344. if encoded != "" {
  1345. if strings.Contains(link, "?") {
  1346. sb.WriteByte('&')
  1347. } else {
  1348. sb.WriteByte('?')
  1349. }
  1350. sb.WriteString(encoded)
  1351. }
  1352. }
  1353. if fragment != "" {
  1354. sb.WriteByte('#')
  1355. // Match the frontend's encodeURIComponent(remark): spaces become
  1356. // %20 (not + as in query strings).
  1357. sb.WriteString(strings.ReplaceAll(url.QueryEscape(fragment), "+", "%20"))
  1358. }
  1359. return sb.String()
  1360. }
  1361. func (s *SubService) buildExternalProxyURLLinks(
  1362. externalProxies []any,
  1363. params map[string]string,
  1364. baseSecurity string,
  1365. makeLink func(dest string, port int) string,
  1366. makeRemark func(ep map[string]any) string,
  1367. ) string {
  1368. links := make([]string, 0, len(externalProxies))
  1369. for _, externalProxy := range externalProxies {
  1370. ep, _ := externalProxy.(map[string]any)
  1371. newSecurity, _ := ep["forceTls"].(string)
  1372. dest, _ := ep["dest"].(string)
  1373. port := int(ep["port"].(float64))
  1374. securityToApply := baseSecurity
  1375. if newSecurity != "same" {
  1376. securityToApply = newSecurity
  1377. }
  1378. nextParams := cloneStringMap(params)
  1379. applyExternalProxyTLSParams(ep, nextParams, securityToApply)
  1380. links = append(
  1381. links,
  1382. buildLinkWithParamsAndSecurity(
  1383. makeLink(dest, port),
  1384. nextParams,
  1385. makeRemark(ep),
  1386. securityToApply,
  1387. newSecurity == "none",
  1388. ),
  1389. )
  1390. }
  1391. return strings.Join(links, "\n")
  1392. }
  1393. func cloneStringMap(source map[string]string) map[string]string {
  1394. cloned := make(map[string]string, len(source))
  1395. maps.Copy(cloned, source)
  1396. return cloned
  1397. }
  1398. func (s *SubService) genRemark(inbound *model.Inbound, email string, extra string) string {
  1399. separationChar := string(s.remarkModel[0])
  1400. orderChars := s.remarkModel[1:]
  1401. orders := map[byte]string{
  1402. 'i': "",
  1403. 'e': "",
  1404. 'o': "",
  1405. }
  1406. if len(email) > 0 && s.emailInRemark {
  1407. orders['e'] = email
  1408. }
  1409. if len(inbound.Remark) > 0 {
  1410. orders['i'] = inbound.Remark
  1411. }
  1412. if len(extra) > 0 {
  1413. orders['o'] = extra
  1414. }
  1415. var remark []string
  1416. for i := 0; i < len(orderChars); i++ {
  1417. char := orderChars[i]
  1418. order, exists := orders[char]
  1419. if exists && order != "" {
  1420. remark = append(remark, order)
  1421. }
  1422. }
  1423. if s.showInfo {
  1424. statsExist := false
  1425. var stats xray.ClientTraffic
  1426. for _, clientStat := range inbound.ClientStats {
  1427. if clientStat.Email == email {
  1428. stats = clientStat
  1429. statsExist = true
  1430. break
  1431. }
  1432. }
  1433. // Get remained days
  1434. if statsExist {
  1435. if !stats.Enable {
  1436. return fmt.Sprintf("⛔️N/A%s%s", separationChar, strings.Join(remark, separationChar))
  1437. }
  1438. if vol := stats.Total - (stats.Up + stats.Down); vol > 0 {
  1439. remark = append(remark, fmt.Sprintf("%s%s", common.FormatTraffic(vol), "📊"))
  1440. }
  1441. now := time.Now().Unix()
  1442. switch exp := stats.ExpiryTime / 1000; {
  1443. case exp > 0:
  1444. remainingSeconds := exp - now
  1445. days := remainingSeconds / 86400
  1446. hours := (remainingSeconds % 86400) / 3600
  1447. minutes := (remainingSeconds % 3600) / 60
  1448. if days > 0 {
  1449. if hours > 0 {
  1450. remark = append(remark, fmt.Sprintf("%dD,%dH⏳", days, hours))
  1451. } else {
  1452. remark = append(remark, fmt.Sprintf("%dD⏳", days))
  1453. }
  1454. } else if hours > 0 {
  1455. remark = append(remark, fmt.Sprintf("%dH⏳", hours))
  1456. } else {
  1457. remark = append(remark, fmt.Sprintf("%dM⏳", minutes))
  1458. }
  1459. case exp < 0:
  1460. days := exp / -86400
  1461. hours := (exp % -86400) / 3600
  1462. minutes := (exp % -3600) / 60
  1463. if days > 0 {
  1464. if hours > 0 {
  1465. remark = append(remark, fmt.Sprintf("%dD,%dH⏳", days, hours))
  1466. } else {
  1467. remark = append(remark, fmt.Sprintf("%dD⏳", days))
  1468. }
  1469. } else if hours > 0 {
  1470. remark = append(remark, fmt.Sprintf("%dH⏳", hours))
  1471. } else {
  1472. remark = append(remark, fmt.Sprintf("%dM⏳", minutes))
  1473. }
  1474. }
  1475. }
  1476. }
  1477. return strings.Join(remark, separationChar)
  1478. }
  1479. func searchKey(data any, key string) (any, bool) {
  1480. switch val := data.(type) {
  1481. case map[string]any:
  1482. for k, v := range val {
  1483. if k == key {
  1484. return v, true
  1485. }
  1486. if result, ok := searchKey(v, key); ok {
  1487. return result, true
  1488. }
  1489. }
  1490. case []any:
  1491. for _, v := range val {
  1492. if result, ok := searchKey(v, key); ok {
  1493. return result, true
  1494. }
  1495. }
  1496. }
  1497. return nil, false
  1498. }
  1499. // buildXhttpExtra walks an xhttpSettings map and returns the JSON blob
  1500. // that goes into the URL's `extra` param (or, for VMess, the link
  1501. // object). Carries ONLY the bidirectional fields from xray-core's
  1502. // SplitHTTPConfig — i.e. the ones the server enforces and the client
  1503. // must match. Strictly one-sided fields are excluded:
  1504. //
  1505. // - server-only (noSSEHeader, scMaxBufferedPosts, scStreamUpServerSecs,
  1506. // serverMaxHeaderBytes) — client wouldn't read them, so emitting
  1507. // them just bloats the URL.
  1508. // - client-only values are included only when present in the inbound
  1509. // JSON. Some deployments/imported configs carry them there, and the
  1510. // subscription link is the only place clients can receive them.
  1511. //
  1512. // Truthy-only guards keep default inbounds emitting the same compact URL
  1513. // they did before this helper grew.
  1514. func buildXhttpExtra(xhttp map[string]any) map[string]any {
  1515. if xhttp == nil {
  1516. return nil
  1517. }
  1518. extra := map[string]any{}
  1519. if xpb, ok := xhttp["xPaddingBytes"].(string); ok && len(xpb) > 0 {
  1520. extra["xPaddingBytes"] = xpb
  1521. }
  1522. if obfs, ok := xhttp["xPaddingObfsMode"].(bool); ok && obfs {
  1523. extra["xPaddingObfsMode"] = true
  1524. for _, field := range []string{"xPaddingKey", "xPaddingHeader", "xPaddingPlacement", "xPaddingMethod"} {
  1525. if v, ok := xhttp[field].(string); ok && len(v) > 0 {
  1526. extra[field] = v
  1527. }
  1528. }
  1529. }
  1530. stringFields := []string{
  1531. "uplinkHTTPMethod",
  1532. "sessionPlacement", "sessionKey",
  1533. "seqPlacement", "seqKey",
  1534. "uplinkDataPlacement", "uplinkDataKey",
  1535. "scMaxEachPostBytes", "scMinPostsIntervalMs",
  1536. }
  1537. for _, field := range stringFields {
  1538. if v, ok := xhttp[field].(string); ok && len(v) > 0 {
  1539. extra[field] = v
  1540. }
  1541. }
  1542. for _, field := range []string{"uplinkChunkSize"} {
  1543. if v, ok := nonZeroShareValue(xhttp[field]); ok {
  1544. extra[field] = v
  1545. }
  1546. }
  1547. for _, field := range []string{"noGRPCHeader"} {
  1548. if v, ok := xhttp[field].(bool); ok && v {
  1549. extra[field] = v
  1550. }
  1551. }
  1552. for _, field := range []string{"xmux", "downloadSettings"} {
  1553. if v, ok := nonEmptyShareObject(xhttp[field]); ok {
  1554. extra[field] = v
  1555. }
  1556. }
  1557. // Headers — emitted as the {name: value} map upstream's struct
  1558. // expects. The server runtime ignores this field, but the client
  1559. // (consuming the share link) honors it. Drop any "host" entry —
  1560. // host already wins as a top-level URL param.
  1561. if rawHeaders, ok := xhttp["headers"].(map[string]any); ok && len(rawHeaders) > 0 {
  1562. out := map[string]any{}
  1563. for k, v := range rawHeaders {
  1564. if strings.EqualFold(k, "host") {
  1565. continue
  1566. }
  1567. out[k] = v
  1568. }
  1569. if len(out) > 0 {
  1570. extra["headers"] = out
  1571. }
  1572. }
  1573. if len(extra) == 0 {
  1574. return nil
  1575. }
  1576. return extra
  1577. }
  1578. func nonZeroShareValue(v any) (any, bool) {
  1579. switch value := v.(type) {
  1580. case string:
  1581. return value, value != ""
  1582. case int:
  1583. return value, value != 0
  1584. case int32:
  1585. return value, value != 0
  1586. case int64:
  1587. return value, value != 0
  1588. case float32:
  1589. return value, value != 0
  1590. case float64:
  1591. return value, value != 0
  1592. default:
  1593. return nil, false
  1594. }
  1595. }
  1596. func nonEmptyShareObject(v any) (any, bool) {
  1597. switch value := v.(type) {
  1598. case map[string]any:
  1599. return value, len(value) > 0
  1600. case map[string]string:
  1601. return value, len(value) > 0
  1602. case []any:
  1603. return value, len(value) > 0
  1604. default:
  1605. return nil, false
  1606. }
  1607. }
  1608. // applyXhttpExtraParams emits the full xhttp config into the URL query
  1609. // params of a vless:// / trojan:// / ss:// link. Sets path/host/mode at
  1610. // top level (xray's Build() always lets these win over `extra`) and packs
  1611. // everything else into a JSON `extra` param. Also writes the flat
  1612. // `x_padding_bytes` param sing-box-family clients understand.
  1613. //
  1614. // Without this, the admin's custom xPaddingBytes / sessionKey / etc. never
  1615. // reach the client and handshakes are silently rejected with
  1616. // `invalid padding (...) length: 0` — the client-visible symptom is
  1617. // "xhttp doesn't connect" on OpenWRT / sing-box.
  1618. //
  1619. // Two encodings are written so every popular client can read at least one:
  1620. //
  1621. // - x_padding_bytes=<range> — flat param, understood by sing-box and its
  1622. // derivatives (Podkop, OpenWRT sing-box, Karing, NekoBox, …).
  1623. // - extra=<url-encoded-json> — full xhttp settings blob, which is how
  1624. // xray-core clients (v2rayNG, Happ, Furious, Exclave, …) pick up the
  1625. // bidirectional fields beyond path/host/mode.
  1626. func applyXhttpExtraParams(xhttp map[string]any, params map[string]string) {
  1627. if xhttp == nil {
  1628. return
  1629. }
  1630. applyPathAndHostParams(xhttp, params)
  1631. if mode, ok := xhttp["mode"].(string); ok {
  1632. params["mode"] = mode
  1633. }
  1634. if xpb, ok := xhttp["xPaddingBytes"].(string); ok && len(xpb) > 0 {
  1635. params["x_padding_bytes"] = xpb
  1636. }
  1637. extra := buildXhttpExtra(xhttp)
  1638. if extra != nil {
  1639. if b, err := json.Marshal(extra); err == nil {
  1640. params["extra"] = string(b)
  1641. }
  1642. }
  1643. }
  1644. var kcpMaskToHeaderType = map[string]string{
  1645. "dns": "dns",
  1646. "dtls": "dtls",
  1647. "srtp": "srtp",
  1648. "utp": "utp",
  1649. "wechat": "wechat-video",
  1650. "wireguard": "wireguard",
  1651. }
  1652. var validFinalMaskUDPTypes = map[string]struct{}{
  1653. "salamander": {},
  1654. "mkcp-legacy": {},
  1655. "xdns": {},
  1656. "xicmp": {},
  1657. "noise": {},
  1658. "header-custom": {},
  1659. "realm": {},
  1660. }
  1661. var validFinalMaskTCPTypes = map[string]struct{}{
  1662. "header-custom": {},
  1663. "fragment": {},
  1664. "sudoku": {},
  1665. }
  1666. // applyKcpShareParams reconstructs legacy KCP share-link fields from either
  1667. // the historical kcpSettings.header/seed shape or the current finalmask model.
  1668. // This keeps subscription output compatible while avoiding panics when older
  1669. // keys are absent from modern inbounds.
  1670. func applyKcpShareParams(stream map[string]any, params map[string]string) {
  1671. extractKcpShareFields(stream).applyToParams(params)
  1672. }
  1673. func applyKcpShareObj(stream map[string]any, obj map[string]any) {
  1674. extractKcpShareFields(stream).applyToObj(obj)
  1675. }
  1676. type kcpShareFields struct {
  1677. headerType string
  1678. seed string
  1679. mtu int
  1680. tti int
  1681. }
  1682. func (f kcpShareFields) applyToParams(params map[string]string) {
  1683. if f.headerType != "" && f.headerType != "none" {
  1684. params["headerType"] = f.headerType
  1685. }
  1686. setStringParam(params, "seed", f.seed)
  1687. setIntParam(params, "mtu", f.mtu)
  1688. setIntParam(params, "tti", f.tti)
  1689. }
  1690. func (f kcpShareFields) applyToObj(obj map[string]any) {
  1691. if f.headerType != "" && f.headerType != "none" {
  1692. obj["type"] = f.headerType
  1693. }
  1694. setStringField(obj, "path", f.seed)
  1695. setIntField(obj, "mtu", f.mtu)
  1696. setIntField(obj, "tti", f.tti)
  1697. }
  1698. func extractKcpShareFields(stream map[string]any) kcpShareFields {
  1699. fields := kcpShareFields{headerType: "none"}
  1700. if kcp, ok := stream["kcpSettings"].(map[string]any); ok {
  1701. if header, ok := kcp["header"].(map[string]any); ok {
  1702. if value, ok := header["type"].(string); ok && value != "" {
  1703. fields.headerType = value
  1704. }
  1705. }
  1706. if value, ok := kcp["seed"].(string); ok && value != "" {
  1707. fields.seed = value
  1708. }
  1709. if value, ok := readPositiveInt(kcp["mtu"]); ok {
  1710. fields.mtu = value
  1711. }
  1712. if value, ok := readPositiveInt(kcp["tti"]); ok {
  1713. fields.tti = value
  1714. }
  1715. }
  1716. for _, rawMask := range normalizedFinalMaskUDPMasks(stream["finalmask"]) {
  1717. mask, _ := rawMask.(map[string]any)
  1718. if mask == nil {
  1719. continue
  1720. }
  1721. if maskType, _ := mask["type"].(string); maskType != "mkcp-legacy" {
  1722. continue
  1723. }
  1724. settings, _ := mask["settings"].(map[string]any)
  1725. header, _ := settings["header"].(string)
  1726. value, _ := settings["value"].(string)
  1727. if header == "" {
  1728. fields.seed = value
  1729. continue
  1730. }
  1731. if mapped, ok := kcpMaskToHeaderType[header]; ok {
  1732. fields.headerType = mapped
  1733. }
  1734. }
  1735. return fields
  1736. }
  1737. func readPositiveInt(value any) (int, bool) {
  1738. switch number := value.(type) {
  1739. case int:
  1740. return number, number > 0
  1741. case int32:
  1742. return int(number), number > 0
  1743. case int64:
  1744. return int(number), number > 0
  1745. case float32:
  1746. parsed := int(number)
  1747. return parsed, parsed > 0
  1748. case float64:
  1749. parsed := int(number)
  1750. return parsed, parsed > 0
  1751. default:
  1752. return 0, false
  1753. }
  1754. }
  1755. func setStringParam(params map[string]string, key, value string) {
  1756. if value == "" {
  1757. delete(params, key)
  1758. return
  1759. }
  1760. params[key] = value
  1761. }
  1762. func setIntParam(params map[string]string, key string, value int) {
  1763. if value <= 0 {
  1764. delete(params, key)
  1765. return
  1766. }
  1767. params[key] = fmt.Sprintf("%d", value)
  1768. }
  1769. func setStringField(obj map[string]any, key, value string) {
  1770. if value == "" {
  1771. delete(obj, key)
  1772. return
  1773. }
  1774. obj[key] = value
  1775. }
  1776. func setIntField(obj map[string]any, key string, value int) {
  1777. if value <= 0 {
  1778. delete(obj, key)
  1779. return
  1780. }
  1781. obj[key] = value
  1782. }
  1783. // applyFinalMaskParams exports the finalmask payload as the compact
  1784. // `fm=<json>` share-link field used by v2rayN-compatible clients.
  1785. func applyFinalMaskParams(finalmask map[string]any, params map[string]string) {
  1786. if fm, ok := marshalFinalMask(finalmask); ok {
  1787. params["fm"] = fm
  1788. }
  1789. }
  1790. func applyFinalMaskObj(finalmask map[string]any, obj map[string]any) {
  1791. if fm, ok := marshalFinalMask(finalmask); ok {
  1792. obj["fm"] = fm
  1793. }
  1794. }
  1795. func marshalFinalMask(finalmask map[string]any) (string, bool) {
  1796. normalized := normalizeFinalMask(finalmask)
  1797. if !hasFinalMaskContent(normalized) {
  1798. return "", false
  1799. }
  1800. b, err := json.Marshal(normalized)
  1801. if err != nil || len(b) == 0 || string(b) == "null" {
  1802. return "", false
  1803. }
  1804. return string(b), true
  1805. }
  1806. func normalizeFinalMask(finalmask map[string]any) map[string]any {
  1807. tcpMasks := normalizedFinalMaskTCPMasks(finalmask)
  1808. udpMasks := normalizedFinalMaskUDPMasks(finalmask)
  1809. quicParams, hasQuicParams := finalmask["quicParams"].(map[string]any)
  1810. if len(tcpMasks) == 0 && len(udpMasks) == 0 && !hasQuicParams {
  1811. return nil
  1812. }
  1813. result := map[string]any{}
  1814. if len(tcpMasks) > 0 {
  1815. result["tcp"] = tcpMasks
  1816. }
  1817. if len(udpMasks) > 0 {
  1818. result["udp"] = udpMasks
  1819. }
  1820. if hasQuicParams && len(quicParams) > 0 {
  1821. result["quicParams"] = quicParams
  1822. }
  1823. return result
  1824. }
  1825. func normalizedFinalMaskTCPMasks(value any) []any {
  1826. finalmask, _ := value.(map[string]any)
  1827. if finalmask == nil {
  1828. return nil
  1829. }
  1830. rawMasks, _ := finalmask["tcp"].([]any)
  1831. if len(rawMasks) == 0 {
  1832. return nil
  1833. }
  1834. normalized := make([]any, 0, len(rawMasks))
  1835. for _, rawMask := range rawMasks {
  1836. mask, _ := rawMask.(map[string]any)
  1837. if mask == nil {
  1838. continue
  1839. }
  1840. maskType, _ := mask["type"].(string)
  1841. if _, ok := validFinalMaskTCPTypes[maskType]; !ok || maskType == "" {
  1842. continue
  1843. }
  1844. normalizedMask := map[string]any{"type": maskType}
  1845. if settings, ok := mask["settings"].(map[string]any); ok && len(settings) > 0 {
  1846. normalizedMask["settings"] = settings
  1847. }
  1848. normalized = append(normalized, normalizedMask)
  1849. }
  1850. if len(normalized) == 0 {
  1851. return nil
  1852. }
  1853. return normalized
  1854. }
  1855. func normalizedFinalMaskUDPMasks(value any) []any {
  1856. finalmask, _ := value.(map[string]any)
  1857. if finalmask == nil {
  1858. return nil
  1859. }
  1860. rawMasks, _ := finalmask["udp"].([]any)
  1861. if len(rawMasks) == 0 {
  1862. return nil
  1863. }
  1864. normalized := make([]any, 0, len(rawMasks))
  1865. for _, rawMask := range rawMasks {
  1866. mask, _ := rawMask.(map[string]any)
  1867. if mask == nil {
  1868. continue
  1869. }
  1870. maskType, _ := mask["type"].(string)
  1871. if _, ok := validFinalMaskUDPTypes[maskType]; !ok || maskType == "" {
  1872. continue
  1873. }
  1874. normalizedMask := map[string]any{"type": maskType}
  1875. if settings, ok := mask["settings"].(map[string]any); ok && len(settings) > 0 {
  1876. normalizedMask["settings"] = settings
  1877. }
  1878. normalized = append(normalized, normalizedMask)
  1879. }
  1880. if len(normalized) == 0 {
  1881. return nil
  1882. }
  1883. return normalized
  1884. }
  1885. func hasFinalMaskContent(value any) bool {
  1886. switch v := value.(type) {
  1887. case nil:
  1888. return false
  1889. case string:
  1890. return len(v) > 0
  1891. case map[string]any:
  1892. for _, item := range v {
  1893. if hasFinalMaskContent(item) {
  1894. return true
  1895. }
  1896. }
  1897. return false
  1898. case []any:
  1899. return slices.ContainsFunc(v, hasFinalMaskContent)
  1900. default:
  1901. return true
  1902. }
  1903. }
  1904. func searchHost(headers any) string {
  1905. data, _ := headers.(map[string]any)
  1906. for k, v := range data {
  1907. if strings.EqualFold(k, "host") {
  1908. switch v.(type) {
  1909. case []any:
  1910. hosts, _ := v.([]any)
  1911. if len(hosts) > 0 {
  1912. return hosts[0].(string)
  1913. } else {
  1914. return ""
  1915. }
  1916. case any:
  1917. return v.(string)
  1918. }
  1919. }
  1920. }
  1921. return ""
  1922. }
  1923. // PageData is a view model for subpage.html
  1924. // PageData contains data for rendering the subscription information page.
  1925. type PageData struct {
  1926. Host string
  1927. BasePath string
  1928. SId string
  1929. Enabled bool
  1930. Download string
  1931. Upload string
  1932. Total string
  1933. Used string
  1934. Remained string
  1935. Expire int64
  1936. LastOnline int64
  1937. Datepicker string
  1938. DownloadByte int64
  1939. UploadByte int64
  1940. TotalByte int64
  1941. SubUrl string
  1942. SubJsonUrl string
  1943. SubClashUrl string
  1944. SubTitle string
  1945. SubSupportUrl string
  1946. Result []string
  1947. Emails []string
  1948. }
  1949. // ResolveRequest extracts scheme and host info from request/headers consistently.
  1950. // ResolveRequest extracts scheme, host, and header information from an HTTP request.
  1951. func (s *SubService) ResolveRequest(c *gin.Context) (scheme string, host string, hostWithPort string, hostHeader string) {
  1952. // scheme
  1953. scheme = "http"
  1954. if c.Request.TLS != nil || strings.EqualFold(c.GetHeader("X-Forwarded-Proto"), "https") {
  1955. scheme = "https"
  1956. }
  1957. // base host (no port)
  1958. if h, err := getHostFromXFH(c.GetHeader("X-Forwarded-Host")); err == nil && h != "" {
  1959. host = h
  1960. }
  1961. if host == "" {
  1962. host = c.GetHeader("X-Real-IP")
  1963. }
  1964. if host == "" {
  1965. var err error
  1966. host, _, err = net.SplitHostPort(c.Request.Host)
  1967. if err != nil {
  1968. host = c.Request.Host
  1969. }
  1970. }
  1971. // host:port for URLs
  1972. hostWithPort = c.GetHeader("X-Forwarded-Host")
  1973. if hostWithPort == "" {
  1974. hostWithPort = c.Request.Host
  1975. }
  1976. if hostWithPort == "" {
  1977. hostWithPort = host
  1978. }
  1979. // header display host
  1980. hostHeader = c.GetHeader("X-Forwarded-Host")
  1981. if hostHeader == "" {
  1982. hostHeader = c.GetHeader("X-Real-IP")
  1983. }
  1984. if hostHeader == "" {
  1985. hostHeader = host
  1986. }
  1987. return
  1988. }
  1989. // BuildURLs constructs absolute subscription and JSON subscription URLs for a given subscription ID.
  1990. // It prioritizes configured URIs, then individual settings, and finally falls back to request-derived components.
  1991. func (s *SubService) BuildURLs(subPath, subJsonPath, subClashPath, subId string) (subURL, subJsonURL, subClashURL string) {
  1992. if subId == "" {
  1993. return "", "", ""
  1994. }
  1995. configuredSubURI, _ := s.settingService.GetSubURI()
  1996. configuredSubJsonURI, _ := s.settingService.GetSubJsonURI()
  1997. configuredSubClashURI, _ := s.settingService.GetSubClashURI()
  1998. // Same base as the panel's Client Information page; s.address is the
  1999. // subscriber's host already normalized away from any loopback/bind IP.
  2000. base := s.settingService.BuildSubURIBase(s.address)
  2001. subURL = s.buildSingleURL(configuredSubURI, base, subPath, subId)
  2002. // When subURI is explicitly configured (reverse-proxy setup), use its
  2003. // scheme+host as the base for JSON and Clash URLs so they match the
  2004. // reverse-proxy endpoint instead of the raw sub-server port. Fall back
  2005. // to the request-derived base if subURI is empty or can't be parsed
  2006. // into a scheme+host (e.g. a malformed value with no scheme).
  2007. jsonClashBase := base
  2008. if configuredSubURI != "" {
  2009. if derived := s.extractBaseFromURI(configuredSubURI); derived != "" {
  2010. jsonClashBase = derived
  2011. }
  2012. }
  2013. subJsonURL = s.buildSingleURL(configuredSubJsonURI, jsonClashBase, subJsonPath, subId)
  2014. subClashURL = s.buildSingleURL(configuredSubClashURI, jsonClashBase, subClashPath, subId)
  2015. return subURL, subJsonURL, subClashURL
  2016. }
  2017. // extractBaseFromURI extracts scheme://host from a configured URI.
  2018. // e.g., "https://example.com/sub-xxx/" → "https://example.com".
  2019. // Returns "" when the URI is empty or lacks a scheme/host, so callers can
  2020. // fall back to the request-derived base instead of emitting a broken value.
  2021. func (s *SubService) extractBaseFromURI(uri string) string {
  2022. u, err := url.Parse(uri)
  2023. if err != nil || u.Scheme == "" || u.Host == "" {
  2024. return ""
  2025. }
  2026. return fmt.Sprintf("%s://%s", u.Scheme, u.Host)
  2027. }
  2028. // buildSingleURL constructs a single URL using configured URI or base components
  2029. func (s *SubService) buildSingleURL(configuredURI, base, basePath, subId string) string {
  2030. if configuredURI != "" {
  2031. return s.joinPathWithID(configuredURI, subId)
  2032. }
  2033. return s.joinPathWithID(base+basePath, subId)
  2034. }
  2035. // joinPathWithID safely joins a base path with a subscription ID
  2036. func (s *SubService) joinPathWithID(basePath, subId string) string {
  2037. if strings.HasSuffix(basePath, "/") {
  2038. return basePath + subId
  2039. }
  2040. return basePath + "/" + subId
  2041. }
  2042. // BuildPageData parses header and prepares the template view model.
  2043. // BuildPageData constructs page data for rendering the subscription information page.
  2044. 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 {
  2045. download := common.FormatTraffic(traffic.Down)
  2046. upload := common.FormatTraffic(traffic.Up)
  2047. total := "∞"
  2048. used := common.FormatTraffic(traffic.Up + traffic.Down)
  2049. remained := ""
  2050. if traffic.Total > 0 {
  2051. total = common.FormatTraffic(traffic.Total)
  2052. left := max(traffic.Total-(traffic.Up+traffic.Down), 0)
  2053. remained = common.FormatTraffic(left)
  2054. }
  2055. datepicker := s.datepicker
  2056. if datepicker == "" {
  2057. datepicker = "gregorian"
  2058. }
  2059. return PageData{
  2060. Host: hostHeader,
  2061. BasePath: basePath,
  2062. SId: subId,
  2063. Enabled: traffic.Enable,
  2064. Download: download,
  2065. Upload: upload,
  2066. Total: total,
  2067. Used: used,
  2068. Remained: remained,
  2069. Expire: traffic.ExpiryTime / 1000,
  2070. LastOnline: lastOnline,
  2071. Datepicker: datepicker,
  2072. DownloadByte: traffic.Down,
  2073. UploadByte: traffic.Up,
  2074. TotalByte: traffic.Total,
  2075. SubUrl: subURL,
  2076. SubJsonUrl: subJsonURL,
  2077. SubClashUrl: subClashURL,
  2078. SubTitle: subTitle,
  2079. SubSupportUrl: subSupportUrl,
  2080. Result: subs,
  2081. Emails: emails,
  2082. }
  2083. }
  2084. func getHostFromXFH(s string) (string, error) {
  2085. if strings.Contains(s, ":") {
  2086. realHost, _, err := net.SplitHostPort(s)
  2087. if err != nil {
  2088. return "", err
  2089. }
  2090. return realHost, nil
  2091. }
  2092. return s, nil
  2093. }