1
0

subService.go 58 KB

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