subService.go 47 KB

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