1
0

subService.go 61 KB

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