1
0

subService.go 61 KB

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