subService.go 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612
  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. stringFields := []string{
  946. "sessionPlacement", "sessionKey",
  947. "seqPlacement", "seqKey",
  948. "uplinkDataPlacement", "uplinkDataKey",
  949. "scMaxEachPostBytes",
  950. }
  951. for _, field := range stringFields {
  952. if v, ok := xhttp[field].(string); ok && len(v) > 0 {
  953. extra[field] = v
  954. }
  955. }
  956. // Headers — emitted as the {name: value} map upstream's struct
  957. // expects. The server runtime ignores this field, but the client
  958. // (consuming the share link) honors it. Drop any "host" entry —
  959. // host already wins as a top-level URL param.
  960. if rawHeaders, ok := xhttp["headers"].(map[string]any); ok && len(rawHeaders) > 0 {
  961. out := map[string]any{}
  962. for k, v := range rawHeaders {
  963. if strings.EqualFold(k, "host") {
  964. continue
  965. }
  966. out[k] = v
  967. }
  968. if len(out) > 0 {
  969. extra["headers"] = out
  970. }
  971. }
  972. if len(extra) == 0 {
  973. return nil
  974. }
  975. return extra
  976. }
  977. // applyXhttpExtraParams emits the full xhttp config into the URL query
  978. // params of a vless:// / trojan:// / ss:// link. Sets path/host/mode at
  979. // top level (xray's Build() always lets these win over `extra`) and packs
  980. // everything else into a JSON `extra` param. Also writes the flat
  981. // `x_padding_bytes` param sing-box-family clients understand.
  982. //
  983. // Without this, the admin's custom xPaddingBytes / sessionKey / etc. never
  984. // reach the client and handshakes are silently rejected with
  985. // `invalid padding (...) length: 0` — the client-visible symptom is
  986. // "xhttp doesn't connect" on OpenWRT / sing-box.
  987. //
  988. // Two encodings are written so every popular client can read at least one:
  989. //
  990. // - x_padding_bytes=<range> — flat param, understood by sing-box and its
  991. // derivatives (Podkop, OpenWRT sing-box, Karing, NekoBox, …).
  992. // - extra=<url-encoded-json> — full xhttp settings blob, which is how
  993. // xray-core clients (v2rayNG, Happ, Furious, Exclave, …) pick up the
  994. // bidirectional fields beyond path/host/mode.
  995. func applyXhttpExtraParams(xhttp map[string]any, params map[string]string) {
  996. if xhttp == nil {
  997. return
  998. }
  999. applyPathAndHostParams(xhttp, params)
  1000. if mode, ok := xhttp["mode"].(string); ok {
  1001. params["mode"] = mode
  1002. }
  1003. if xpb, ok := xhttp["xPaddingBytes"].(string); ok && len(xpb) > 0 {
  1004. params["x_padding_bytes"] = xpb
  1005. }
  1006. extra := buildXhttpExtra(xhttp)
  1007. if extra != nil {
  1008. if b, err := json.Marshal(extra); err == nil {
  1009. params["extra"] = string(b)
  1010. }
  1011. }
  1012. }
  1013. var kcpMaskToHeaderType = map[string]string{
  1014. "header-dns": "dns",
  1015. "header-dtls": "dtls",
  1016. "header-srtp": "srtp",
  1017. "header-utp": "utp",
  1018. "header-wechat": "wechat-video",
  1019. "header-wireguard": "wireguard",
  1020. }
  1021. var validFinalMaskUDPTypes = map[string]struct{}{
  1022. "salamander": {},
  1023. "mkcp-aes128gcm": {},
  1024. "header-dns": {},
  1025. "header-dtls": {},
  1026. "header-srtp": {},
  1027. "header-utp": {},
  1028. "header-wechat": {},
  1029. "header-wireguard": {},
  1030. "mkcp-original": {},
  1031. "xdns": {},
  1032. "xicmp": {},
  1033. "noise": {},
  1034. "header-custom": {},
  1035. }
  1036. var validFinalMaskTCPTypes = map[string]struct{}{
  1037. "header-custom": {},
  1038. "fragment": {},
  1039. "sudoku": {},
  1040. }
  1041. // applyKcpShareParams reconstructs legacy KCP share-link fields from either
  1042. // the historical kcpSettings.header/seed shape or the current finalmask model.
  1043. // This keeps subscription output compatible while avoiding panics when older
  1044. // keys are absent from modern inbounds.
  1045. func applyKcpShareParams(stream map[string]any, params map[string]string) {
  1046. extractKcpShareFields(stream).applyToParams(params)
  1047. }
  1048. func applyKcpShareObj(stream map[string]any, obj map[string]any) {
  1049. extractKcpShareFields(stream).applyToObj(obj)
  1050. }
  1051. type kcpShareFields struct {
  1052. headerType string
  1053. seed string
  1054. mtu int
  1055. tti int
  1056. }
  1057. func (f kcpShareFields) applyToParams(params map[string]string) {
  1058. if f.headerType != "" && f.headerType != "none" {
  1059. params["headerType"] = f.headerType
  1060. }
  1061. setStringParam(params, "seed", f.seed)
  1062. setIntParam(params, "mtu", f.mtu)
  1063. setIntParam(params, "tti", f.tti)
  1064. }
  1065. func (f kcpShareFields) applyToObj(obj map[string]any) {
  1066. if f.headerType != "" && f.headerType != "none" {
  1067. obj["type"] = f.headerType
  1068. }
  1069. setStringField(obj, "path", f.seed)
  1070. setIntField(obj, "mtu", f.mtu)
  1071. setIntField(obj, "tti", f.tti)
  1072. }
  1073. func extractKcpShareFields(stream map[string]any) kcpShareFields {
  1074. fields := kcpShareFields{headerType: "none"}
  1075. if kcp, ok := stream["kcpSettings"].(map[string]any); ok {
  1076. if header, ok := kcp["header"].(map[string]any); ok {
  1077. if value, ok := header["type"].(string); ok && value != "" {
  1078. fields.headerType = value
  1079. }
  1080. }
  1081. if value, ok := kcp["seed"].(string); ok && value != "" {
  1082. fields.seed = value
  1083. }
  1084. if value, ok := readPositiveInt(kcp["mtu"]); ok {
  1085. fields.mtu = value
  1086. }
  1087. if value, ok := readPositiveInt(kcp["tti"]); ok {
  1088. fields.tti = value
  1089. }
  1090. }
  1091. for _, rawMask := range normalizedFinalMaskUDPMasks(stream["finalmask"]) {
  1092. mask, _ := rawMask.(map[string]any)
  1093. if mask == nil {
  1094. continue
  1095. }
  1096. maskType, _ := mask["type"].(string)
  1097. if mapped, ok := kcpMaskToHeaderType[maskType]; ok {
  1098. fields.headerType = mapped
  1099. continue
  1100. }
  1101. switch maskType {
  1102. case "mkcp-original":
  1103. fields.seed = ""
  1104. case "mkcp-aes128gcm":
  1105. fields.seed = ""
  1106. settings, _ := mask["settings"].(map[string]any)
  1107. if value, ok := settings["password"].(string); ok && value != "" {
  1108. fields.seed = value
  1109. }
  1110. }
  1111. }
  1112. return fields
  1113. }
  1114. func readPositiveInt(value any) (int, bool) {
  1115. switch number := value.(type) {
  1116. case int:
  1117. return number, number > 0
  1118. case int32:
  1119. return int(number), number > 0
  1120. case int64:
  1121. return int(number), number > 0
  1122. case float32:
  1123. parsed := int(number)
  1124. return parsed, parsed > 0
  1125. case float64:
  1126. parsed := int(number)
  1127. return parsed, parsed > 0
  1128. default:
  1129. return 0, false
  1130. }
  1131. }
  1132. func setStringParam(params map[string]string, key, value string) {
  1133. if value == "" {
  1134. delete(params, key)
  1135. return
  1136. }
  1137. params[key] = value
  1138. }
  1139. func setIntParam(params map[string]string, key string, value int) {
  1140. if value <= 0 {
  1141. delete(params, key)
  1142. return
  1143. }
  1144. params[key] = fmt.Sprintf("%d", value)
  1145. }
  1146. func setStringField(obj map[string]any, key, value string) {
  1147. if value == "" {
  1148. delete(obj, key)
  1149. return
  1150. }
  1151. obj[key] = value
  1152. }
  1153. func setIntField(obj map[string]any, key string, value int) {
  1154. if value <= 0 {
  1155. delete(obj, key)
  1156. return
  1157. }
  1158. obj[key] = value
  1159. }
  1160. // applyFinalMaskParams exports the finalmask payload as the compact
  1161. // `fm=<json>` share-link field used by v2rayN-compatible clients.
  1162. func applyFinalMaskParams(finalmask map[string]any, params map[string]string) {
  1163. if fm, ok := marshalFinalMask(finalmask); ok {
  1164. params["fm"] = fm
  1165. }
  1166. }
  1167. func applyFinalMaskObj(finalmask map[string]any, obj map[string]any) {
  1168. if fm, ok := marshalFinalMask(finalmask); ok {
  1169. obj["fm"] = fm
  1170. }
  1171. }
  1172. func marshalFinalMask(finalmask map[string]any) (string, bool) {
  1173. normalized := normalizeFinalMask(finalmask)
  1174. if !hasFinalMaskContent(normalized) {
  1175. return "", false
  1176. }
  1177. b, err := json.Marshal(normalized)
  1178. if err != nil || len(b) == 0 || string(b) == "null" {
  1179. return "", false
  1180. }
  1181. return string(b), true
  1182. }
  1183. func normalizeFinalMask(finalmask map[string]any) map[string]any {
  1184. tcpMasks := normalizedFinalMaskTCPMasks(finalmask)
  1185. udpMasks := normalizedFinalMaskUDPMasks(finalmask)
  1186. quicParams, hasQuicParams := finalmask["quicParams"].(map[string]any)
  1187. if len(tcpMasks) == 0 && len(udpMasks) == 0 && !hasQuicParams {
  1188. return nil
  1189. }
  1190. result := map[string]any{}
  1191. if len(tcpMasks) > 0 {
  1192. result["tcp"] = tcpMasks
  1193. }
  1194. if len(udpMasks) > 0 {
  1195. result["udp"] = udpMasks
  1196. }
  1197. if hasQuicParams && len(quicParams) > 0 {
  1198. result["quicParams"] = quicParams
  1199. }
  1200. return result
  1201. }
  1202. func normalizedFinalMaskTCPMasks(value any) []any {
  1203. finalmask, _ := value.(map[string]any)
  1204. if finalmask == nil {
  1205. return nil
  1206. }
  1207. rawMasks, _ := finalmask["tcp"].([]any)
  1208. if len(rawMasks) == 0 {
  1209. return nil
  1210. }
  1211. normalized := make([]any, 0, len(rawMasks))
  1212. for _, rawMask := range rawMasks {
  1213. mask, _ := rawMask.(map[string]any)
  1214. if mask == nil {
  1215. continue
  1216. }
  1217. maskType, _ := mask["type"].(string)
  1218. if _, ok := validFinalMaskTCPTypes[maskType]; !ok || maskType == "" {
  1219. continue
  1220. }
  1221. normalizedMask := map[string]any{"type": maskType}
  1222. if settings, ok := mask["settings"].(map[string]any); ok && len(settings) > 0 {
  1223. normalizedMask["settings"] = settings
  1224. }
  1225. normalized = append(normalized, normalizedMask)
  1226. }
  1227. if len(normalized) == 0 {
  1228. return nil
  1229. }
  1230. return normalized
  1231. }
  1232. func normalizedFinalMaskUDPMasks(value any) []any {
  1233. finalmask, _ := value.(map[string]any)
  1234. if finalmask == nil {
  1235. return nil
  1236. }
  1237. rawMasks, _ := finalmask["udp"].([]any)
  1238. if len(rawMasks) == 0 {
  1239. return nil
  1240. }
  1241. normalized := make([]any, 0, len(rawMasks))
  1242. for _, rawMask := range rawMasks {
  1243. mask, _ := rawMask.(map[string]any)
  1244. if mask == nil {
  1245. continue
  1246. }
  1247. maskType, _ := mask["type"].(string)
  1248. if _, ok := validFinalMaskUDPTypes[maskType]; !ok || maskType == "" {
  1249. continue
  1250. }
  1251. normalizedMask := map[string]any{"type": maskType}
  1252. if settings, ok := mask["settings"].(map[string]any); ok && len(settings) > 0 {
  1253. normalizedMask["settings"] = settings
  1254. }
  1255. normalized = append(normalized, normalizedMask)
  1256. }
  1257. if len(normalized) == 0 {
  1258. return nil
  1259. }
  1260. return normalized
  1261. }
  1262. func hasFinalMaskContent(value any) bool {
  1263. switch v := value.(type) {
  1264. case nil:
  1265. return false
  1266. case string:
  1267. return len(v) > 0
  1268. case map[string]any:
  1269. for _, item := range v {
  1270. if hasFinalMaskContent(item) {
  1271. return true
  1272. }
  1273. }
  1274. return false
  1275. case []any:
  1276. return slices.ContainsFunc(v, hasFinalMaskContent)
  1277. default:
  1278. return true
  1279. }
  1280. }
  1281. func searchHost(headers any) string {
  1282. data, _ := headers.(map[string]any)
  1283. for k, v := range data {
  1284. if strings.EqualFold(k, "host") {
  1285. switch v.(type) {
  1286. case []any:
  1287. hosts, _ := v.([]any)
  1288. if len(hosts) > 0 {
  1289. return hosts[0].(string)
  1290. } else {
  1291. return ""
  1292. }
  1293. case any:
  1294. return v.(string)
  1295. }
  1296. }
  1297. }
  1298. return ""
  1299. }
  1300. // PageData is a view model for subpage.html
  1301. // PageData contains data for rendering the subscription information page.
  1302. type PageData struct {
  1303. Host string
  1304. BasePath string
  1305. SId string
  1306. Enabled bool
  1307. Download string
  1308. Upload string
  1309. Total string
  1310. Used string
  1311. Remained string
  1312. Expire int64
  1313. LastOnline int64
  1314. Datepicker string
  1315. DownloadByte int64
  1316. UploadByte int64
  1317. TotalByte int64
  1318. SubUrl string
  1319. SubJsonUrl string
  1320. SubClashUrl string
  1321. SubTitle string
  1322. SubSupportUrl string
  1323. Result []string
  1324. }
  1325. // ResolveRequest extracts scheme and host info from request/headers consistently.
  1326. // ResolveRequest extracts scheme, host, and header information from an HTTP request.
  1327. func (s *SubService) ResolveRequest(c *gin.Context) (scheme string, host string, hostWithPort string, hostHeader string) {
  1328. // scheme
  1329. scheme = "http"
  1330. if c.Request.TLS != nil || strings.EqualFold(c.GetHeader("X-Forwarded-Proto"), "https") {
  1331. scheme = "https"
  1332. }
  1333. // base host (no port)
  1334. if h, err := getHostFromXFH(c.GetHeader("X-Forwarded-Host")); err == nil && h != "" {
  1335. host = h
  1336. }
  1337. if host == "" {
  1338. host = c.GetHeader("X-Real-IP")
  1339. }
  1340. if host == "" {
  1341. var err error
  1342. host, _, err = net.SplitHostPort(c.Request.Host)
  1343. if err != nil {
  1344. host = c.Request.Host
  1345. }
  1346. }
  1347. // host:port for URLs
  1348. hostWithPort = c.GetHeader("X-Forwarded-Host")
  1349. if hostWithPort == "" {
  1350. hostWithPort = c.Request.Host
  1351. }
  1352. if hostWithPort == "" {
  1353. hostWithPort = host
  1354. }
  1355. // header display host
  1356. hostHeader = c.GetHeader("X-Forwarded-Host")
  1357. if hostHeader == "" {
  1358. hostHeader = c.GetHeader("X-Real-IP")
  1359. }
  1360. if hostHeader == "" {
  1361. hostHeader = host
  1362. }
  1363. return
  1364. }
  1365. // BuildURLs constructs absolute subscription and JSON subscription URLs for a given subscription ID.
  1366. // It prioritizes configured URIs, then individual settings, and finally falls back to request-derived components.
  1367. func (s *SubService) BuildURLs(scheme, hostWithPort, subPath, subJsonPath, subClashPath, subId string) (subURL, subJsonURL, subClashURL string) {
  1368. if subId == "" {
  1369. return "", "", ""
  1370. }
  1371. configuredSubURI, _ := s.settingService.GetSubURI()
  1372. configuredSubJsonURI, _ := s.settingService.GetSubJsonURI()
  1373. configuredSubClashURI, _ := s.settingService.GetSubClashURI()
  1374. var baseScheme, baseHostWithPort string
  1375. if configuredSubURI == "" || configuredSubJsonURI == "" || configuredSubClashURI == "" {
  1376. baseScheme, baseHostWithPort = s.getBaseSchemeAndHost(scheme, hostWithPort)
  1377. }
  1378. subURL = s.buildSingleURL(configuredSubURI, baseScheme, baseHostWithPort, subPath, subId)
  1379. subJsonURL = s.buildSingleURL(configuredSubJsonURI, baseScheme, baseHostWithPort, subJsonPath, subId)
  1380. subClashURL = s.buildSingleURL(configuredSubClashURI, baseScheme, baseHostWithPort, subClashPath, subId)
  1381. return subURL, subJsonURL, subClashURL
  1382. }
  1383. // getBaseSchemeAndHost determines the base scheme and host from settings or falls back to request values
  1384. func (s *SubService) getBaseSchemeAndHost(requestScheme, requestHostWithPort string) (string, string) {
  1385. subDomain, err := s.settingService.GetSubDomain()
  1386. if err != nil || subDomain == "" {
  1387. return requestScheme, requestHostWithPort
  1388. }
  1389. // Get port and TLS settings
  1390. subPort, _ := s.settingService.GetSubPort()
  1391. subKeyFile, _ := s.settingService.GetSubKeyFile()
  1392. subCertFile, _ := s.settingService.GetSubCertFile()
  1393. // Determine scheme from TLS configuration
  1394. scheme := "http"
  1395. if subKeyFile != "" && subCertFile != "" {
  1396. scheme = "https"
  1397. }
  1398. // Build host:port, always include port for clarity
  1399. hostWithPort := fmt.Sprintf("%s:%d", subDomain, subPort)
  1400. return scheme, hostWithPort
  1401. }
  1402. // buildSingleURL constructs a single URL using configured URI or base components
  1403. func (s *SubService) buildSingleURL(configuredURI, baseScheme, baseHostWithPort, basePath, subId string) string {
  1404. if configuredURI != "" {
  1405. return s.joinPathWithID(configuredURI, subId)
  1406. }
  1407. baseURL := fmt.Sprintf("%s://%s", baseScheme, baseHostWithPort)
  1408. return s.joinPathWithID(baseURL+basePath, subId)
  1409. }
  1410. // joinPathWithID safely joins a base path with a subscription ID
  1411. func (s *SubService) joinPathWithID(basePath, subId string) string {
  1412. if strings.HasSuffix(basePath, "/") {
  1413. return basePath + subId
  1414. }
  1415. return basePath + "/" + subId
  1416. }
  1417. // BuildPageData parses header and prepares the template view model.
  1418. // BuildPageData constructs page data for rendering the subscription information page.
  1419. 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 {
  1420. download := common.FormatTraffic(traffic.Down)
  1421. upload := common.FormatTraffic(traffic.Up)
  1422. total := "∞"
  1423. used := common.FormatTraffic(traffic.Up + traffic.Down)
  1424. remained := ""
  1425. if traffic.Total > 0 {
  1426. total = common.FormatTraffic(traffic.Total)
  1427. left := max(traffic.Total-(traffic.Up+traffic.Down), 0)
  1428. remained = common.FormatTraffic(left)
  1429. }
  1430. datepicker := s.datepicker
  1431. if datepicker == "" {
  1432. datepicker = "gregorian"
  1433. }
  1434. return PageData{
  1435. Host: hostHeader,
  1436. BasePath: basePath,
  1437. SId: subId,
  1438. Enabled: traffic.Enable,
  1439. Download: download,
  1440. Upload: upload,
  1441. Total: total,
  1442. Used: used,
  1443. Remained: remained,
  1444. Expire: traffic.ExpiryTime / 1000,
  1445. LastOnline: lastOnline,
  1446. Datepicker: datepicker,
  1447. DownloadByte: traffic.Down,
  1448. UploadByte: traffic.Up,
  1449. TotalByte: traffic.Total,
  1450. SubUrl: subURL,
  1451. SubJsonUrl: subJsonURL,
  1452. SubClashUrl: subClashURL,
  1453. SubTitle: subTitle,
  1454. SubSupportUrl: subSupportUrl,
  1455. Result: subs,
  1456. }
  1457. }
  1458. func getHostFromXFH(s string) (string, error) {
  1459. if strings.Contains(s, ":") {
  1460. realHost, _, err := net.SplitHostPort(s)
  1461. if err != nil {
  1462. return "", err
  1463. }
  1464. return realHost, nil
  1465. }
  1466. return s, nil
  1467. }