1
0

subService.go 62 KB

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