1
0

subService.go 63 KB

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