1
0

subService.go 63 KB

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