1
0

subService.go 62 KB

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