1
0

subService.go 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682
  1. package sub
  2. import (
  3. "encoding/base64"
  4. "fmt"
  5. "maps"
  6. "net"
  7. "net/url"
  8. "slices"
  9. "strings"
  10. "time"
  11. "github.com/gin-gonic/gin"
  12. "github.com/goccy/go-json"
  13. "github.com/mhsanaei/3x-ui/v3/database"
  14. "github.com/mhsanaei/3x-ui/v3/database/model"
  15. "github.com/mhsanaei/3x-ui/v3/logger"
  16. "github.com/mhsanaei/3x-ui/v3/util/common"
  17. "github.com/mhsanaei/3x-ui/v3/util/random"
  18. "github.com/mhsanaei/3x-ui/v3/web/service"
  19. "github.com/mhsanaei/3x-ui/v3/xray"
  20. )
  21. // SubService provides business logic for generating subscription links and managing subscription data.
  22. type SubService struct {
  23. address string
  24. showInfo bool
  25. remarkModel string
  26. datepicker string
  27. emailInRemark bool
  28. inboundService service.InboundService
  29. settingService service.SettingService
  30. // nodesByID is populated per request from the Node table so
  31. // resolveInboundAddress can return the node's address for any
  32. // inbound whose NodeID is set. Keeps the per-link host derivation
  33. // O(1) instead of O(N) DB hits.
  34. nodesByID map[int]*model.Node
  35. }
  36. // NewSubService creates a new subscription service with the given configuration.
  37. func NewSubService(showInfo bool, remarkModel string) *SubService {
  38. return &SubService{
  39. showInfo: showInfo,
  40. remarkModel: remarkModel,
  41. }
  42. }
  43. // PrepareForRequest sets per-request state (host + nodes map) on the
  44. // shared SubService. Called by every entry point — GetSubs, GetJson,
  45. // GetClash — so resolveInboundAddress sees the right host and the
  46. // freshly-loaded node map regardless of which sub flavour the client
  47. // hit.
  48. func (s *SubService) PrepareForRequest(host string) {
  49. s.address = host
  50. s.loadNodes()
  51. }
  52. // GetSubs retrieves subscription links for a given subscription ID and host.
  53. func (s *SubService) GetSubs(subId string, host string) ([]string, int64, xray.ClientTraffic, error) {
  54. s.PrepareForRequest(host)
  55. var result []string
  56. var traffic xray.ClientTraffic
  57. var lastOnline int64
  58. var hasEnabledClient bool
  59. var clientTraffics []xray.ClientTraffic
  60. inbounds, err := s.getInboundsBySubId(subId)
  61. if err != nil {
  62. return nil, 0, traffic, err
  63. }
  64. if len(inbounds) == 0 {
  65. return nil, 0, traffic, nil
  66. }
  67. s.datepicker, err = s.settingService.GetDatepicker()
  68. if err != nil {
  69. s.datepicker = "gregorian"
  70. }
  71. s.emailInRemark, err = s.settingService.GetSubEmailInRemark()
  72. if err != nil {
  73. s.emailInRemark = true
  74. }
  75. seenEmails := make(map[string]struct{})
  76. for _, inbound := range inbounds {
  77. clients, err := s.inboundService.GetClients(inbound)
  78. if err != nil {
  79. logger.Error("SubService - GetClients: Unable to get clients from inbound")
  80. }
  81. if clients == nil {
  82. continue
  83. }
  84. s.projectThroughFallbackMaster(inbound)
  85. for _, client := range clients {
  86. if client.SubID == subId {
  87. if client.Enable {
  88. hasEnabledClient = true
  89. }
  90. result = append(result, s.GetLink(inbound, client.Email))
  91. var ct xray.ClientTraffic
  92. ct, clientTraffics = s.appendUniqueTraffic(seenEmails, clientTraffics, inbound.ClientStats, client.Email)
  93. if ct.LastOnline > lastOnline {
  94. lastOnline = ct.LastOnline
  95. }
  96. }
  97. }
  98. }
  99. // Prepare statistics
  100. for index, clientTraffic := range clientTraffics {
  101. if index == 0 {
  102. traffic.Up = clientTraffic.Up
  103. traffic.Down = clientTraffic.Down
  104. traffic.Total = clientTraffic.Total
  105. if clientTraffic.ExpiryTime > 0 {
  106. traffic.ExpiryTime = clientTraffic.ExpiryTime
  107. }
  108. } else {
  109. traffic.Up += clientTraffic.Up
  110. traffic.Down += clientTraffic.Down
  111. if traffic.Total == 0 || clientTraffic.Total == 0 {
  112. traffic.Total = 0
  113. } else {
  114. traffic.Total += clientTraffic.Total
  115. }
  116. if clientTraffic.ExpiryTime != traffic.ExpiryTime {
  117. traffic.ExpiryTime = 0
  118. }
  119. }
  120. }
  121. traffic.Enable = hasEnabledClient
  122. return result, lastOnline, traffic, nil
  123. }
  124. func (s *SubService) getInboundsBySubId(subId string) ([]*model.Inbound, error) {
  125. db := database.GetDB()
  126. var inbounds []*model.Inbound
  127. err := db.Model(model.Inbound{}).Preload("ClientStats").Where(`id in (
  128. SELECT DISTINCT inbounds.id
  129. FROM inbounds
  130. JOIN client_inbounds ON client_inbounds.inbound_id = inbounds.id
  131. JOIN clients ON clients.id = client_inbounds.client_id
  132. WHERE
  133. inbounds.protocol in ('vmess','vless','trojan','shadowsocks','hysteria','hysteria2')
  134. AND clients.sub_id = ? AND inbounds.enable = ?
  135. )`, subId, true).Find(&inbounds).Error
  136. if err != nil {
  137. return nil, err
  138. }
  139. return inbounds, nil
  140. }
  141. // appendUniqueTraffic resolves the traffic stats for email and appends them
  142. // to acc only the first time email is seen. Shared-email mode lets one
  143. // client_traffics row underpin several inbounds, so without dedupe its
  144. // quota and usage would be counted once per inbound.
  145. func (s *SubService) appendUniqueTraffic(seen map[string]struct{}, acc []xray.ClientTraffic, stats []xray.ClientTraffic, email string) (xray.ClientTraffic, []xray.ClientTraffic) {
  146. ct := s.getClientTraffics(stats, email)
  147. if _, dup := seen[email]; !dup {
  148. seen[email] = struct{}{}
  149. acc = append(acc, ct)
  150. }
  151. return ct, acc
  152. }
  153. func (s *SubService) getClientTraffics(traffics []xray.ClientTraffic, email string) xray.ClientTraffic {
  154. for _, traffic := range traffics {
  155. if traffic.Email == email {
  156. return traffic
  157. }
  158. }
  159. return xray.ClientTraffic{}
  160. }
  161. func (s *SubService) getFallbackMaster(dest string, streamSettings string) (string, int, string, error) {
  162. db := database.GetDB()
  163. var inbound *model.Inbound
  164. err := db.Model(model.Inbound{}).
  165. Where("JSON_TYPE(settings, '$.fallbacks') = 'array'").
  166. Where("EXISTS (SELECT * FROM json_each(settings, '$.fallbacks') WHERE json_extract(value, '$.dest') = ?)", dest).
  167. Find(&inbound).Error
  168. if err != nil {
  169. return "", 0, "", err
  170. }
  171. return inbound.Listen, inbound.Port, mergeStreamFromMaster(streamSettings, inbound.StreamSettings), nil
  172. }
  173. // projectThroughFallbackMaster mutates the inbound in place so its
  174. // Listen/Port/StreamSettings reflect the externally reachable master
  175. // when applicable. Covers both fallback mechanisms:
  176. // - panel-tracked: an inbound_fallbacks row where child_id = inbound.Id
  177. // - legacy unix-socket: inbound.Listen begins with "@" and some VLESS/
  178. // Trojan inbound's settings.fallbacks references that listen address
  179. //
  180. // Returns true when a projection happened; sub services call this before
  181. // generating links so a child VLESS-WS bound to 127.0.0.1 emits the
  182. // master's :443 + TLS state instead of its own loopback endpoint.
  183. func (s *SubService) projectThroughFallbackMaster(inbound *model.Inbound) bool {
  184. if inbound == nil {
  185. return false
  186. }
  187. db := database.GetDB()
  188. var master *model.Inbound
  189. var rule model.InboundFallback
  190. if err := db.Where("child_id = ?", inbound.Id).
  191. Order("sort_order ASC, id ASC").
  192. First(&rule).Error; err == nil {
  193. var m model.Inbound
  194. if err := db.Where("id = ?", rule.MasterId).First(&m).Error; err == nil {
  195. master = &m
  196. }
  197. }
  198. if master == nil && len(inbound.Listen) > 0 && inbound.Listen[0] == '@' {
  199. var m model.Inbound
  200. if err := db.Model(model.Inbound{}).
  201. Where("JSON_TYPE(settings, '$.fallbacks') = 'array'").
  202. Where("EXISTS (SELECT * FROM json_each(settings, '$.fallbacks') WHERE json_extract(value, '$.dest') = ?)", inbound.Listen).
  203. First(&m).Error; err == nil {
  204. master = &m
  205. }
  206. }
  207. if master == nil {
  208. return false
  209. }
  210. inbound.StreamSettings = mergeStreamFromMaster(inbound.StreamSettings, master.StreamSettings)
  211. inbound.Listen = master.Listen
  212. inbound.Port = master.Port
  213. return true
  214. }
  215. // mergeStreamFromMaster copies the master's security + tlsSettings +
  216. // realitySettings + externalProxy onto the child's stream so the child's
  217. // link advertises the master's TLS / Reality state. Transport (network
  218. // + ws/grpc/etc. settings) stays the child's.
  219. func mergeStreamFromMaster(childStream, masterStream string) string {
  220. var stream map[string]any
  221. json.Unmarshal([]byte(childStream), &stream)
  222. if stream == nil {
  223. stream = map[string]any{}
  224. }
  225. var mst map[string]any
  226. json.Unmarshal([]byte(masterStream), &mst)
  227. if mst == nil {
  228. return childStream
  229. }
  230. stream["security"] = mst["security"]
  231. if v, ok := mst["tlsSettings"]; ok {
  232. stream["tlsSettings"] = v
  233. } else {
  234. delete(stream, "tlsSettings")
  235. }
  236. if v, ok := mst["realitySettings"]; ok {
  237. stream["realitySettings"] = v
  238. } else {
  239. delete(stream, "realitySettings")
  240. }
  241. if v, ok := mst["externalProxy"]; ok {
  242. stream["externalProxy"] = v
  243. }
  244. out, err := json.MarshalIndent(stream, "", " ")
  245. if err != nil {
  246. return childStream
  247. }
  248. return string(out)
  249. }
  250. // GetLink dispatches to the protocol-specific generator for one (inbound, client)
  251. // pair. Returns "" when the inbound's protocol doesn't produce a subscription URL
  252. // (socks, http, mixed, wireguard, dokodemo, tunnel). The returned string may
  253. // contain multiple `\n`-separated URLs when the inbound has externalProxy set.
  254. func (s *SubService) GetLink(inbound *model.Inbound, email string) string {
  255. switch inbound.Protocol {
  256. case "vmess":
  257. return s.genVmessLink(inbound, email)
  258. case "vless":
  259. return s.genVlessLink(inbound, email)
  260. case "trojan":
  261. return s.genTrojanLink(inbound, email)
  262. case "shadowsocks":
  263. return s.genShadowsocksLink(inbound, email)
  264. case "hysteria", "hysteria2":
  265. return s.genHysteriaLink(inbound, email)
  266. }
  267. return ""
  268. }
  269. // Protocol link generators are intentionally ordered as:
  270. // vmess -> vless -> trojan -> shadowsocks -> hysteria.
  271. func (s *SubService) genVmessLink(inbound *model.Inbound, email string) string {
  272. if inbound.Protocol != model.VMESS {
  273. return ""
  274. }
  275. address := s.resolveInboundAddress(inbound)
  276. obj := map[string]any{
  277. "v": "2",
  278. "add": address,
  279. "port": inbound.Port,
  280. "type": "none",
  281. }
  282. stream := unmarshalStreamSettings(inbound.StreamSettings)
  283. network, _ := stream["network"].(string)
  284. applyVmessNetworkParams(stream, network, obj)
  285. if finalmask, ok := stream["finalmask"].(map[string]any); ok {
  286. applyFinalMaskObj(finalmask, obj)
  287. }
  288. security, _ := stream["security"].(string)
  289. obj["tls"] = security
  290. if security == "tls" {
  291. applyVmessTLSParams(stream, obj)
  292. }
  293. clients, _ := s.inboundService.GetClients(inbound)
  294. clientIndex := findClientIndex(clients, email)
  295. obj["id"] = clients[clientIndex].ID
  296. obj["scy"] = clients[clientIndex].Security
  297. externalProxies, _ := stream["externalProxy"].([]any)
  298. if len(externalProxies) > 0 {
  299. return s.buildVmessExternalProxyLinks(externalProxies, obj, inbound, email)
  300. }
  301. obj["ps"] = s.genRemark(inbound, email, "")
  302. return buildVmessLink(obj)
  303. }
  304. func (s *SubService) genVlessLink(inbound *model.Inbound, email string) string {
  305. if inbound.Protocol != model.VLESS {
  306. return ""
  307. }
  308. address := s.resolveInboundAddress(inbound)
  309. stream := unmarshalStreamSettings(inbound.StreamSettings)
  310. clients, _ := s.inboundService.GetClients(inbound)
  311. clientIndex := findClientIndex(clients, email)
  312. uuid := clients[clientIndex].ID
  313. port := inbound.Port
  314. streamNetwork := stream["network"].(string)
  315. params := make(map[string]string)
  316. params["type"] = streamNetwork
  317. // Add encryption parameter for VLESS from inbound settings
  318. var settings map[string]any
  319. json.Unmarshal([]byte(inbound.Settings), &settings)
  320. if encryption, ok := settings["encryption"].(string); ok {
  321. params["encryption"] = encryption
  322. }
  323. applyShareNetworkParams(stream, streamNetwork, params)
  324. if finalmask, ok := stream["finalmask"].(map[string]any); ok {
  325. applyFinalMaskParams(finalmask, params)
  326. }
  327. security, _ := stream["security"].(string)
  328. switch security {
  329. case "tls":
  330. applyShareTLSParams(stream, params)
  331. if streamNetwork == "tcp" && len(clients[clientIndex].Flow) > 0 {
  332. params["flow"] = clients[clientIndex].Flow
  333. }
  334. case "reality":
  335. applyShareRealityParams(stream, params)
  336. if streamNetwork == "tcp" && len(clients[clientIndex].Flow) > 0 {
  337. params["flow"] = clients[clientIndex].Flow
  338. }
  339. default:
  340. params["security"] = "none"
  341. }
  342. externalProxies, _ := stream["externalProxy"].([]any)
  343. if len(externalProxies) > 0 {
  344. return s.buildExternalProxyURLLinks(
  345. externalProxies,
  346. params,
  347. security,
  348. func(dest string, port int) string {
  349. return fmt.Sprintf("vless://%s@%s:%d", uuid, dest, port)
  350. },
  351. func(ep map[string]any) string {
  352. return s.genRemark(inbound, email, ep["remark"].(string))
  353. },
  354. )
  355. }
  356. link := fmt.Sprintf("vless://%s@%s:%d", uuid, address, port)
  357. return buildLinkWithParams(link, params, s.genRemark(inbound, email, ""))
  358. }
  359. func (s *SubService) genTrojanLink(inbound *model.Inbound, email string) string {
  360. if inbound.Protocol != model.Trojan {
  361. return ""
  362. }
  363. address := s.resolveInboundAddress(inbound)
  364. stream := unmarshalStreamSettings(inbound.StreamSettings)
  365. clients, _ := s.inboundService.GetClients(inbound)
  366. clientIndex := findClientIndex(clients, email)
  367. password := clients[clientIndex].Password
  368. port := inbound.Port
  369. streamNetwork := stream["network"].(string)
  370. params := make(map[string]string)
  371. params["type"] = streamNetwork
  372. applyShareNetworkParams(stream, streamNetwork, params)
  373. if finalmask, ok := stream["finalmask"].(map[string]any); ok {
  374. applyFinalMaskParams(finalmask, params)
  375. }
  376. security, _ := stream["security"].(string)
  377. switch security {
  378. case "tls":
  379. applyShareTLSParams(stream, params)
  380. case "reality":
  381. applyShareRealityParams(stream, params)
  382. if streamNetwork == "tcp" && len(clients[clientIndex].Flow) > 0 {
  383. params["flow"] = clients[clientIndex].Flow
  384. }
  385. default:
  386. params["security"] = "none"
  387. }
  388. externalProxies, _ := stream["externalProxy"].([]any)
  389. if len(externalProxies) > 0 {
  390. return s.buildExternalProxyURLLinks(
  391. externalProxies,
  392. params,
  393. security,
  394. func(dest string, port int) string {
  395. return fmt.Sprintf("trojan://%s@%s:%d", password, dest, port)
  396. },
  397. func(ep map[string]any) string {
  398. return s.genRemark(inbound, email, ep["remark"].(string))
  399. },
  400. )
  401. }
  402. link := fmt.Sprintf("trojan://%s@%s:%d", password, address, port)
  403. return buildLinkWithParams(link, params, s.genRemark(inbound, email, ""))
  404. }
  405. func (s *SubService) genShadowsocksLink(inbound *model.Inbound, email string) string {
  406. if inbound.Protocol != model.Shadowsocks {
  407. return ""
  408. }
  409. address := s.resolveInboundAddress(inbound)
  410. stream := unmarshalStreamSettings(inbound.StreamSettings)
  411. clients, _ := s.inboundService.GetClients(inbound)
  412. var settings map[string]any
  413. json.Unmarshal([]byte(inbound.Settings), &settings)
  414. inboundPassword := settings["password"].(string)
  415. method := settings["method"].(string)
  416. clientIndex := findClientIndex(clients, email)
  417. streamNetwork := stream["network"].(string)
  418. params := make(map[string]string)
  419. params["type"] = streamNetwork
  420. applyShareNetworkParams(stream, streamNetwork, params)
  421. if finalmask, ok := stream["finalmask"].(map[string]any); ok {
  422. applyFinalMaskParams(finalmask, params)
  423. }
  424. security, _ := stream["security"].(string)
  425. if security == "tls" {
  426. applyShareTLSParams(stream, params)
  427. }
  428. encPart := fmt.Sprintf("%s:%s", method, clients[clientIndex].Password)
  429. if method[0] == '2' {
  430. encPart = fmt.Sprintf("%s:%s:%s", method, inboundPassword, clients[clientIndex].Password)
  431. }
  432. externalProxies, _ := stream["externalProxy"].([]any)
  433. if len(externalProxies) > 0 {
  434. proxyParams := cloneStringMap(params)
  435. proxyParams["security"] = security
  436. return s.buildExternalProxyURLLinks(
  437. externalProxies,
  438. proxyParams,
  439. security,
  440. func(dest string, port int) string {
  441. return fmt.Sprintf("ss://%s@%s:%d", base64.StdEncoding.EncodeToString([]byte(encPart)), dest, port)
  442. },
  443. func(ep map[string]any) string {
  444. return s.genRemark(inbound, email, ep["remark"].(string))
  445. },
  446. )
  447. }
  448. link := fmt.Sprintf("ss://%s@%s:%d", base64.StdEncoding.EncodeToString([]byte(encPart)), address, inbound.Port)
  449. return buildLinkWithParams(link, params, s.genRemark(inbound, email, ""))
  450. }
  451. func (s *SubService) genHysteriaLink(inbound *model.Inbound, email string) string {
  452. if !model.IsHysteria(inbound.Protocol) {
  453. return ""
  454. }
  455. var stream map[string]any
  456. json.Unmarshal([]byte(inbound.StreamSettings), &stream)
  457. clients, _ := s.inboundService.GetClients(inbound)
  458. clientIndex := -1
  459. for i, client := range clients {
  460. if client.Email == email {
  461. clientIndex = i
  462. break
  463. }
  464. }
  465. auth := clients[clientIndex].Auth
  466. params := make(map[string]string)
  467. params["security"] = "tls"
  468. tlsSetting, _ := stream["tlsSettings"].(map[string]any)
  469. alpns, _ := tlsSetting["alpn"].([]any)
  470. var alpn []string
  471. for _, a := range alpns {
  472. alpn = append(alpn, a.(string))
  473. }
  474. if len(alpn) > 0 {
  475. params["alpn"] = strings.Join(alpn, ",")
  476. }
  477. if sniValue, ok := searchKey(tlsSetting, "serverName"); ok {
  478. params["sni"], _ = sniValue.(string)
  479. }
  480. tlsSettings, _ := searchKey(tlsSetting, "settings")
  481. if tlsSetting != nil {
  482. if fpValue, ok := searchKey(tlsSettings, "fingerprint"); ok {
  483. params["fp"], _ = fpValue.(string)
  484. }
  485. if insecure, ok := searchKey(tlsSettings, "allowInsecure"); ok {
  486. if insecure.(bool) {
  487. params["insecure"] = "1"
  488. }
  489. }
  490. }
  491. // salamander obfs (Hysteria2). The panel-side link generator already
  492. // emits these; keep the subscription output in sync so a client has
  493. // the obfs password to match the server.
  494. if finalmask, ok := stream["finalmask"].(map[string]any); ok {
  495. applyFinalMaskParams(finalmask, params)
  496. if udpMasks, ok := finalmask["udp"].([]any); ok {
  497. for _, m := range udpMasks {
  498. mask, _ := m.(map[string]any)
  499. if mask == nil || mask["type"] != "salamander" {
  500. continue
  501. }
  502. settings, _ := mask["settings"].(map[string]any)
  503. if pw, ok := settings["password"].(string); ok && pw != "" {
  504. params["obfs"] = "salamander"
  505. params["obfs-password"] = pw
  506. break
  507. }
  508. }
  509. }
  510. }
  511. var settings map[string]any
  512. json.Unmarshal([]byte(inbound.Settings), &settings)
  513. version, _ := settings["version"].(float64)
  514. protocol := "hysteria2"
  515. if int(version) == 1 {
  516. protocol = "hysteria"
  517. }
  518. // Fan out one link per External Proxy entry if any. Previously this
  519. // generator ignored `externalProxy` entirely, so the link kept the
  520. // server's own IP/port even when the admin configured an alternate
  521. // endpoint (e.g. a CDN hostname + port that forwards to the node).
  522. // Matches the behaviour of genVlessLink / genTrojanLink / ….
  523. externalProxies, _ := stream["externalProxy"].([]any)
  524. if len(externalProxies) > 0 {
  525. links := make([]string, 0, len(externalProxies))
  526. for _, externalProxy := range externalProxies {
  527. ep, ok := externalProxy.(map[string]any)
  528. if !ok {
  529. continue
  530. }
  531. dest, _ := ep["dest"].(string)
  532. portF, okPort := ep["port"].(float64)
  533. if dest == "" || !okPort {
  534. continue
  535. }
  536. epRemark, _ := ep["remark"].(string)
  537. link := fmt.Sprintf("%s://%s@%s:%d", protocol, auth, dest, int(portF))
  538. u, _ := url.Parse(link)
  539. q := u.Query()
  540. for k, v := range params {
  541. q.Add(k, v)
  542. }
  543. u.RawQuery = q.Encode()
  544. u.Fragment = s.genRemark(inbound, email, epRemark)
  545. links = append(links, u.String())
  546. }
  547. return strings.Join(links, "\n")
  548. }
  549. // No external proxy configured — use the inbound's resolved address so
  550. // node-managed inbounds get the node's host instead of the central panel's.
  551. link := fmt.Sprintf("%s://%s@%s:%d", protocol, auth, s.resolveInboundAddress(inbound), inbound.Port)
  552. url, _ := url.Parse(link)
  553. q := url.Query()
  554. for k, v := range params {
  555. q.Add(k, v)
  556. }
  557. url.RawQuery = q.Encode()
  558. url.Fragment = s.genRemark(inbound, email, "")
  559. return url.String()
  560. }
  561. // loadNodes refreshes nodesByID from the DB. Called once per request so
  562. // the per-inbound resolveInboundAddress lookups are pure map reads.
  563. // We filter to address != ” so a half-configured node row doesn't
  564. // accidentally produce a useless host like "https://:2053".
  565. func (s *SubService) loadNodes() {
  566. db := database.GetDB()
  567. var nodes []*model.Node
  568. if err := db.Model(&model.Node{}).Where("address != ''").Find(&nodes).Error; err != nil {
  569. logger.Warning("subscription: load nodes failed:", err)
  570. s.nodesByID = nil
  571. return
  572. }
  573. m := make(map[int]*model.Node, len(nodes))
  574. for _, n := range nodes {
  575. m[n.Id] = n
  576. }
  577. s.nodesByID = m
  578. }
  579. // resolveInboundAddress picks the host an external client should
  580. // connect to. Order:
  581. // 1. If the inbound is node-managed and the node has an address, use
  582. // the node's address — central panel's hostname doesn't speak xray
  583. // for that inbound.
  584. // 2. If the inbound binds to a non-wildcard listen address, use it.
  585. // 3. Otherwise fall back to the request's host (whatever the client
  586. // subscribed against).
  587. func (s *SubService) resolveInboundAddress(inbound *model.Inbound) string {
  588. if inbound.NodeID != nil && s.nodesByID != nil {
  589. if n, ok := s.nodesByID[*inbound.NodeID]; ok && n.Address != "" {
  590. return n.Address
  591. }
  592. }
  593. if inbound.Listen == "" || inbound.Listen == "0.0.0.0" || inbound.Listen == "::" || inbound.Listen == "::0" {
  594. return s.address
  595. }
  596. return inbound.Listen
  597. }
  598. func findClientIndex(clients []model.Client, email string) int {
  599. for i, client := range clients {
  600. if client.Email == email {
  601. return i
  602. }
  603. }
  604. return -1
  605. }
  606. func unmarshalStreamSettings(streamSettings string) map[string]any {
  607. var stream map[string]any
  608. json.Unmarshal([]byte(streamSettings), &stream)
  609. return stream
  610. }
  611. func applyPathAndHostParams(settings map[string]any, params map[string]string) {
  612. params["path"] = settings["path"].(string)
  613. if host, ok := settings["host"].(string); ok && len(host) > 0 {
  614. params["host"] = host
  615. } else {
  616. headers, _ := settings["headers"].(map[string]any)
  617. params["host"] = searchHost(headers)
  618. }
  619. }
  620. func applyPathAndHostObj(settings map[string]any, obj map[string]any) {
  621. obj["path"] = settings["path"].(string)
  622. if host, ok := settings["host"].(string); ok && len(host) > 0 {
  623. obj["host"] = host
  624. } else {
  625. headers, _ := settings["headers"].(map[string]any)
  626. obj["host"] = searchHost(headers)
  627. }
  628. }
  629. func applyShareNetworkParams(stream map[string]any, streamNetwork string, params map[string]string) {
  630. switch streamNetwork {
  631. case "tcp":
  632. tcp, _ := stream["tcpSettings"].(map[string]any)
  633. header, _ := tcp["header"].(map[string]any)
  634. typeStr, _ := header["type"].(string)
  635. if typeStr == "http" {
  636. request := header["request"].(map[string]any)
  637. requestPath, _ := request["path"].([]any)
  638. params["path"] = requestPath[0].(string)
  639. headers, _ := request["headers"].(map[string]any)
  640. params["host"] = searchHost(headers)
  641. params["headerType"] = "http"
  642. }
  643. case "kcp":
  644. applyKcpShareParams(stream, params)
  645. case "ws":
  646. ws, _ := stream["wsSettings"].(map[string]any)
  647. applyPathAndHostParams(ws, params)
  648. case "grpc":
  649. grpc, _ := stream["grpcSettings"].(map[string]any)
  650. params["serviceName"] = grpc["serviceName"].(string)
  651. params["authority"], _ = grpc["authority"].(string)
  652. if grpc["multiMode"].(bool) {
  653. params["mode"] = "multi"
  654. }
  655. case "httpupgrade":
  656. httpupgrade, _ := stream["httpupgradeSettings"].(map[string]any)
  657. applyPathAndHostParams(httpupgrade, params)
  658. case "xhttp":
  659. xhttp, _ := stream["xhttpSettings"].(map[string]any)
  660. applyXhttpExtraParams(xhttp, params)
  661. }
  662. }
  663. // applyXhttpExtraObj copies the bidirectional xhttp settings into the
  664. // VMess base64 JSON link object. VMess supports arbitrary keys, so we
  665. // flatten the SplitHTTPConfig "extra" fields directly onto obj.
  666. func applyXhttpExtraObj(xhttp map[string]any, obj map[string]any) {
  667. if xpb, ok := xhttp["xPaddingBytes"].(string); ok && len(xpb) > 0 {
  668. obj["x_padding_bytes"] = xpb
  669. }
  670. maps.Copy(obj, buildXhttpExtra(xhttp))
  671. }
  672. func applyVmessNetworkParams(stream map[string]any, network string, obj map[string]any) {
  673. obj["net"] = network
  674. switch network {
  675. case "tcp":
  676. tcp, _ := stream["tcpSettings"].(map[string]any)
  677. header, _ := tcp["header"].(map[string]any)
  678. typeStr, _ := header["type"].(string)
  679. obj["type"] = typeStr
  680. if typeStr == "http" {
  681. request := header["request"].(map[string]any)
  682. requestPath, _ := request["path"].([]any)
  683. obj["path"] = requestPath[0].(string)
  684. headers, _ := request["headers"].(map[string]any)
  685. obj["host"] = searchHost(headers)
  686. }
  687. case "kcp":
  688. applyKcpShareObj(stream, obj)
  689. case "ws":
  690. ws, _ := stream["wsSettings"].(map[string]any)
  691. applyPathAndHostObj(ws, obj)
  692. case "grpc":
  693. grpc, _ := stream["grpcSettings"].(map[string]any)
  694. obj["path"] = grpc["serviceName"].(string)
  695. obj["authority"] = grpc["authority"].(string)
  696. if grpc["multiMode"].(bool) {
  697. obj["type"] = "multi"
  698. }
  699. case "httpupgrade":
  700. httpupgrade, _ := stream["httpupgradeSettings"].(map[string]any)
  701. applyPathAndHostObj(httpupgrade, obj)
  702. case "xhttp":
  703. xhttp, _ := stream["xhttpSettings"].(map[string]any)
  704. applyPathAndHostObj(xhttp, obj)
  705. if mode, ok := xhttp["mode"].(string); ok {
  706. obj["mode"] = mode
  707. }
  708. applyXhttpExtraObj(xhttp, obj)
  709. }
  710. }
  711. func applyShareTLSParams(stream map[string]any, params map[string]string) {
  712. params["security"] = "tls"
  713. tlsSetting, _ := stream["tlsSettings"].(map[string]any)
  714. alpns, _ := tlsSetting["alpn"].([]any)
  715. var alpn []string
  716. for _, a := range alpns {
  717. alpn = append(alpn, a.(string))
  718. }
  719. if len(alpn) > 0 {
  720. params["alpn"] = strings.Join(alpn, ",")
  721. }
  722. if sniValue, ok := searchKey(tlsSetting, "serverName"); ok {
  723. params["sni"], _ = sniValue.(string)
  724. }
  725. tlsSettings, _ := searchKey(tlsSetting, "settings")
  726. if tlsSetting != nil {
  727. if fpValue, ok := searchKey(tlsSettings, "fingerprint"); ok {
  728. params["fp"], _ = fpValue.(string)
  729. }
  730. }
  731. }
  732. func applyVmessTLSParams(stream map[string]any, obj map[string]any) {
  733. tlsSetting, _ := stream["tlsSettings"].(map[string]any)
  734. alpns, _ := tlsSetting["alpn"].([]any)
  735. if len(alpns) > 0 {
  736. var alpn []string
  737. for _, a := range alpns {
  738. alpn = append(alpn, a.(string))
  739. }
  740. obj["alpn"] = strings.Join(alpn, ",")
  741. }
  742. if sniValue, ok := searchKey(tlsSetting, "serverName"); ok {
  743. obj["sni"], _ = sniValue.(string)
  744. }
  745. tlsSettings, _ := searchKey(tlsSetting, "settings")
  746. if tlsSetting != nil {
  747. if fpValue, ok := searchKey(tlsSettings, "fingerprint"); ok {
  748. obj["fp"], _ = fpValue.(string)
  749. }
  750. }
  751. }
  752. func applyShareRealityParams(stream map[string]any, params map[string]string) {
  753. params["security"] = "reality"
  754. realitySetting, _ := stream["realitySettings"].(map[string]any)
  755. realitySettings, _ := searchKey(realitySetting, "settings")
  756. if realitySetting != nil {
  757. if sniValue, ok := searchKey(realitySetting, "serverNames"); ok {
  758. sNames, _ := sniValue.([]any)
  759. params["sni"] = sNames[random.Num(len(sNames))].(string)
  760. }
  761. if pbkValue, ok := searchKey(realitySettings, "publicKey"); ok {
  762. params["pbk"], _ = pbkValue.(string)
  763. }
  764. if sidValue, ok := searchKey(realitySetting, "shortIds"); ok {
  765. shortIds, _ := sidValue.([]any)
  766. params["sid"] = shortIds[random.Num(len(shortIds))].(string)
  767. }
  768. if fpValue, ok := searchKey(realitySettings, "fingerprint"); ok {
  769. if fp, ok := fpValue.(string); ok && len(fp) > 0 {
  770. params["fp"] = fp
  771. }
  772. }
  773. if pqvValue, ok := searchKey(realitySettings, "mldsa65Verify"); ok {
  774. if pqv, ok := pqvValue.(string); ok && len(pqv) > 0 {
  775. params["pqv"] = pqv
  776. }
  777. }
  778. params["spx"] = "/" + random.Seq(15)
  779. }
  780. }
  781. func buildVmessLink(obj map[string]any) string {
  782. jsonStr, _ := json.MarshalIndent(obj, "", " ")
  783. return "vmess://" + base64.StdEncoding.EncodeToString(jsonStr)
  784. }
  785. func cloneVmessShareObj(baseObj map[string]any, newSecurity string) map[string]any {
  786. newObj := map[string]any{}
  787. for key, value := range baseObj {
  788. if !(newSecurity == "none" && (key == "alpn" || key == "sni" || key == "fp")) {
  789. newObj[key] = value
  790. }
  791. }
  792. return newObj
  793. }
  794. func (s *SubService) buildVmessExternalProxyLinks(externalProxies []any, baseObj map[string]any, inbound *model.Inbound, email string) string {
  795. var links strings.Builder
  796. for index, externalProxy := range externalProxies {
  797. ep, _ := externalProxy.(map[string]any)
  798. newSecurity, _ := ep["forceTls"].(string)
  799. newObj := cloneVmessShareObj(baseObj, newSecurity)
  800. newObj["ps"] = s.genRemark(inbound, email, ep["remark"].(string))
  801. newObj["add"] = ep["dest"].(string)
  802. newObj["port"] = int(ep["port"].(float64))
  803. if newSecurity != "same" {
  804. newObj["tls"] = newSecurity
  805. }
  806. if index > 0 {
  807. links.WriteString("\n")
  808. }
  809. links.WriteString(buildVmessLink(newObj))
  810. }
  811. return links.String()
  812. }
  813. func buildLinkWithParams(link string, params map[string]string, fragment string) string {
  814. parsedURL, _ := url.Parse(link)
  815. q := parsedURL.Query()
  816. for k, v := range params {
  817. q.Add(k, v)
  818. }
  819. parsedURL.RawQuery = q.Encode()
  820. parsedURL.Fragment = fragment
  821. return parsedURL.String()
  822. }
  823. func buildLinkWithParamsAndSecurity(link string, params map[string]string, fragment, security string, omitTLSFields bool) string {
  824. parsedURL, _ := url.Parse(link)
  825. q := parsedURL.Query()
  826. for k, v := range params {
  827. if k == "security" {
  828. v = security
  829. }
  830. if omitTLSFields && (k == "alpn" || k == "sni" || k == "fp") {
  831. continue
  832. }
  833. q.Add(k, v)
  834. }
  835. parsedURL.RawQuery = q.Encode()
  836. parsedURL.Fragment = fragment
  837. return parsedURL.String()
  838. }
  839. func (s *SubService) buildExternalProxyURLLinks(
  840. externalProxies []any,
  841. params map[string]string,
  842. baseSecurity string,
  843. makeLink func(dest string, port int) string,
  844. makeRemark func(ep map[string]any) string,
  845. ) string {
  846. links := make([]string, 0, len(externalProxies))
  847. for _, externalProxy := range externalProxies {
  848. ep, _ := externalProxy.(map[string]any)
  849. newSecurity, _ := ep["forceTls"].(string)
  850. dest, _ := ep["dest"].(string)
  851. port := int(ep["port"].(float64))
  852. securityToApply := baseSecurity
  853. if newSecurity != "same" {
  854. securityToApply = newSecurity
  855. }
  856. links = append(
  857. links,
  858. buildLinkWithParamsAndSecurity(
  859. makeLink(dest, port),
  860. params,
  861. makeRemark(ep),
  862. securityToApply,
  863. newSecurity == "none",
  864. ),
  865. )
  866. }
  867. return strings.Join(links, "\n")
  868. }
  869. func cloneStringMap(source map[string]string) map[string]string {
  870. cloned := make(map[string]string, len(source))
  871. maps.Copy(cloned, source)
  872. return cloned
  873. }
  874. func (s *SubService) genRemark(inbound *model.Inbound, email string, extra string) string {
  875. separationChar := string(s.remarkModel[0])
  876. orderChars := s.remarkModel[1:]
  877. orders := map[byte]string{
  878. 'i': "",
  879. 'e': "",
  880. 'o': "",
  881. }
  882. if len(email) > 0 && s.emailInRemark {
  883. orders['e'] = email
  884. }
  885. if len(inbound.Remark) > 0 {
  886. orders['i'] = inbound.Remark
  887. }
  888. if len(extra) > 0 {
  889. orders['o'] = extra
  890. }
  891. var remark []string
  892. for i := 0; i < len(orderChars); i++ {
  893. char := orderChars[i]
  894. order, exists := orders[char]
  895. if exists && order != "" {
  896. remark = append(remark, order)
  897. }
  898. }
  899. if s.showInfo {
  900. statsExist := false
  901. var stats xray.ClientTraffic
  902. for _, clientStat := range inbound.ClientStats {
  903. if clientStat.Email == email {
  904. stats = clientStat
  905. statsExist = true
  906. break
  907. }
  908. }
  909. // Get remained days
  910. if statsExist {
  911. if !stats.Enable {
  912. return fmt.Sprintf("⛔️N/A%s%s", separationChar, strings.Join(remark, separationChar))
  913. }
  914. if vol := stats.Total - (stats.Up + stats.Down); vol > 0 {
  915. remark = append(remark, fmt.Sprintf("%s%s", common.FormatTraffic(vol), "📊"))
  916. }
  917. now := time.Now().Unix()
  918. switch exp := stats.ExpiryTime / 1000; {
  919. case exp > 0:
  920. remainingSeconds := exp - now
  921. days := remainingSeconds / 86400
  922. hours := (remainingSeconds % 86400) / 3600
  923. minutes := (remainingSeconds % 3600) / 60
  924. if days > 0 {
  925. if hours > 0 {
  926. remark = append(remark, fmt.Sprintf("%dD,%dH⏳", days, hours))
  927. } else {
  928. remark = append(remark, fmt.Sprintf("%dD⏳", days))
  929. }
  930. } else if hours > 0 {
  931. remark = append(remark, fmt.Sprintf("%dH⏳", hours))
  932. } else {
  933. remark = append(remark, fmt.Sprintf("%dM⏳", minutes))
  934. }
  935. case exp < 0:
  936. days := exp / -86400
  937. hours := (exp % -86400) / 3600
  938. minutes := (exp % -3600) / 60
  939. if days > 0 {
  940. if hours > 0 {
  941. remark = append(remark, fmt.Sprintf("%dD,%dH⏳", days, hours))
  942. } else {
  943. remark = append(remark, fmt.Sprintf("%dD⏳", days))
  944. }
  945. } else if hours > 0 {
  946. remark = append(remark, fmt.Sprintf("%dH⏳", hours))
  947. } else {
  948. remark = append(remark, fmt.Sprintf("%dM⏳", minutes))
  949. }
  950. }
  951. }
  952. }
  953. return strings.Join(remark, separationChar)
  954. }
  955. func searchKey(data any, key string) (any, bool) {
  956. switch val := data.(type) {
  957. case map[string]any:
  958. for k, v := range val {
  959. if k == key {
  960. return v, true
  961. }
  962. if result, ok := searchKey(v, key); ok {
  963. return result, true
  964. }
  965. }
  966. case []any:
  967. for _, v := range val {
  968. if result, ok := searchKey(v, key); ok {
  969. return result, true
  970. }
  971. }
  972. }
  973. return nil, false
  974. }
  975. // buildXhttpExtra walks an xhttpSettings map and returns the JSON blob
  976. // that goes into the URL's `extra` param (or, for VMess, the link
  977. // object). Carries ONLY the bidirectional fields from xray-core's
  978. // SplitHTTPConfig — i.e. the ones the server enforces and the client
  979. // must match. Strictly one-sided fields are excluded:
  980. //
  981. // - server-only (noSSEHeader, scMaxBufferedPosts, scStreamUpServerSecs,
  982. // serverMaxHeaderBytes) — client wouldn't read them, so emitting
  983. // them just bloats the URL.
  984. // - client-only (headers, uplinkHTTPMethod, uplinkChunkSize,
  985. // noGRPCHeader, scMinPostsIntervalMs, xmux, downloadSettings) — the
  986. // inbound config doesn't have them; the client configures them
  987. // locally.
  988. //
  989. // Truthy-only guards keep default inbounds emitting the same compact URL
  990. // they did before this helper grew.
  991. func buildXhttpExtra(xhttp map[string]any) map[string]any {
  992. if xhttp == nil {
  993. return nil
  994. }
  995. extra := map[string]any{}
  996. if xpb, ok := xhttp["xPaddingBytes"].(string); ok && len(xpb) > 0 {
  997. extra["xPaddingBytes"] = xpb
  998. }
  999. if obfs, ok := xhttp["xPaddingObfsMode"].(bool); ok && obfs {
  1000. extra["xPaddingObfsMode"] = true
  1001. for _, field := range []string{"xPaddingKey", "xPaddingHeader", "xPaddingPlacement", "xPaddingMethod"} {
  1002. if v, ok := xhttp[field].(string); ok && len(v) > 0 {
  1003. extra[field] = v
  1004. }
  1005. }
  1006. }
  1007. if mode, ok := xhttp["mode"].(string); ok && len(mode) > 0 {
  1008. extra["mode"] = mode
  1009. }
  1010. stringFields := []string{
  1011. "sessionPlacement", "sessionKey",
  1012. "seqPlacement", "seqKey",
  1013. "uplinkDataPlacement", "uplinkDataKey",
  1014. "scMaxEachPostBytes",
  1015. }
  1016. for _, field := range stringFields {
  1017. if v, ok := xhttp[field].(string); ok && len(v) > 0 {
  1018. extra[field] = v
  1019. }
  1020. }
  1021. // Headers — emitted as the {name: value} map upstream's struct
  1022. // expects. The server runtime ignores this field, but the client
  1023. // (consuming the share link) honors it. Drop any "host" entry —
  1024. // host already wins as a top-level URL param.
  1025. if rawHeaders, ok := xhttp["headers"].(map[string]any); ok && len(rawHeaders) > 0 {
  1026. out := map[string]any{}
  1027. for k, v := range rawHeaders {
  1028. if strings.EqualFold(k, "host") {
  1029. continue
  1030. }
  1031. out[k] = v
  1032. }
  1033. if len(out) > 0 {
  1034. extra["headers"] = out
  1035. }
  1036. }
  1037. if len(extra) == 0 {
  1038. return nil
  1039. }
  1040. return extra
  1041. }
  1042. // applyXhttpExtraParams emits the full xhttp config into the URL query
  1043. // params of a vless:// / trojan:// / ss:// link. Sets path/host/mode at
  1044. // top level (xray's Build() always lets these win over `extra`) and packs
  1045. // everything else into a JSON `extra` param. Also writes the flat
  1046. // `x_padding_bytes` param sing-box-family clients understand.
  1047. //
  1048. // Without this, the admin's custom xPaddingBytes / sessionKey / etc. never
  1049. // reach the client and handshakes are silently rejected with
  1050. // `invalid padding (...) length: 0` — the client-visible symptom is
  1051. // "xhttp doesn't connect" on OpenWRT / sing-box.
  1052. //
  1053. // Two encodings are written so every popular client can read at least one:
  1054. //
  1055. // - x_padding_bytes=<range> — flat param, understood by sing-box and its
  1056. // derivatives (Podkop, OpenWRT sing-box, Karing, NekoBox, …).
  1057. // - extra=<url-encoded-json> — full xhttp settings blob, which is how
  1058. // xray-core clients (v2rayNG, Happ, Furious, Exclave, …) pick up the
  1059. // bidirectional fields beyond path/host/mode.
  1060. func applyXhttpExtraParams(xhttp map[string]any, params map[string]string) {
  1061. if xhttp == nil {
  1062. return
  1063. }
  1064. applyPathAndHostParams(xhttp, params)
  1065. if mode, ok := xhttp["mode"].(string); ok {
  1066. params["mode"] = mode
  1067. }
  1068. if xpb, ok := xhttp["xPaddingBytes"].(string); ok && len(xpb) > 0 {
  1069. params["x_padding_bytes"] = xpb
  1070. }
  1071. extra := buildXhttpExtra(xhttp)
  1072. if extra != nil {
  1073. if b, err := json.Marshal(extra); err == nil {
  1074. params["extra"] = string(b)
  1075. }
  1076. }
  1077. }
  1078. var kcpMaskToHeaderType = map[string]string{
  1079. "header-dns": "dns",
  1080. "header-dtls": "dtls",
  1081. "header-srtp": "srtp",
  1082. "header-utp": "utp",
  1083. "header-wechat": "wechat-video",
  1084. "header-wireguard": "wireguard",
  1085. }
  1086. var validFinalMaskUDPTypes = map[string]struct{}{
  1087. "salamander": {},
  1088. "mkcp-aes128gcm": {},
  1089. "header-dns": {},
  1090. "header-dtls": {},
  1091. "header-srtp": {},
  1092. "header-utp": {},
  1093. "header-wechat": {},
  1094. "header-wireguard": {},
  1095. "mkcp-original": {},
  1096. "xdns": {},
  1097. "xicmp": {},
  1098. "noise": {},
  1099. "header-custom": {},
  1100. }
  1101. var validFinalMaskTCPTypes = map[string]struct{}{
  1102. "header-custom": {},
  1103. "fragment": {},
  1104. "sudoku": {},
  1105. }
  1106. // applyKcpShareParams reconstructs legacy KCP share-link fields from either
  1107. // the historical kcpSettings.header/seed shape or the current finalmask model.
  1108. // This keeps subscription output compatible while avoiding panics when older
  1109. // keys are absent from modern inbounds.
  1110. func applyKcpShareParams(stream map[string]any, params map[string]string) {
  1111. extractKcpShareFields(stream).applyToParams(params)
  1112. }
  1113. func applyKcpShareObj(stream map[string]any, obj map[string]any) {
  1114. extractKcpShareFields(stream).applyToObj(obj)
  1115. }
  1116. type kcpShareFields struct {
  1117. headerType string
  1118. seed string
  1119. mtu int
  1120. tti int
  1121. }
  1122. func (f kcpShareFields) applyToParams(params map[string]string) {
  1123. if f.headerType != "" && f.headerType != "none" {
  1124. params["headerType"] = f.headerType
  1125. }
  1126. setStringParam(params, "seed", f.seed)
  1127. setIntParam(params, "mtu", f.mtu)
  1128. setIntParam(params, "tti", f.tti)
  1129. }
  1130. func (f kcpShareFields) applyToObj(obj map[string]any) {
  1131. if f.headerType != "" && f.headerType != "none" {
  1132. obj["type"] = f.headerType
  1133. }
  1134. setStringField(obj, "path", f.seed)
  1135. setIntField(obj, "mtu", f.mtu)
  1136. setIntField(obj, "tti", f.tti)
  1137. }
  1138. func extractKcpShareFields(stream map[string]any) kcpShareFields {
  1139. fields := kcpShareFields{headerType: "none"}
  1140. if kcp, ok := stream["kcpSettings"].(map[string]any); ok {
  1141. if header, ok := kcp["header"].(map[string]any); ok {
  1142. if value, ok := header["type"].(string); ok && value != "" {
  1143. fields.headerType = value
  1144. }
  1145. }
  1146. if value, ok := kcp["seed"].(string); ok && value != "" {
  1147. fields.seed = value
  1148. }
  1149. if value, ok := readPositiveInt(kcp["mtu"]); ok {
  1150. fields.mtu = value
  1151. }
  1152. if value, ok := readPositiveInt(kcp["tti"]); ok {
  1153. fields.tti = value
  1154. }
  1155. }
  1156. for _, rawMask := range normalizedFinalMaskUDPMasks(stream["finalmask"]) {
  1157. mask, _ := rawMask.(map[string]any)
  1158. if mask == nil {
  1159. continue
  1160. }
  1161. maskType, _ := mask["type"].(string)
  1162. if mapped, ok := kcpMaskToHeaderType[maskType]; ok {
  1163. fields.headerType = mapped
  1164. continue
  1165. }
  1166. switch maskType {
  1167. case "mkcp-original":
  1168. fields.seed = ""
  1169. case "mkcp-aes128gcm":
  1170. fields.seed = ""
  1171. settings, _ := mask["settings"].(map[string]any)
  1172. if value, ok := settings["password"].(string); ok && value != "" {
  1173. fields.seed = value
  1174. }
  1175. }
  1176. }
  1177. return fields
  1178. }
  1179. func readPositiveInt(value any) (int, bool) {
  1180. switch number := value.(type) {
  1181. case int:
  1182. return number, number > 0
  1183. case int32:
  1184. return int(number), number > 0
  1185. case int64:
  1186. return int(number), number > 0
  1187. case float32:
  1188. parsed := int(number)
  1189. return parsed, parsed > 0
  1190. case float64:
  1191. parsed := int(number)
  1192. return parsed, parsed > 0
  1193. default:
  1194. return 0, false
  1195. }
  1196. }
  1197. func setStringParam(params map[string]string, key, value string) {
  1198. if value == "" {
  1199. delete(params, key)
  1200. return
  1201. }
  1202. params[key] = value
  1203. }
  1204. func setIntParam(params map[string]string, key string, value int) {
  1205. if value <= 0 {
  1206. delete(params, key)
  1207. return
  1208. }
  1209. params[key] = fmt.Sprintf("%d", value)
  1210. }
  1211. func setStringField(obj map[string]any, key, value string) {
  1212. if value == "" {
  1213. delete(obj, key)
  1214. return
  1215. }
  1216. obj[key] = value
  1217. }
  1218. func setIntField(obj map[string]any, key string, value int) {
  1219. if value <= 0 {
  1220. delete(obj, key)
  1221. return
  1222. }
  1223. obj[key] = value
  1224. }
  1225. // applyFinalMaskParams exports the finalmask payload as the compact
  1226. // `fm=<json>` share-link field used by v2rayN-compatible clients.
  1227. func applyFinalMaskParams(finalmask map[string]any, params map[string]string) {
  1228. if fm, ok := marshalFinalMask(finalmask); ok {
  1229. params["fm"] = fm
  1230. }
  1231. }
  1232. func applyFinalMaskObj(finalmask map[string]any, obj map[string]any) {
  1233. if fm, ok := marshalFinalMask(finalmask); ok {
  1234. obj["fm"] = fm
  1235. }
  1236. }
  1237. func marshalFinalMask(finalmask map[string]any) (string, bool) {
  1238. normalized := normalizeFinalMask(finalmask)
  1239. if !hasFinalMaskContent(normalized) {
  1240. return "", false
  1241. }
  1242. b, err := json.Marshal(normalized)
  1243. if err != nil || len(b) == 0 || string(b) == "null" {
  1244. return "", false
  1245. }
  1246. return string(b), true
  1247. }
  1248. func normalizeFinalMask(finalmask map[string]any) map[string]any {
  1249. tcpMasks := normalizedFinalMaskTCPMasks(finalmask)
  1250. udpMasks := normalizedFinalMaskUDPMasks(finalmask)
  1251. quicParams, hasQuicParams := finalmask["quicParams"].(map[string]any)
  1252. if len(tcpMasks) == 0 && len(udpMasks) == 0 && !hasQuicParams {
  1253. return nil
  1254. }
  1255. result := map[string]any{}
  1256. if len(tcpMasks) > 0 {
  1257. result["tcp"] = tcpMasks
  1258. }
  1259. if len(udpMasks) > 0 {
  1260. result["udp"] = udpMasks
  1261. }
  1262. if hasQuicParams && len(quicParams) > 0 {
  1263. result["quicParams"] = quicParams
  1264. }
  1265. return result
  1266. }
  1267. func normalizedFinalMaskTCPMasks(value any) []any {
  1268. finalmask, _ := value.(map[string]any)
  1269. if finalmask == nil {
  1270. return nil
  1271. }
  1272. rawMasks, _ := finalmask["tcp"].([]any)
  1273. if len(rawMasks) == 0 {
  1274. return nil
  1275. }
  1276. normalized := make([]any, 0, len(rawMasks))
  1277. for _, rawMask := range rawMasks {
  1278. mask, _ := rawMask.(map[string]any)
  1279. if mask == nil {
  1280. continue
  1281. }
  1282. maskType, _ := mask["type"].(string)
  1283. if _, ok := validFinalMaskTCPTypes[maskType]; !ok || maskType == "" {
  1284. continue
  1285. }
  1286. normalizedMask := map[string]any{"type": maskType}
  1287. if settings, ok := mask["settings"].(map[string]any); ok && len(settings) > 0 {
  1288. normalizedMask["settings"] = settings
  1289. }
  1290. normalized = append(normalized, normalizedMask)
  1291. }
  1292. if len(normalized) == 0 {
  1293. return nil
  1294. }
  1295. return normalized
  1296. }
  1297. func normalizedFinalMaskUDPMasks(value any) []any {
  1298. finalmask, _ := value.(map[string]any)
  1299. if finalmask == nil {
  1300. return nil
  1301. }
  1302. rawMasks, _ := finalmask["udp"].([]any)
  1303. if len(rawMasks) == 0 {
  1304. return nil
  1305. }
  1306. normalized := make([]any, 0, len(rawMasks))
  1307. for _, rawMask := range rawMasks {
  1308. mask, _ := rawMask.(map[string]any)
  1309. if mask == nil {
  1310. continue
  1311. }
  1312. maskType, _ := mask["type"].(string)
  1313. if _, ok := validFinalMaskUDPTypes[maskType]; !ok || maskType == "" {
  1314. continue
  1315. }
  1316. normalizedMask := map[string]any{"type": maskType}
  1317. if settings, ok := mask["settings"].(map[string]any); ok && len(settings) > 0 {
  1318. normalizedMask["settings"] = settings
  1319. }
  1320. normalized = append(normalized, normalizedMask)
  1321. }
  1322. if len(normalized) == 0 {
  1323. return nil
  1324. }
  1325. return normalized
  1326. }
  1327. func hasFinalMaskContent(value any) bool {
  1328. switch v := value.(type) {
  1329. case nil:
  1330. return false
  1331. case string:
  1332. return len(v) > 0
  1333. case map[string]any:
  1334. for _, item := range v {
  1335. if hasFinalMaskContent(item) {
  1336. return true
  1337. }
  1338. }
  1339. return false
  1340. case []any:
  1341. return slices.ContainsFunc(v, hasFinalMaskContent)
  1342. default:
  1343. return true
  1344. }
  1345. }
  1346. func searchHost(headers any) string {
  1347. data, _ := headers.(map[string]any)
  1348. for k, v := range data {
  1349. if strings.EqualFold(k, "host") {
  1350. switch v.(type) {
  1351. case []any:
  1352. hosts, _ := v.([]any)
  1353. if len(hosts) > 0 {
  1354. return hosts[0].(string)
  1355. } else {
  1356. return ""
  1357. }
  1358. case any:
  1359. return v.(string)
  1360. }
  1361. }
  1362. }
  1363. return ""
  1364. }
  1365. // PageData is a view model for subpage.html
  1366. // PageData contains data for rendering the subscription information page.
  1367. type PageData struct {
  1368. Host string
  1369. BasePath string
  1370. SId string
  1371. Enabled bool
  1372. Download string
  1373. Upload string
  1374. Total string
  1375. Used string
  1376. Remained string
  1377. Expire int64
  1378. LastOnline int64
  1379. Datepicker string
  1380. DownloadByte int64
  1381. UploadByte int64
  1382. TotalByte int64
  1383. SubUrl string
  1384. SubJsonUrl string
  1385. SubClashUrl string
  1386. SubTitle string
  1387. SubSupportUrl string
  1388. Result []string
  1389. }
  1390. // ResolveRequest extracts scheme and host info from request/headers consistently.
  1391. // ResolveRequest extracts scheme, host, and header information from an HTTP request.
  1392. func (s *SubService) ResolveRequest(c *gin.Context) (scheme string, host string, hostWithPort string, hostHeader string) {
  1393. // scheme
  1394. scheme = "http"
  1395. if c.Request.TLS != nil || strings.EqualFold(c.GetHeader("X-Forwarded-Proto"), "https") {
  1396. scheme = "https"
  1397. }
  1398. // base host (no port)
  1399. if h, err := getHostFromXFH(c.GetHeader("X-Forwarded-Host")); err == nil && h != "" {
  1400. host = h
  1401. }
  1402. if host == "" {
  1403. host = c.GetHeader("X-Real-IP")
  1404. }
  1405. if host == "" {
  1406. var err error
  1407. host, _, err = net.SplitHostPort(c.Request.Host)
  1408. if err != nil {
  1409. host = c.Request.Host
  1410. }
  1411. }
  1412. // host:port for URLs
  1413. hostWithPort = c.GetHeader("X-Forwarded-Host")
  1414. if hostWithPort == "" {
  1415. hostWithPort = c.Request.Host
  1416. }
  1417. if hostWithPort == "" {
  1418. hostWithPort = host
  1419. }
  1420. // header display host
  1421. hostHeader = c.GetHeader("X-Forwarded-Host")
  1422. if hostHeader == "" {
  1423. hostHeader = c.GetHeader("X-Real-IP")
  1424. }
  1425. if hostHeader == "" {
  1426. hostHeader = host
  1427. }
  1428. return
  1429. }
  1430. // BuildURLs constructs absolute subscription and JSON subscription URLs for a given subscription ID.
  1431. // It prioritizes configured URIs, then individual settings, and finally falls back to request-derived components.
  1432. func (s *SubService) BuildURLs(scheme, hostWithPort, subPath, subJsonPath, subClashPath, subId string) (subURL, subJsonURL, subClashURL string) {
  1433. if subId == "" {
  1434. return "", "", ""
  1435. }
  1436. configuredSubURI, _ := s.settingService.GetSubURI()
  1437. configuredSubJsonURI, _ := s.settingService.GetSubJsonURI()
  1438. configuredSubClashURI, _ := s.settingService.GetSubClashURI()
  1439. var baseScheme, baseHostWithPort string
  1440. if configuredSubURI == "" || configuredSubJsonURI == "" || configuredSubClashURI == "" {
  1441. baseScheme, baseHostWithPort = s.getBaseSchemeAndHost(scheme, hostWithPort)
  1442. }
  1443. subURL = s.buildSingleURL(configuredSubURI, baseScheme, baseHostWithPort, subPath, subId)
  1444. subJsonURL = s.buildSingleURL(configuredSubJsonURI, baseScheme, baseHostWithPort, subJsonPath, subId)
  1445. subClashURL = s.buildSingleURL(configuredSubClashURI, baseScheme, baseHostWithPort, subClashPath, subId)
  1446. return subURL, subJsonURL, subClashURL
  1447. }
  1448. // getBaseSchemeAndHost determines the base scheme and host from settings or falls back to request values
  1449. func (s *SubService) getBaseSchemeAndHost(requestScheme, requestHostWithPort string) (string, string) {
  1450. subDomain, err := s.settingService.GetSubDomain()
  1451. if err != nil || subDomain == "" {
  1452. return requestScheme, requestHostWithPort
  1453. }
  1454. // Get port and TLS settings
  1455. subPort, _ := s.settingService.GetSubPort()
  1456. subKeyFile, _ := s.settingService.GetSubKeyFile()
  1457. subCertFile, _ := s.settingService.GetSubCertFile()
  1458. // Determine scheme from TLS configuration
  1459. scheme := "http"
  1460. if subKeyFile != "" && subCertFile != "" {
  1461. scheme = "https"
  1462. }
  1463. // Build host:port, always include port for clarity
  1464. hostWithPort := fmt.Sprintf("%s:%d", subDomain, subPort)
  1465. return scheme, hostWithPort
  1466. }
  1467. // buildSingleURL constructs a single URL using configured URI or base components
  1468. func (s *SubService) buildSingleURL(configuredURI, baseScheme, baseHostWithPort, basePath, subId string) string {
  1469. if configuredURI != "" {
  1470. return s.joinPathWithID(configuredURI, subId)
  1471. }
  1472. baseURL := fmt.Sprintf("%s://%s", baseScheme, baseHostWithPort)
  1473. return s.joinPathWithID(baseURL+basePath, subId)
  1474. }
  1475. // joinPathWithID safely joins a base path with a subscription ID
  1476. func (s *SubService) joinPathWithID(basePath, subId string) string {
  1477. if strings.HasSuffix(basePath, "/") {
  1478. return basePath + subId
  1479. }
  1480. return basePath + "/" + subId
  1481. }
  1482. // BuildPageData parses header and prepares the template view model.
  1483. // BuildPageData constructs page data for rendering the subscription information page.
  1484. func (s *SubService) BuildPageData(subId string, hostHeader string, traffic xray.ClientTraffic, lastOnline int64, subs []string, subURL, subJsonURL, subClashURL string, basePath string, subTitle string, subSupportUrl string) PageData {
  1485. download := common.FormatTraffic(traffic.Down)
  1486. upload := common.FormatTraffic(traffic.Up)
  1487. total := "∞"
  1488. used := common.FormatTraffic(traffic.Up + traffic.Down)
  1489. remained := ""
  1490. if traffic.Total > 0 {
  1491. total = common.FormatTraffic(traffic.Total)
  1492. left := max(traffic.Total-(traffic.Up+traffic.Down), 0)
  1493. remained = common.FormatTraffic(left)
  1494. }
  1495. datepicker := s.datepicker
  1496. if datepicker == "" {
  1497. datepicker = "gregorian"
  1498. }
  1499. return PageData{
  1500. Host: hostHeader,
  1501. BasePath: basePath,
  1502. SId: subId,
  1503. Enabled: traffic.Enable,
  1504. Download: download,
  1505. Upload: upload,
  1506. Total: total,
  1507. Used: used,
  1508. Remained: remained,
  1509. Expire: traffic.ExpiryTime / 1000,
  1510. LastOnline: lastOnline,
  1511. Datepicker: datepicker,
  1512. DownloadByte: traffic.Down,
  1513. UploadByte: traffic.Up,
  1514. TotalByte: traffic.Total,
  1515. SubUrl: subURL,
  1516. SubJsonUrl: subJsonURL,
  1517. SubClashUrl: subClashURL,
  1518. SubTitle: subTitle,
  1519. SubSupportUrl: subSupportUrl,
  1520. Result: subs,
  1521. }
  1522. }
  1523. func getHostFromXFH(s string) (string, error) {
  1524. if strings.Contains(s, ":") {
  1525. realHost, _, err := net.SplitHostPort(s)
  1526. if err != nil {
  1527. return "", err
  1528. }
  1529. return realHost, nil
  1530. }
  1531. return s, nil
  1532. }